Appending to list from while loop Python 3 - list

How can I append user int inputs to a list with a while loop? So whenever the number the user inputs is bigger than zero will be added to the list, but when it is a negative number the while loop will break and will continue to the next action. I am a total beginner in python 3, I tried a few things but didn't work. Here is what I tried :
numbers=[]
number = int(input("Please input a number: "))
while number>=0:
numbers.append(number)
if number <0:
break

You have two logical errors there:
First, you're never re-prompting for the number once you enter the while loop. You need to get a new number inside the loop so that you decide what to do upon the next iteration (append to the list, or stop the loop).
Second, your test if number < 0 is superfluous. Your loop runs only as long as number is greater or equal to zero; so inside the loop, there's no way the number can be smaller than zero. The test at the while above is quite sufficient.
Personally I'd rewrite the loop into an endless loop while True: ... and inside the loop I'd first prompt for a number. If that number were <0, I'd break out of the loop. Else, the remainder of the loop would be to append the new number to your list.
But there are countless solutions. Good luck!

You could use a for-loop instead like this pseudo code
if number<0
// do nothing or something or whatever
else:
yourRange = range(0,number)
for count in yourRange:
numbers.append(number)

Related

If two digits are the same 0s then make 0 condition in C++ and Root

In my code, legends are running within a loop, and I am trying to show a graph with
0-10%
10-20%
and so on. The problem is when I write this code
legend->AddEntry(gr[i], Form("%d0-%d0 %%",i+0,i+1), "lep");
It shows
00-10%
10-20% etc
So how to not show 00, but 0 in the first line?
A small adaptation of the shown statement should be enough; use:
legend->AddEntry(gr[i], Form("%d-%d %%", i*10 , (i+1)*10), "lep");
Explanation:
Form("%d0-%d0 %%",i+0,i+1) seems to be some kind of string formatting, and i your loop variable which runs from 0 to 9, right? The shown Form statement just appends "0" hard-coded to the single digit in i; instead, you can multiply i by 10, resulting in the actual numbers you want printed; and since 10*0 is still 0, this will be a single digit still; so, replace the previous Form(...) call with Form("%d-%d %%", i*10, (i+1)*10) and you should have the result you want!
In case you're worrying that printing i*10 is "less efficient" than printing i with "0" suffix - don't. The formatting and output of the string is most probably orders of magnitude slower than the multiplication anyway, so any overhead of doing multiple multiplications is negligible.

printing a character when no other output was printed

How do I print a particular character when up to that point in my code, no condition has been satisfied?
Example :
If I have an array of 100 numbers and if I traverse the array by 'for' loop and do not find my number, how do I print a single line " Not Found " ?
I am using C++.
You would typically create a boolean variable before the loop, maybe called found and set it to false. If the number is found in the loop, you would set found to true. After the loop is done, you would use an if statement to test if found is false and, if found to be so, output the " Not Found " message.
There are other ways that are usually better. But this is the simplest one that everyone should learn first.

How to create a list of numbers 1-1000 to simplify?

