Summary of unknown amounts of integers in a list - python

How can I transfer the list that I take from the user as unknown amount of integers?
f.sum(i[0],i[-1])
def sum(*args):
total=0
for a in args:
total+=a
if a is "q":
break
print(total)
while True:
print("sum")
y = input("Number: ")
if int(y) is 0:
print(i)
f.sum(i[0],i[-1])
break
i.append(int(y))
Can not take unknown amount in f.sum(args) part
Given 2,3,5
Expected: 10
Result: 5
With i[0], i[1]

I think your main problem resides in what you are passing to the function. You are sending the first and last element, but (I think) you want to send the list:
while True:
i = []
print("sum")
y = int(input("Number: "))
if y == 0:
print(i)
print_sum(i)
break
i.append(y)
Also, it doesn't make sense to check in the sum if a value "q", because you are assuming (when you add) they are integers:
# Renamed to "print_sum", since I would expect "sum" to return it, and not print it
def print_sum(*args):
total=0
for a in args:
total+=a
print(total)
Note: I wrote this in the comments initally, but I thought it would be clearer in a comment.
Edit: Do you have to implement your own sum? Python already has one

Related

Finding whether element entering in a list is duplicate or unique, while the program is running

so, I came across this question, where I have to create a list, take the elements as input from the user. After doing so, I have to check whether the elements entered by the user are 'Unique' or 'Duplicate', and this has to be done while the program is running. i.e if the input entered is duplicate, then I have to terminate the program then and there, otherwise proceed.
I have written the following code (Python):
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0,num):
q = int(input('element %d: '%(i+1)))
list.append(q)
print(list)
cnt = 0
for i in range(0,num):
if(list[i]==q):
cnt = cnt+1
if(cnt>1):
print('Duplicate')
else:
cnt = cnt+0
if(cnt==0):
print('Unique')
print('\nProgram Terminated!')
The thing is that, I know that I might have to use the break statement in the loop where I check whether the values are equal, but I somehow can't place it correctly.
Thank you! :)
If you want to check each time the user puts in a new element, i think this is the solution to your question:
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0, num):
q = int(input('element %d: ' % (i+1)))
if q not in list:
print('Unique')
list.append(q)
else:
print('Duplicate')
break
print(list)
print('\nProgram Terminated!')

How to set the data type of a function parameter in python?

def recursiveSum(lst):
if len(lst) == 0:
return 0
else:
#print(str(type(lst))+'\n')
num = lst[len(lst)-1]
return recursiveSum(lst.pop()) + num
size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
lst.append(input("Enter number "+str(i+1)+" = " ))
print(recursiveSum(lst))
In this code i am trying to find sum of list of numbers recursively , this is my first attempt with recursions , i think my approach and algorithm was correct , the list when passed to the recursiveSum() function somehow makes it string in the else part , the commented line when executed ends up printing
class 'list'
class 'str'
I don't understand how the print statement prints both list and str.
Can someone explain this ?
I think you forgot to type cast to int when input:
lst.append(int(input("Enter number "+str(i+1)+" = " )))
Two problems:
you do not convert your inputs into numerics/integers
you recurse using the popped element not the remaining list
Fix:
def recursiveSum(lst):
if len(lst) == 0:
return 0
else:
num = lst[0] # use the first one
return recursiveSum(lst[1:]) + num # and recurse on the remaining slice
size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
lst.append(int(input("Enter number "+str(i+1)+" = " )))
print(recursiveSum(lst))
list.pop() returns the element popped from the list - not the list-remainder.

Python: Issue with Elif Break

