I'm following a book and i ran into this sample program. I'm not sure how the numbers[position] in line 5 is working here? What is the relationship between position and numbers in that variable assignment?
numbers = [1, 3, 5]
position = 0
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print "Found even number", number
break
position = position + 1
else:
print "No even number found"
That number inside square brackets is an index of the list,
like so
lst = ["b", "c", 3] # Take care not to use "list" as a variable name by the way.
print lst[0] # I used lst in my example
gives you:
"b"
The first element of the list.
However I could not pass without saying that for loop is a far better way of doing this. Rather than incrementing position one-by-one and telling while loop to stop when it reaches to the length of the list is just good for understanding the concepts. I am sure your textbook is going to cover that next.
It's not variable assignment, it's lookup. position is an index; when it has a value of 0, numbers[position] returns 1 (the first element in numbers), for position 1 it gets 3, etc.
Python sequences like list are indexed 0-up, so the first element in a sequence is at index 0, and the last is at index len(seq) - 1.
In number = numbers[position] literally means what it says. position is a position in the list. First it is assigned to zero, so when doing numbers[position] it is actually calling the number in the list at position zero which is 1. Then it does position = position + 1 which will ask it for the number in position 1 in the list and so on.
I wasn't familiar with this style of variable assignment. I've seen lists referenced directly using index numbers. But since this post, I've tried the following and it cleared it up. Thank you very much!
list1 = ["apples", "oranges"]
position = 1
output1 = list1[0]
output2 = list1[position]
print output1
print output2
Related
I have a list and I want the list to display an image whenever a certain string in the list is chosen. However, I don't know how to make it so that if you reach the end of the list, you go to the beginning again, or if you go to the beginning of the list and go backwards, you end up and the end of the list. Is there a piece code to do this?
If I understand correctly, there are two parts to the problem.
you want to associate an image to an item in the list. And you don't have any issue with this.
you want to cycle the list, that is, once you reach the end, you wanna start over.
For cycling the list, the simplest is to use a while True loop and at the end of the loop when the last element of the list is reached, reset to the first (or zeroth) in the list.
The simplest example could be as below:
a = [0,1,2,3,4]
index = len(a)
while True:
if index < len(a):
else:
index = 0
print(a[index])
index += 1
You can use the modulo operator %.
my_list = ["Apple", "Bannana", "Orange"]
def looping_list(my_list, index):
return my_list[index % len(my_list)]
print(looping_list(my_list, 3)) # outputs "Apple"
Also can handle negative numbers just fine.
so I have a list of 5 or fewer elements and the elements are just integers from 0-9 and the elements are randomly assigned and its possible for the list to have 5 zeros or 5 ones etc, and I have the following function to check if there is a zero in the list. this will return the index of the first zero it finds. just ignore the .getValue()
def check0(self):
'''
check for the index of the first card with value 0 in hand
:return:
'''
index = 0
found = False
while not found and index<len(self.hand):
if self.hand[index].getValue() == 0:
found = True
index += 1
if not found:
index = -1
return index
but the problem is that it always returns the first zero it finds in the list. in another class I am using this function to check if the hand has any zeros.
I need to write a for loop or some other loop that will traverse the list hand and tell me if all the elements in the hand are zeros.
so the only solution I can think of for this problem is to traverse the list once and when the first zero is found increment the counter and then traverse the list again this time excluding the zero that had already been found.
for example:
I have the list
[0,0,0,0,0]
in the first traversal, the check0() method will return the index 0 for the first zero but then I traverse the list again this time excluding the first zero and repeating that until I reach the last element.
I was thinking something like this:
def find_zeros():
counter = 0
for I in some_list(0,len(some_list),-1):
if I.check0() != -1:
counter += 1
if counter == len(some_list):
return True
return False
can anyone help me with this issue?
let me know if anything is unclear
also I'm not allowed to import anything and time complexity isn't an issue
"I need to write a for loop or some other loop that will traverse the list hand and tell me if all the elements in the hand are zeros." (OP)
Well, to check if all elements in your list are zero you could use count:
lst1 = [0,0,0,0,0]
print(len(lst1) == lst1.count(0))
Or maybe list comprehension:
lst1 = [0,0,0,0,0]
print(lst1 == [nr for nr in lst1 if nr == 0])
probably better written using all like:
lst1 = [0,0,0,0,0]
print(all(i==0 for i in lst1))
Or maybe create a second list the same size:
lst1 = [0,0,0,0,0]
print(lst1 == [0]*len(lst1))
You can use enumerate for this type of problem.
for index, ch in enumerate(list_name):
print(i, ch)
This will give you the index of each and every character in the list.
You can use an 'if' statement later to check if 'ch' is a zero.
Hope it helped.
listt=[1,0,2,0,1]
for i in range(len(listt)):
if listt[i]==0:
print(i)
break #if you want to find first occurence
To check all ekements are 0,
if len(set(listt))==1 and listt[0]==0:
print("All index have 0 ")
You could define the function like this:
def check0(self):
index = (self.hand+[0]).index(0)
return -1 if not any(self.hand) else index
Make a function that receives a string containing only digits and may also be an empty string, which returns an integer value which is the maximum of all the digits that are in the EVEN POSITIONS of the original string.
If the empty string, the function should return -1.
For example:
max_even_pos("123454321") returns 5, because 5 is the maximum of 1,3,5,3,1, which are the digits in the original string in even positions.
# My code
def max_even_pos(st):
if not st:
return -1 ### This line satisfies the empty list condition
for i in range(len(st)): ### Problem I have. Trying to find
## the max integer from even positions
num_list = [i] # assigns elements to the list
if i%2 == 0: # checks if elements are even
return max(num_list) # result
My only problem is trying to get the code to find the greatest integer in the even position of the original string. I think "num_list = [i]" causes the error, but I am unsure how to change this so it executes properly.
As of right now, it outputs 0 for all cases
Your current code ensures that num_list has no more than a single element. When you hit the first even index, 0, you stop and return that index, without regard to the input value. You have several errors to correct:
Put the return after the loop. You have to get through all of the input before you can return the required value.
Accumulate the values with append. Your current code keeps only the last one.
Accumulate the input values; i is the position, not the value. I believe that you want st[i]
Also look into better ways to iterate through a list. Look at for loops or list slicing with a step of 2. If you are ready for another level of learning, look up list comprehension; you can reduce this function to a one-line return.
#Prune is correct. Maybe comparing the lines below to your original will help you for next time....
test_string = "123454321"
def max_even_pos(st):
num_list = []
if not st:
return -1
for i in range(len(st)):
if i%2 == 0:
num_list.append(st[i])
return max(num_list)
print(max_even_pos(test_string))
I have ran into a logic error that I cannot solve and would like some assistance towards it.
Here's my code
Mysentence = MySentence
print(Mysentence)
MysentenceList = Mysentence.split()
List = []
for k in MysentenceList:
position = MysentenceList.index(k)
position = position + 1
position = str(position)
List.append(position)
Basically cannot handle unique words
If you want to assign each word a "unique id", you'd have to manage this in another data structure. Another list would do the trick:
UniqueWords = []
for k in ThesentenceList:
if k in UniqueWords:
position = UniqueWords.index(k)
else:
position = len(UniqueWords)
UniqueWords.append(k)
position = position + 1
position = str(position)
TheList.append(position)
Your list after splitting is ["Hello", "Hello", "I", "Hello"] which you then use to assign the word index value.
The first instance of "Hello" is index 0, the first instance of "I" is index 2. If you want to assign a "unique word ID" counting from zero without gaps in the sequence you're going to have to change your ID assignment algorithm to manage the duplicate words.
I'd propose using something like a Python dictionary to track the unique words as you find them (it's a hash map, so avoids list iteration with "index" which is going to get pretty slow with long inputs).
list.index(item) is giving you the position of first instance of item in list. The first instance of "Hello" is in position 0, but you're adding 1 to the position, so it's going to report 1 each time. "I" is located in position 2, so it's reporting 3.
I'm asked to create a method that returns the number of occurrences of a given item in a list. I know how to write code to find a specific item, but how can I code it to where it counts the number of occurrences of a random item.
For example if I have a list [4, 6 4, 3, 6, 4, 9] and I type something like
s1.count(4), it should return 3 or s1.count(6) should return 2.
I'm not allowed to use and built-in functions though.
In a recent assignment, I was asked to count the number of occurrences that sub string "ou" appeared in a given string, and I coded it
if len(astr) < 2:
return 0
else:
return (astr[:2] == "ou")+ count_pattern(astr[1:])
Would something like this work??
def count(self, item):
num=0
for i in self.s_list:
if i in self.s_list:
num[i] +=1
def __str__(self):
return str(self.s_list)
If this list is already sorted, the "most efficient" method -- in terms of Big-O -- would be to perform a binary search with a count-forward/count-backward if the value was found.
However, for an unsorted list as in the example, then the only way to count the occurrences is to go through each item in turn (or sort it first ;-). Here is some pseudo-code, note that it is simpler than the code presented in the original post (there is no if x in list or count[x]):
set count to 0
for each element in the list:
if the element is what we are looking for:
add one to count
Happy coding.
If I told you to count the number of fours in the following list, how would you do it?
1 4 2 4 3 8 2 1 4 2 4 9 7 4
You would start by remembering no fours yet, and add 1 for each element that equals 4. To traverse a list, you can use a for statement. Given an element of the list el, you can check whether it is four like this:
if el == 4:
# TODO: Add 1 to the counter here
In response to your edit:
You're currently testing if i in self.s_list:, which doesn't make any sense since i is an element of the list and therefore always present in it.
When adding to a number, you simply write num += 1. Brackets are only necessary if you want to access the values of a list or dictionary.
Also, don't forget to return num at the end of the function so that somebody calling it gets the result back.
Actually the most efficient method in terms of Big-O would be O(log n). #pst's method would result in O(log n + s) which could become linear if the array is made up of equal elements.
The way to achieve O(log n) would be to use 2 binary searches (which gives O(2log n), but we discard constants, so it is still O(log n)) that are modified to not have an equality test, therefore making all searches unsuccessful. However, on an unsuccessful search (low > high) we return low.
In the first search, if the middle is greater than your search term, recurse into the higher part of the array, else recurse into the lower part. In the second search, reverse the binary comparison.
The first search yields the right boundary of the equal element and the second search yields the left boundary. Simply subtract to get the amount of occurrences.
Based on algorithm described in Skiena.
This seems like a homework... anyways. Try list.count(item). That should do the job.
Third or fourth element here:
http://docs.python.org/tutorial/datastructures.html
Edit:
try something else like:
bukket = dict()
for elem in astr:
if elem not in bukket.keys():
bukket[elem] = 1
else:
bukket[elem] += 1
You can now get all the elements in the list with dict.keys() as list and the corresponding occurences with dict[key].
So you can test it:
import random
l = []
for i in range(0,200):
l.append(random.randint(0,20))
print l
l.sort()
print l
bukket = dict()
for elem in l:
if elem not in bukket.keys():
bukket[elem] = 1
else:
bukket[elem] += 1
print bukket