I am working on a "Whats my number?" program (http://goo.gl/upgkZ2) as posted on reddit and I was wondering if there was a way I could have a list of numbers 1-1000 and remove groups of numbers that follow a certain criteria. I was wondering if there was any simpler way to do this?
You can create a list of 1-1000 in a simpler way by using:
tons = list(xrange(1000))
You don't actually need a list at all to solve this problem (well, find the two solutions to this problem). Loop over the numbers and continue (return to the top of the loop for the next iteration) for each condition that fails to be met:
for i in xrange(10,1001):
s_i = str(i)
if '1' in s_i or '7' in s_i:
continue
if sum([int(d) for d in s_i]) > 10:
continue
...
print i, 'satisfies the conditions.'
You need to use filter on the initial list removing each case one at a time
For efficiency, cut out the biggest ones first, like the last case removes 90% of the list
You can also use numpy to create an array:
import numpy as np
a=np.arange(1,1001)

User input ending loops on C++

I am trying to create something (I'm thinking probably a loop?) that will allow me to have the user enter several numbers and then enter something like "done" to get all the numbers added up.
for example if I have a float (call it x for now) they could enter "7 enter 5 enter 9 enter done enter" and it would add those numbers and make x that value. Where I am coming into problems is that I need the user to be able to be able to enter as many numbers as they want (between 1 and 70 as an example) without specifying how many numbers they want to enter, just entering something in when they are done.
Thank you all
You'll need to use an infinite loop (while (true) or for (;;)) to read the next input into a string.
Check if the string is done. If so, break the loop.
Then try to parse that string into a double (don't use float) with the function std::stod.
If the parsing fails, optionally print an error message like "Bad input, try again" and restart the loop. If the parsing succeeds, add the number to the counter and restart the loop.

Prime backwards in order

An emirp (prime spelled backwards) is a pime number whose reversal is also prime. Ex. 17 & 71. I have to write a program that displays the first 100 emirps. It has to display 10 numbers per line and align the numbers properly:
2 3 5 7 11 13 17 31 37 71
73 79 97 101 107 113 131 149 151 157.
I have no cue what I am doing and would love if anyone could dump this down for me.
It sounds like there are two general problems:
Finding the emirps.
Formatting the output as required.
Break down your tasks into smaller parts, and then you'll be able to see more clearly how to get the whole task done.
To find the emirps, first write some helper functions:
is_prime() to determine whether a number is prime or not
reverse_digits() to reverse the digits of any number
Combining these two functions, you can imagine a loop that finds all the numbers that are primes both forward and reversed. Your first task is complete when you can simply generate a list of those numbers, printing them to the console one per line.
Next, work out what format you want to use (it looks like a fixed format of some number of character spaces per number is what you need). You know that you have 100 numbers, 10 per line, so working out how to format the numbers should be straightforward.
Break the problem down into simpler sub-problems:
Firstly, you need to check whether a number is prime. This is such a common task that you can easily Google it - or try a naive implementation yourself, which may be better given that this is homework.
Secondly, you need to reverse the digits of a number. I'd suggest you figure out an algorithm for this on a piece of paper first, then implement it in code.
Put the two together - it shouldn't be that hard.
Format the results properly. Printing 10 numbers per line is something you should be able to figure out easily once the rest is done.
Once you have a simple version working you might be able to optimise it in some way.
A straight forward way of checking if a number is prime is by trying all known primes less than it and seeing if it divides evenly into that number.
Example: To find the first couple of primes
Start off with the number 2, it is prime because the only divisors are itself and 1, meaning the only way to multiple two numbers to get 2 is 2 x 1. Likewise for 3.
So that starts us off with two known primes 2 and 3. To check the next number we can check if 4 modulo 2 equals 0. This means when divide 2 into 4 there is no remainder, which means 2 is a factor of 4. Specifically we know 2 x 2 = 4. Thus 4 is not prime.
Moving on to the next number: 5. To check five we try 5 modulo 2 and 5 modulo 3, both of which equals one. So 5 is prime, add it to our list of known primes and then continue on checking the next number. This rather tedious process is great for a computer.
So on and so forth - check the next number by looping through all previous found primes and check if they divide evenly, if all previously found primes don't divide evenly, you have a new prime. Repeat.
You can speed this up by counting by 2's, since all even numbers are divisible by two. Also, another nice trick is you don't have to check any primes greater than the square root of the number, since anything larger would need a smaller prime factor. Cuts your loops in half.
So that is your algorithm to generate a large list of primes.
Collect a good chunk of them in an array, say the first 10,000 or so. And then loop through them, reverse the numbers and see if the result is in your array. If so you have a emirp, continue until you get the first 100 emirps
If the first 10,000 primes don't return 100 emirps. Move on to the next 10,000. Repeat.
For homework, I would use a fairly simplistic isPrime function, pseudo-code along the lines of:
def isPrime (num):
set testDiv1 to 2
while testDiv1 multiplied by testDiv1 is less than or equal to num:
testDiv2 = integer part of (num divided by testDiv1)
if testDiv1 multiplied by testDiv2 is equal to num:
return true
Add 1 to testDiv1
return false
This basically checks whether the number is evenly divisible by any number between 2 and the square root of the number, a primitive primality check. The reson you stop at the square root is because you would have already found a match below it if there was one above it.
For example 100 is 2 times 50, 4 times 25, 5 time 20 and 10 times 10. The next one after that would be 20 times 5 but you don't need to check 20 since it would have been found when you checked 5. Any positive number can be expressed as a product of two other positive numbers, one below the square root and one above (other than the exact square root case of course).
The next tricky bit is the reversal of digits. C has some nice features which will make this easier for you, the pseudo-code is basically:
def reverseDigits (num):
set newNum to zero
while num is not equal to zero:
multiply newnum by ten
add (num modulo ten) to newnum
set num to the integer part of (num divided by ten)
return newNum
In C, you can use int() for integer parts and % for the modulo operator (what's left over when you divide something by something else - like 47 % 10 is 7, 9 % 4 is 1, 1000 % 10 is 0 and so on).
The isEmirp will be a fairly simplistic:
def isEmirp (num):
if not isPrime (num):
return false
num2 = reverseDigits (num)
if not isPrime (num2):
return false
return true
Then at the top level, your code will look something like:
def mainProg:
create array of twenty emirps
set currEmirp to zero
set tryNum to two
while currEmirp is less than twenty
if isEmirp (tryNum):
put tryNum into emirps array at position currEmirp
add 1 to currEmirp
for currEmirp ranging from 0 to 9:
print formatted emirps array at position currEmirp
print new line
for currEmirp ranging from 10 to 19:
print formatted emirps array at position currEmirp
print new line
Right, you should be able to get some usable code out of that, I hope. If you have any questions of the translation, leave a comment and I'll provide pointers for you, rather than solving it or doing the actual work.
You'll learn a great deal more if you try yourself, even if you have a lot of trouble initially.