I'm trying to make a simple program that will take all of your lottery numbers, and compare them (using set intersect) with the winning numbers that you input.
I've gotten the groundwork laid where you enter your numbers, it gets submitted to a sublist, which will then be converted into five separate sets, which will be used to compare. However, when you run the script, the while loop will not break when the length of the list is 5 (this is the goal).
Can someone explain what I'm doing wrong? Or maybe even a better way of working this whole program. I'm relatively new to the world of Python, I'm just diving in, and trying to make this program work.
# Start Program
def set_convert(list):
conversion = set(list)
return conversion
def comparison(winning_numbers, my_numbers):
pass
def main():
print('Welcome to the Lottery Checker v1.0!')
winning_numbers = [int(x) for x in input('Enter the winning numbers(Sep w/ Spaces): ').split()]
winning_set = set_convert(winning_numbers)
my_numbers = []
while True:
numbers = [int(x) for x in input('Enter your numbers(Sep w/ Spaces Max: 5): ').split()]
if len(numbers) == 6:
my_numbers.append(numbers)
print('Added! Want to add more?')
elif len(my_numbers) == 5:
break
else:
pass
else:
pass
print('Here are your numbers: {}. Good luck! :-)'.format(my_numbers))
main()
Replace
elif len(my_numbers) == 5:
with
elif len(numbers) == 5:
Also, it is advisable that you don't use the keyword list as an argument for the function set_convert. Rather, define it as:
def set_convert(mylist):
conversion = set(mylist)
return conversion
And finally, you don't need to pass in my_numbers and winning_numbers into the function comparison as arguments since they are available in the outer scope.

How to store arbitrary number of inputs from user?

Just wondering how I would store the inputs for an average sum of square roots problem.
The user can input as many numbers as they until they type 'end'
here is what i have for that
while(True):
x = input("Enter a number please:")
if x == 'end':
break
You can append these values to a list. Sum and then divide by the length for the average.
nums = []
while True:
x = input("Enter a number:")
if x == 'end':
avg = sum(nums) / len(nums)
print("And the average is....", avg)
break
elif x.isdigit():
nums.append(int(x))
else:
print("Try again.")
The next thing you'd want to learn about is a data structure such a list. You can then add items to the list on the fly with list.append.
However, it's noteworthy that where ever you're learning Python from will certainly go over lists at one point or another.
If you mean that you want to store all the x values given, just use a list. l = [] l.append(x).

Square number sequence in Python

I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
When I run this code it infinitely prints "1" ... I'm guessing that the value of a does not increase by += so it's a=1 forever. How do I fix this?
There are some problems. First, your input (what raw_input() returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
Second, you are setting a = 1 each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line
a = 1
Finally, it's not necesary to check if a > n, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
There is a small error in your code:
while a < n:
a=1 # `a` is always 1 :)
print a*a
a += 1
if a > n:
break
You're setting the value of a back to 1 on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1 line.
As others have noted, your specific problem is resetting a each time you loop. A much more Pythonic approach to this is the for loop:
for a in range(1, n):
print(a ** 2)
This means you don't have to manually increment a or decide when to break or otherwise exit a while loop, and is generally less prone to mistakes like resetting a.
Also, note that raw_input returns a string, you need to make it into an int:
n = int(raw_input("Enter number: "))
an even better idea is to make a simple function
def do_square(x):
return x*x
then just run a list comprehension on it
n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]
this is a more pythonic way to do what you are trying to do
you really want to use functions to define functional blocks that are easy to digest and potentially can be reused
you can extend this concept and create a function to get input from the user and do some validation on it
def get_user_int():
#a function to make sure the user enters an integer > 0
while True:
try:
n = int(raw_input("Enter a number greater than zero:"))
except TypeError:
print "Error!! expecting a number!"
continue;
if n > 0:
return n
print "Error: Expecting a number greater than zero!"
and then you can build your input right into your list
squares = [do_square(i) for i in range(1,get_user_int()+1)]
and really do_square is such a simple function we could easily just do it in our loop
squares = [x*x for x in range(1,get_user_int())]
The first line in your loop sets's a to one on every iteration.
You assign a=1 inside the loop. That means it's overwriting the a+=1.
try this:
n = eval(raw_input("Enter number"))
a=1
while a < n:
print a*a
a += 1
The issue here is that the value of a gets overridden every time you enter in the loop
Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..
def powers(x):
n=1
while((n**2)<=x):
print(n**2, end =' ')
n +=1

Categories

Resources