While Loops - Increment a List - python

I'm stuck trying to figure out this while loop. It seemed simple at first but I keep running into errors. I think I just haven't used python in a while so it's hard to get back into the gist of things.
Write a while loop that will add 100 numbers to a list, starting from the number 100 and incrementing by 2 each time. For example, start from 100, then the next number added will be 102, then 104 and so on.
I have this so far;
count = 0
while count < 99:
count += 1
numbers.append(len(numbers)+2)
for x in numbers:
print(x)
But that is simply giving me 0-100 printed out when I want it to be 2,4,6,8,10,...

numbers = []
index = 0
number = 100
while index < 100:
number += 2
index += 1
numbers.append(number)
for x in numbers:
print(x)

With a few modifications, and using a while loop as per your exercise:
numbers = []
count = 0
while count < 100:
numbers.append(100 + (2*count))
count += 1
for x in numbers:
print(x)
Or with a for loop:
numbers = []
for i in range(100):
numbers.append(100 + (2*i))
for x in numbers:
print(x)
Or as a list comprehension:
numbers.extend([(100 + (2*el)) for el in range(100)])
Or as a recursion:
numbers = []
def rec(num):
if num < 100:
numbers.append(100 + (2*num))
rec(num + 1)
rec(0)

Something like this:
numbers = []
while len(numbers) != 100:
if len(numbers) > 0:
numbers.append(numbers[-1] + 2)
else:
numbers.append(100)
Little explanation:
You loop until your list has 100 elements. If list is empty (which will be at the beginning), add first number (100, in our case). After that, just add last number in list increased by 2.

Try numbers.extend(range(100, 300, 2)). It's a much shorter way to do exactly what you're looking for.
Edit: For the people downvoting, can you at least leave a comment? My initial response was prior to the question being clarified (that a while loop was required). I'm giving the pythonic way of doing it, as I was unaware of the requirement.

Related

Python code returns nothing after putting input

I am absolutely clueless because I ran this code earlier and it worked fine. I don't remember changing anything. Once I enter my input it returns empty but is still running the program.
import random
print("This program finds the smallest difference between any two elements in"+
" a randomly generated list of integers, using two different algorithms with"+
" different Big-O efficiency.\n")
min_ran = int(input("Enter random min range:"))
max_ran = int(input("Enter random max range:"))
len_list = int(input("Enter length of list:"))
counter = 1
output_list = []
while counter <= len_list:
output_list.append(random.randint(min_ran,max_ran))
def algorithm1():
diff = 10**20
for i in range(len_list-1):
for j in range(i+1,len_list):
if abs(output_list[i]-output_list[j]) < diff:
diff = abs(output_list[i]-output_list[j])
return diff
def algorithm2():
mid = len_list // 2
list1 = output_list[:mid]
list2 = output_list[mid:]
list1.sort()
list2.sort()
ans = 10**20
i = j = 0
while i < len(list1) and j < len(list2):
ans = min(ans,abs(list1[i]-list2[j]))
if list1[i] < list2[j]:
i += 1
else:
j +=1
return ans
print("\nList:",output_list)
print("List length:",len_list)
print(algorithm1())
print(algorithm2())
At line 12 you're creating an infinite loop unless the len_list input is under 1
while counter <= len_list:
output_list.append(random.randint(min_ran,max_ran))
Adding counter += 1 into the loop seems to fix it.
That seemed to be the only bug i ran into running the code.
Though i'd highly suggest using a for loop in this case instead of a while loop to prevent infinite loops such as that
you don't change your counter. it will cause an infinite loop.
counter = 1
output_list = []
while counter <= len_list:
output_list.append(random.randint(min_ran,max_ran))
try:
output_list = [random.randint(min_ran,max_ran) for x in range(0,len_list)]
side note: I'd recommend using some kind of version control software such as git in order to avoid unwanted changes that cause small logical bugs.

I can't get count to work in my Python code

