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.
Related
def prime_count(a, b):
for i in range(a,b):
if i % 2 != 0:
return sum(i)
else:
return 0 "
I am a beginner programmer, I have been practicing on some challenges on Edabit, small problems but that require some thinking (for me).
I am trying to count how many prime numbers are on a and b, they are already integers and there is no user input.
I am not very good at loops yet and thought this was going to be a good challenge to practice, what am I doing wrong? I keep getting int object is not iterable
If reference need, here is the link for the challenge.
Link : https://edabit.com/challenge/6QYwhZstMuHYtZRbT
it is an interesting problem that you are solving. You will have to run two-loops here. One to iterate from a to b and the inner loop to check if each element in a -->b is prime or not (the inner loop should run from 2 to j in [a,b).
def primecheck(a,b):
printlist=[]
if a > 1:
for i in range(a,b+1):
for j in range(2,i):
if i % j == 0:
break
else:
printlist.append(i)
if len(printlist) == 0:
return 0
else:
return len(printlist), printlist
Try this out.
As people say in the comment section, calling sum() is what's causing an error.
But, even if you somehow got that part right, you wouldn't quite get what you want. Maybe you were just trying a simple for loop to check if numbers are odd...?
Anyway, I normally like using Sieve of Eratosthenes to generate prime numbers because it's simple.
def sieve_of_eratosthenes(start, end):
if start > end:
raise AssertionError
# end = end + 1 # If end is inclusive, then uncomment this line.
if end < 2:
return 0
sieve = [i for i in range(2, end)] # Initialize an array of number from 2 to end.
size = len(sieve)
p = 2 # Initial prime.
count = 0
# This block implements Sieve of Eratosthenes.
while count < size:
for i in range(count, size):
num = sieve[i]
if num != p and num % p == 0:
sieve[i] = 0
if count == size-1:
break
count += 1
while sieve[count] == 0:
count += 1
if count == size-1:
break
p = sieve[count] # Update the next prime.
# This block calculates the numbers of primes between start and end.
num_of_primes = 0
for p in sieve:
if p == 0 or p < start:
continue
num_of_primes += 1
print(sieve)
return num_of_primes
sieve_of_eratosthenes(1, 100) # This should return 25.
So I'm writing some code for my class and have to have a list of floats that are input by a user and print them out with normal iteration and reverse iteration, and I have basically all of it done. But when it should ask multiple times for the user input, it only asks one time then prints everything out and finishes without asking multiple times.
Any help would be appreciated as to why it isnt asking multiple times for input even though I have a for loop?
Is there an easier way to get a list of floats from user input that I don't know about?
Thanks
emptyList = []
userInput = high = low = total = float(input("Input a float > "))
emptyList.append(userInput)
for y in range(len(emptyList)-1):
userInput = float(input("Input a float > "))
emptyList.append(userInput)
total += emptyList
if userInput > high:
high = userInput
if userInput < low:
low = userInput
avg = total / len(emptyList)
above_avg = below_avg = 0
for y in range(len(emptyList)):
if emptyList[y] > avg:
above_avg += 1
if emptyList[y] < avg:
below_avg += 1
I checked your logic and according to that you are running your first for loop to the length of emptyList-1 so, after adding one element your emptylist's length becomes 1 and 1-1=0 so, your for loop will work only to 0th index and after that it will break.
I tried this
a=[]
b = []
t=0
count = 0
total = 0
for i in range(0,5):
x= float(input())
count = count + 1
total = total+ x
a.append(x)
print(count)
for i in range(count-1,-1,-1):
print('Aya')
print (i)
b.append(a[i])
for i in range(0,count-1):
for j in range(i,count):
if(a[i]>a[j]):
t=a[i]
a[i]=a[j]
a[j]=t
print(a)
print(b)
print(total)
print(total/count)
print(a[0])
and found it working perfectly fine for me and my for loop is taking values on every iteration.
You may try like this:
n = int(input("Number of inputs: "))
emptyList = []
while n:
userInput = float(input("Enter a Float > "))
emptyList.append(userInput)
n-=1
print(emptyList)
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.
I am trying to put together a simple program which could work out n prime numbers. I would like to do this by using a nested for loop, where one would go through the numbers, and another would divide that number by all of the numbers up to it to see if it would be divisible by anything.
The problem I am having is that in the main for loop, I need to start it at 2, seeing as 1 would mess up the system and I don't want it to be considered a prime. For the loop to have a starting number however, it also needs an ending number which is difficult in this instance as it is hard to generate the largest prime that will be needed prior to the loop working.
Here's the program that I am using right now. Where I have marked X is where I need to somehow put an ending number for the For Loop. I guess it would be much simpler if I let the For Loop be completely open, and simply take out anything that '1' would produce in the loop itself, but this feels like cheating and I want to do it right.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in range(2,X):
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
Thanks for your help!
You can step through an unlimited amount of numbers using a generator object.
Insert the following somewhere near the top of your code:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
What this does is it creates a function for constructing generator objects that "pause" whenever they reach the yield statement to "yield" whatever value is specified by the yield command, and then continue to execute from the next line beneath the yield statement.
Python's own range function is itself an example of a generator, and is roughly equivalent to (ignoring the step argument and other peculiarities)
def range(start, end):
i = start
while i < end:
yield i
i += 1
So your program would then look like this:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in infinite_number_generator():
check = 0
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
if i == limit:
break
I should also point out that the code you provided is buggy - it will never stop printing because there's no checking whether you've found your limit number of primes yet or not.
This should do what you want.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
counter = 0
i = 2
while counter < limit:
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
counter += 1
print (i)
i += 1
In your code you start i with 2 and always increment by 1, so the i will always remain greater than 1, therefore the test if i > 1 is useless.
For efficiency you can stop the check at the square of i or i/2 (no divisors in [i/2 + 1, i[ ).
you can update your code as follow:
n = int(input("Enter the amount of Prime Numbers: "))
FoundPrimes = 0
i = 2
while FoundPrimes < n:
isPrime = True
for j in range(2,1 + i//2):
if (i % j) == 0:
isPrime = False
if isPrime:
FoundPrimes += 1
print(i, end = '\t')
i += 1
What is wrong with this code to find the primes of a number and store them in a list?
def primes(num):
res = num
i = 2
z = []
while res != 1:
if num%i == 0:
z.append(i)
res = num/i
else:
i += 1
if num=4 and i=2 you got an infinite loop, cause "i" and "res" never changes ...
It's python compliant, but your algorithm is not good.
Try res = res/i.