Pass all the elements of a list through a functions - list

I created a python program that arranges and finds the median of a series of numbers a user inputs. I keep getting this error.
Traceback (most recent call last):
File "C:/Users/NL-LP3/Desktop/Corses/Python/Tests Programs/median user input.py", line 24, in
median(^series)
TypeError: median() takes 1 positional argument but 4 were given
series=[]
finished = False
while not finished:
number = input("Please enter a number, when you are done hit ENTER")
if len(number)>0:
series.append([number])
print ("Number Entered")
else:
finished = True
print (series)
def median(data):
data.sort(key=int)
elements = len(data)
middle = int(elements/2)
if elements%2 ==1:
print (data[middle])
else:
half = ((data[middle])+(data[middle-1]))/2
print (half)
median(*series)

Three issues here:
You are passing in a string into your array, you need to convert it to an int
You are passing in an array to an array which gives you an output like this:
[[5], [6], [7]]
You are attempting to unpack your array by using the * in your *series.
It needs to be this:
[5, 6, 7]
Change this line:
series.append(int(number))
You are also just need to pass in the array to median like such:
median(series)

you unpack your series as you are passing it to your function:
median(*series)
this way median is called with all the items in the list as arguments. what you want is:
median(series)
missed the second issue! read Jason Heine's answer...

Related

For-loop error: list index out of range

So I am rather new to programming and just recently started with Classes and we are supposed to make a phonebook that can be loaded in seperate text files.
I however keep running into the problem in this section that when I get into the for-loop. It hits a brick wall on
if storage[2] == permaStorage[i].number:
And tells me "IndexError: list index out of range". I am almost certain it is due to permaStorage starts out empty, but even when I attempt to fill it with temporary instances of Phonebook it tells me it out of range. The main reason it is there is to check if a phone number already exists within the permaStorage.
Anyone got a good tip on how to solve this or work around it?
(Sorry if the text is badly written. Just joined this site and not sure on the style)
class Phonebook():
def __init__(self):
self.name = ''
self.number = ''
def Add(name1, number1):
y = Phonebook()
y.name = name1
y.number = number1
return y
def Main():
permaStorage = []
while True:
print " add name number\n lookup name\n alias name newname\n change name number\n save filename\n load filename\n quit\n"
choices = raw_input ("What would you like to do?: ")
storage = choices.split(" ")
if storage[0] == "add":
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
except:
raw_input ("Remember to write name and phonenumber! Press any key to continue \n")
I think problem is that permaStorage is empty list and then u try to:
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
will cause an error because permaStorage has 0 items but u trying to get first (i=0, permaStorage[0]) item.
I think you should replace second if clause with first one:
for i in range(0, len(permaStorage)+1):
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
So in this case if perStorage is blank you will append some value and next if clause will be ok.
Indexing starts at zero in python. Hence, a list of length 5 has the last element index as 4 starting from 0. Change range to range(0, len(permastorage))
You should iterate upto the last element of the list, not beyond.
Try -
for i in range(0, len(permaStorage)):
The list of numbers produced in range() is from the start, but not including the end, so range(3) == [0, 1, 2].
So if your list x has length 10, range(0, len(x)) will give you 0 through 9, which is the correct indices of the elements of your list.
Adding 1 to len(x) will produce the range 0 through 10, and when you try to access x[10], it will fail.

Return instead of print key in a Python list

I'm trying to create a function where each key in a list becomes an updatable parameter for another function.
I know that I can print all the keys in a list like this:
x = [a , b, c, d]
for key in x:
print(key)
But when I use the return statement like:
for key in x:
return key
It only returns a.
How can I iterate over a list and return each value every time the loop is performed.
Thank you very much.
A slight modification is ok:
def PrintKey(x):
for key in x:
yield key
When you use the return statement you leave the function, thus after the first loop the interpreter exits the function and returns the first index of your list.
Could you post more code?
I see no reason to put this in a function but if you need to, one option could be :
for i in range(len(list)):
storeSomeWhere = myFunction(list, i)
def myFunction(list, i):
return list[i]
For what? The for loop already hands you one value from the list at a time.
If you insist you can use a generator function that accepts the list and returns the next element each time it is used (until it runs out of elements, then a StopIteration exception is raised):
def gen(li):
for element in li:
yield element
li = [1, 2, 3, 4]
a = gen(li)
print(next(a))
# 1
print(next(a))
# 2
print(next(a))
# 3
print(next(a))
# 4
print(next(a))
Traceback (most recent call last):
File "main.py", line 63, in <module>
print(next(a))
StopIteration
But again, I don't see any reason to use this in your case. Simply use the value that the for loop hands you.

