My teacher wants me to find the median of 10 inputs from the user by using iterations.
This is how I used iterations to find the sum, number of odd numbers, the max, and the number of prime numbers. But I'm stuck on finding the median.
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
for i in range(10):
x=float(input("Please enter a number")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
import math
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
my_list =[]
for i in range(10):
x=float(input("Please enter a number: ")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
my_list.append(x)
my_list.sort()
size =len(my_list)
if size == 1:
median = my_list[0]
elif size % 2 == 0:
size = int(size/2)
median=(my_list[size-1]+my_list[size])/2
else:
median = my_list[int(size / 2)]
print("sum is ", sum, ",odd is ", odd, ",temp is ", temp, ",prime is ", prime, "median is ", median)
Main()
First of all, as a user pointed out in a comment to your question, your method to determine prime numbers is not correct. You only should increase that counter after all factors have been checked, not after each one.
There are a few questions on StackOverflow that show how to calculate primes in python; here is a slightly improved version of your code with that error fixed (and some style improvement suggestions):
def main():
sum = 0
counter_odd = 0
max_num = None
min_num = None
counter_prime = 0
median = 0
for i in range(10):
x = float(input("Please enter a number"))
sum += x
if x % 2 != 0:
counter_odd += 1
if max_num is None or max_num < x:
max_num = x
if min_num is None or min_num > x:
min_num = x
if x == 0 or x == 1:
counter_prime += 1
elif x > 1:
if not any(x % d == 0 for d in range(2, int(math.sqrt(x)) + 1)):
counter_prime += 1
As to your main question: there are several questions on SO about finding medians in unsorted lists (that would be very similar to searching for medians without having the whole list at the beginning). Maybe search for that without the Python tag, so you get to see some algorithms without tying to a specific language.
For example, in this question you can find the suggestion to use the median of medians approach (Wikipedia).
Related
I have some code where I must find the multiples of number 3 and then summarize them
I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found.
I have tried so many times and tried to find the solution on google, but could not find
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them
It's easier than you think:
sum(range(0, 1000, 3))
Explanation:
range is defined as such: range([start], end[, step]) so range(0, 1000, 3) means go from 0 to 1000 in steps of 3
The sum function will sum over any iterable (which includes range)
You need a variable to hold the sum (If you are in learning stage):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit:
To answer your comment use condition or condition:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result variable to which you can keep adding:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter and sum:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)
I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)
Please could you help correct this code! It's for finding all perfect numbers below the set limit of 10,000, I've used comments to explain what I'm doing. Thanks!
#Stores list of factors and first perfect number
facs = []
x = 1
#Defines function for finding factors
def findfactors(num):
#Creates for loop to find all factors of num
for i in range(1, num + 1):
if num % i == 0:
#Stores factor in facs
facs.append(i)
#Activates loop
while x < 10000:
#Finds factors of x and appends them to list
findfactors(x)
#Finds sum of list
facsum = sum(facs)
#Makes decision based on sum of factors and original number
if facsum == x:
#Ouputs and increases x
print(x)
x += 1
else:
#Increases x
x += 1
In number theory, a perfect number is a positive integer that is equal
to the sum of its proper positive divisors, that is, the sum of its
positive divisors excluding the number itself (also known as its
aliquot sum). The first perfect number is 6. The next perfect number
is 28. This is followed by the perfect numbers 496 and 8128.
(Wikipedia)
You have to exclude the number itself from the factors list.
Also, for each x you have to start with the empty facs and then append to it. You don't want previous numbers factors in that list. The following code works.
x = 1
def findfactors(num):
facs = []
for i in range(1, num):
if num % i == 0:
facs.append(i)
return facs
while x < 10000:
facs = findfactors(x)
facsum = sum(facs)
if facsum == x:
print(x)
x += 1
else:
x += 1
This is a simpler implementation of your logic.
x = 1
#Defines function for finding factors
def isperfectnum(num):
sum=0
#Creates for loop to find all factors of num
for i in range(1, num ):
if num % i == 0:
sum=sum+i
if sum==num:
return TRUE
else
return FALSE
#Activates loop
while x < 10000:
#Finds perfect numbers
if isperfectnum(x):
print(x)
x=x+1
Found the problem!
Should have been:
for i in range(1, num - 1)
Rather than:
for i in range(1, num + 1)
Thanks to all contributors!
intialize list inside the def and return and the range should not include the original num so range would be from 1 to num which includes 1 but excludes orginal num so it will generate range from 1 to num-1
#Stores list of factors and first perfect number
x = 1
#Defines function for finding factors
def findfactors(num):
facs = []
for i in range(1, num):
if num % i == 0:
#Stores factor in facs
facs.append(i)
return facs
#Activates loop
while x < 1000:
#Finds factors of x and appends them to list
facs=findfactors(x)
#Finds sum of list
facsum = sum(facs)
#Makes decision based on sum of factors and original number
if facsum == x:
#Ouputs and increases x
print(x)
x+= 1
Much faster than generating list
Approach from What is the most efficient way of finding all the factors of a number in Python?
#Stores list of factors and first perfect number
x = 1
#Defines function for finding factors
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
#Activates loop
while x < 10000:
#Finds factors of x and appends them to list
facs=factors(x)
facs.remove(x) # remove original number as it is not required further
#Finds sum of list
facsum = sum(facs)
#Makes decision based on sum of factors and original number
if facsum == x:
#Ouputs and increases x
print(x)
x+= 1
i am creating a python program, to allow a user to input numbers and find the total, average, highest and lowest of the numbers inputted. my teacher has told me to improve the program by removing the first and last number(which i have now done ) inputted into the list and not to use the min and max functions.I am confused on how doing so.
totalList=[]
TotalNum = int(input("Please enter how many numbers are to be entered:"))
Change=TotalNum
Input=0
Total=0
while TotalNum>0:
TotalNum = TotalNum - 1
Input = int(input("Enter Number: "))
totalList.append(Input)
Total = Total +Input
while 1 == 1:
totalList = totalList[1:-1]
TotalList = totalList
print("Total:" ,Total)
print("Average:",Total/Change)
print("Highest:",max(TotalList))
print("Lowest:",min(TotalList))
When removing the first and last numbers of the list, since lists are zero-indexed in python (meaning the first number is at index 0), you'll want to change totalList = totalList[1:-1] to start from 0, making it totalList = totalList[0:-1].
However, we may want to use those first and last numbers when searching for the maximum and minimum numbers in the list. So, I think what your teacher may have meant was to use the first and last numbers as min and max, and update them as you search through the list.
I will show you finding the minimum, and then using the same idea you can find the maximum.
min_num = TotalList[0]
max_num = TotalList[-1]
for i in TotalList:
if i < min_num:
i = min_num
# print("Highest:",max_num)
print("Lowest:", min_num)
Note: You don't need the infinite while 1 == 1: loop, delete it.
def find_low(nums, index):
lowest = None
lowNum = float("inf")
for num in nums:
if num < lowNum:
lowNum = num
lowest = num
highest = None
highNum = -float("inf")
for num in nums:
if num > highNum:
highNum = num
highest = num
Used = []
newL = []
for num in range(lowest, highest + 1):
if num in nums and not num in Used:
newL.append(num)
Used.append(num)
return newL[index - 1]
numbers = [1,2,3,4,5]
print(find_low(numbers, 1))
#The second paramter, 1, finds the lowest number, not 0
I'm having trouble with my code. The question is:
"By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?"
This is what it looks like:
div = 10001
i = 2
count = 0
prime = 0
now = []
while count < div:
for x in range (2,i+1):
if len(now) ==2:
break
elif i%x == 0:
now.append(x)
if len(now)==1:
prime = i
count += 1
now = []
i+=1
print(prime)
I have tried div up to 1000 and it seems to work fine(for div 1000 I receive 7919). However, when I try div = 10001 I get nothing, not even errors. If someone would help me out I would really appreciate it.
Thank you.
# 7 10001st prime
import itertools
def is_prime(n):
for i in range(2, n//2 + 1):
if n % i == 0:
return False
else:
continue
return True
p = 0
for x in itertools.count(1):
if is_prime(x):
if p == 10001:
print(x)
break
p += 1
Try this code:
prime_list = lambda x:[i for i in xrange(2, x+1) if all([i%x for x in xrange(2, int(i**0.5+1))])][10000]
print prime_list(120000)
Lambda in Python defines an anonymous function and xrange is similar to range, defining a range of integer numbers. The code uses list comprehension and goes through the numbers twice up to the square root of the final number (thus i**0.5). Each number gets eliminated if it is a multiple of the number that's in the range count. You are left with a list of prime numbers in order. So, you just have to print out the number with the right index.
With just some simple modifications (and simplifications) to your code, you can compute the number you're looking for in 1/3 of a second. First, we only check up to the square root as #Hashman suggests. Next, we only test and divide by odd numbers, dealing with 2 as a special case up front. Finally, we toss the whole now array length logic and simply take advantage of Python's break logic:
limit = 10001
i = 3
count = 1
prime = 2
while count < limit:
for x in range(3, int(i ** 0.5) + 1, 2):
if i % x == 0:
break
else: # no break
prime = i
count += 1
i += 2
print(prime)
As before, this gives us 7919 for a limit of 1000 and it gives us 104743 for a limit of 10001. But this still is not as fast as a sieve.
m=0
n=None
s=1
while s<=10001:
for i in range(1,m):
if m%i==0:n=i
if n==1:print(m,'is prime',s);s+=1
m+=1