I'm trying to create a code that will print every number in a range set by the user, and then identify how many numbers in that range are odd numbers and how many are even.
I've tried a few different formats, but I'm very much a beginner and can't seem to nail down where I'm going wrong. I'm trying to keep the code as simple as possible.
for i in range(x,y+1):
print(i)
range = (x,y+1)
count_odd = 0
count_even = 0
for n in range:
if n%2==0:
count_even = count_even+1
else:
count_odd = count_odd+1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Currently when I run this, even numbers always comes to 0 and odd to 2.
On line 4 you have:
range = (x,y+1)
This is the tuple (x, y+1) not the range between them. So when you loop through it you are only looping through those two numbers. I assume in your case they are both odd. I would recommend removing that line and starting your second for loop like this:
for n in range(x, y + 1):
range is a builtin function, which returns an iterable from [start, end). You likely want something like:
count_odd = 0
count_even = 0
for n in range(x,y+1):
if n % 2 == 0:
count_even = count_even + 1
else:
count_odd = count_odd + 1
print("Number of even numbers :", count_even)
print("Number of odd numbers :", count_odd)
There's no point for a loop. If your range consists of even elements, then half of values is even and half is odd. If it consists og odd elements and starts from odd value then half+1 is odd and half-1 is even. It starts with even value then it's opposite.

In JES which I believe is Python 2, how do I do a nested for loop to count reps until a list is sorted

I am taking a beginners programming class using JES which I believe is Python 2.
My teacher has asked that we create an empty list and then add random numbers to it, then sort it from lowest to highest. That part I have done correctly. The extra credit is to add a nested for loop that will count the reps it takes to sort the list.
This is what I have:
from random import *
def main():
# create list of 25 (this can be changed to number of your choice) random numbers from -100 to 100
# print list with message "list before shuffling"
numList = []
count = 0
while count < 15:
num = randint( -100 , 100 )
numList.append(num)
count = count + 1
printNow("the List before shuffling: " +str(numList))
n = len(numList)
add = 0
# Randomly shuffle list with items only moving if a lower number is being switched with a larger number
# do this 1000 times ( this can be changed to number of your choice)
# print list with message "list after shuffling"
for reps in range (0 , 500):
i = randrange(0, n)
j = randrange(0, n)
# extra credit, add nested for loop to count number of reps it takes to sort the list
for sort in range(0, len(numList)):
for item in range(sort+1, len(numList)):
while numList[sort] < numList[item] or add < reps:
add = add + 1
if i < j:
if numList[i] > numList[j]:
temp = numList[i]
numList[i] = numList[j]
numList[j] = temp
elif j < i:
if numList[i] < numList[j]:
temp = numList[j]
numList[j] = numList[i]
numList[i] = temp
print(" List was sorted in " + str(add) + " reps.")
printNow("The List after shuffling: " +str(numList))
My teacher says that I have too many loops in my extra credit section. I am stuck and am looking for someone to explain what I am doing wrong.
I DO NOT want someone to solve it for me, but tell me what I am doing wrong.
I don't believe that is any reason for you to put a while loop within your two-level for loop. With two for loops, you should be able to iterate through your list and use some other conditional-checker (hint: that you have already used in this script you've shown) to determine whether the current list element is in the right spot (for the moment - may be shuffled around later). You could look in to:
bubble sort

Why does this code not go to an infinite loop? (Python)

I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.
Try to change N to number:
while count < N:
while count < number:
Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

How can I Keep the following program running until it becomes a single digit number?