How to add a element to the next list everytime a new value is entered?

For example I have a list with a month and the month number, I want to add in another value in [0][1], [1][1],[2][1] every time I input a new value. I'm thinking of the append function however I'm unsure how to re-code that to make that value to input into the the next list along in the list.
list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]
def month():
global list
count = 0
while value_count < 3:
value = int(input("Enter a value: "))
if value in range(101):
list[0][1].append(value)
count += 1
else:
print('Try Again.')
month()
I want to result with something like:
list = [[['Jan'],1,54], [['Feb'],2,65],[['Mar'],3,62]]
Where 54, 65 and 62 are random numbers a user has entered.
Please see the comments in the code
# list is a function used by python to create lists,
# do not use builtins' names for your variables
my_list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]
def month():
# print("Don't use globals!\n"*100)
# you can pass arguments to a function, like in "def mont(my_list)"
global my_list
# cycling on a numerical index is complicated, use this syntax
# instead, meaning "use, in turn, the same name to refer to each
# element of the list"
for element in my_list:
value = int(input("Enter a value: "))
# if value in range(101):
if 1: # always true, the test doesn't work as you expect
element.append(value)
else:
print('Try Again.')
month()
print my_list
you can write the input loop like this
value = 101
while not (0<=value<101):
value = int(input(...)
element.append(value)
this way you'll miss the alternative prompt but it's good enough.

Sequential Search: Input Length Isn't Detected Python

I'm writing a program where the user inputs a list of numbers, and then is asked which number he or she wants the program to return that numbers position. (Ex. 3,5,1,9,12,6 --> find position in list where 9 occurs)
I can get this to work if I hard code the list and the search number, but I'm having trouble with input. Mostly my problem is that Python isn't detecting the length of the list of numbers but I'm not sure how to fix this.
Here is the code I have:
def List(line):
list = []
for e in line.split(','):
list.append(int(e))
def Search(num, list):
for i in range(len(list)):
if list[i] == num:
return i
return -1
def main():
line = input("Enter list of numbers separated by commas: ")
p = input("Number searching for")
print(List(line))
a = Search(p, list)
print(a)
main()
And here's the error:
Traceback (most recent call last):
File "G:\Final Exam Practice\linearsearch.py", line 24, in <module>
main()
File "G:\Final Exam Practice\linearsearch.py", line 19, in main
a = Search(p, list)
File "G:\Final Exam Practice\linearsearch.py", line 7, in Search
for i in range(len(list)):
TypeError: object of type 'type' has no len()
First, this answer has something you could use. list.index is a class method that returns the index of a list item:
>>> mylist = [3,5,1,9,12,6]
>>> mylist.index(9)
3
Next, a TypeError is raised because list is one of Python's reserved keywords. If you want to pass a list to your Search function, don't name it 'list'.
Just changing the name of the 'list' variable in the function will solve your problem. Additionally, here's another way to define search (Python function names are usually lowercase):
def search(num, mylist):
try:
return mylist.index(num)
except:
return -1

Python: TypeError: 'NoneType' object is not iterable Confusion

I'm new to python and am trying to write a code that would deal poker hands and check for pat flushes. Below is my code and the shell when I try to run it. According to my professor this should return True if there is only one suit in the hand, i.e., only one entry in the set "suits" and False otherwise, but I keep getting this error message. Can someone help explain this to me?
from random import *
suits = {'H','C','D','S'} #hearts, clubs, diamonds, spades
ranks = {'a','2','3','4','5','6','7','8','9','10','j','q','k'} #card values
deck = [r +s for r in ranks for s in suits]
hand = []
def deal (n):
'''deals n hands'''
for n in range (0,n):
hand = sample (deck,5)
for x in hand:
deck.remove (x)
print (hand)
def is_flush (hand):
'''checks for pat flush hands'''
suits = {c[-1] for c in hand}
return len(suits) == 1
RUN
>>> is_flush (5)
['10S', 'qD', '8H', '8D', '3S']
['5C', 'jC', 'kS', '4C', '2H']
['2S', '7C', '7H', '7S', '9S']
['8C', '8S', 'aH', '5S', '2D']
['9D', '6S', '4D', 'qS', '9H']
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
is_flush (5)
File "K:/stalter_3.py", line 19, in is_flush
suits = {c[-1] for c in hand}
TypeError: 'NoneType' object is not iterable
>>>
You're calling is_flush(5). If I understand you correctly, then that value 5 is the variable hand which you are trying to iterate through (as if it were a hand) in c[-1] for c in hand, but you can't iterate an integer. The reason I'm confused is I would expect it to say that it's an IntType, not a NoneType.