I want to write a program that can calculate the sum of an integer as well as count its digits . It will keep doing this until it becomes a one digit number.
For example, if I input 453 then its sum will be 12 and digit 3.
Then it will calculate the sum of 12=1+2=3 it will keep doing this until it becomes one digit. I did the first part but i could not able to run it continuously using While . any help will be appreciated.
def main():
Sum = 0
m = 0
n = input("Please enter an interger: ")
numList = list(n)
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
main()
It is not the most efficient way, but it doesn't matter much here; to me, this is a problem to elegantly solve by recursion :)
def sum_digits(n):
n = str(n)
if int(n) < 10:
return n
else:
count = 0
for c in n:
count += int(c)
return sum_digits(count)
print sum_digits(123456789) # --> 9 # a string
A little harder to read:
def sum_digits2(n):
if n < 10:
return n
else:
return sum_digits2(sum(int(c) for c in str(n))) # this one returns an int
There are a couple of tricky things to watch out for. Hopefully this code gets you going in the right direction. You need to have a conditional for while on the number of digits remaining in your sum. The other thing is that you need to covert back and forth between strings and ints. I have fixed the while loop here, but the string <-> int problem remains. Good luck!
def main():
count = 9999
Sum = 0
m = 0
n = input("Please enter an integer: ")
numList = list(n)
while count > 1:
count = len(numList)
for i in numList:
m = int(i)
Sum = m+Sum
print(Sum)
print(count)
# The following needs to be filled in.
numlist = ???
main()
You can do this without repeated string parsing:
import math
x = 105 # or get from int(input(...))
count = 1 + int(math.log10(x))
while x >= 10:
sum = 0
for i in xrange(count):
sum += x % 10
x /= 10
x = sum
At the end, x will be a single-digit number as described, and count is the number of original digits.
I would like to give credit to this stackoverflow question for a succinct way to sum up digits of a number, and the answers above for giving you some insight to the solution.
Here is the code I wrote, with functions and all. Ideally you should be able to reuse functions, and here the function digit_sum(input_number) is being used over and over until the size of the return value (ie: length, if sum_of_digits is read as a string) is 1. Now you can use the while loop to keep checking till the size is what you want, and then abort.
def digit_sum(input_number):
return sum(int(digit) for digit in str(input_number))
input_number = input("Please enter a number: ")
sum_of_digits = digit_sum(input_number)
while(len(str(sum_of_digits)) > 1):
sum_of_digits = digit_sum(input_number)
output = 'Sum of digits of ' + str(input_number) + ' is ' + str(sum_of_digits)
print output
input_number = sum_of_digits
this is using recursive functions
def sumo(n):
sumof = 0
while n > 0:
r = n%10 #last digit
n = n/10 # quotient
sumof += r #add to sum
if sumof/10 == 0: # if no of digits in sum is only 1, then return
return sumof
elif sumof/10 > 0: #else call the function on the sumof
sumo(sumof)
Probably the first temptation would be to write
while x > 9:
x = sum(map(int, str(x)))
that literally means "until there is only one digit replace x by the sum of its digits".
From a performance point of view however one should note that computing the digits of a number is a complex operation because Python (and computers in general) store numbers in binary form and each digit in theory requires a modulo 10 operation to be extracted.
Thus if the input is not a string to begin with you can reduce the number of computations noting that if we're interested in the final sum (and not in the result of intermediate passes) it doesn't really matter the order in which the digits are summed, therefore one could compute the result directly, without converting the number to string first and at each "pass"
while x > 9:
x = x // 10 + x % 10
this costs, from a mathematical point of view, about the same of just converting a number to string.
Moreover instead of working out just one digit however one could also works in bigger chunks, still using maths and not doing the conversion to string, for example with
while x > 99999999:
x = x // 100000000 + x % 100000000
while x > 9999:
x = x // 10000 + x % 10000
while x > 99:
x = x // 100 + x % 100
while x > 9:
x = x // 10 + x % 10
The first loop works 8 digits at a time, the second 4 at a time, the third two and the last works one digit at a time. Also it could make sense to convert the intermediate levels to if instead of while because most often after processing n digits at a time the result will have n or less digits, leaving while loops only for first and last phases.
Note that however the computation at this point is so fast that Python general overhead becomes the most important part and thus not much more can be gained.
You could define a function to find the sum and keep updating the argument to be the most recent sum until you hit one digit.
def splitSum(num):
Sum = 0
for i in str(num):
m = int(i)
Sum = Sum + m
return str(Sum)
n = input("Please enter an integer: ")
count = 0
while count != 1:
Sum = splitSum(n)
count = len(Sum)
print(Sum)
print(count)
n = Sum

Categories