list index out of range while list is full - python-3.x

When I execute this code:
import random
list1 = ['afgdddd', 'bcbvnbn', 'casretb', 'dbcbv ', 'egfhsgs']
list2 = ['a5y5546', 'brtewtwret', 'chrtyey', 'dqawtet', 'egreg']
choice1 = random.randint(0, len(list1))
print(list1[choice1])
print(list2[choice1])
Sometimes a get this error:
python IndexError: list index out of range
What is causing this?

Valid list indices for a list of length 5 are 0,1,2,3,4. You are choosing a random number from 0,1,2,3,4,5. When the random number is 5 your index is out of range just as the error message says.
To prevent this from occurring you need a random number between 0 and 4. Simply change to:
choice1 = random.randint(0, len(list1) - 1)
Subtracting 1 from the length of a list is a very common pattern to get the last element in an array.
To debug something like this yourself, you should print(choice1) before trying to print(list1[choice1]) to see why the index may be out of range.

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

Get numbers from user, put them in a list, and find the biggest odd number

I'm a beginner in Python 3. I want to:
Ask for 10 numbers from the user and put them in a list
Check for the biggest odd number
The following code just put the last number in the value (number)
and I have no idea how to check for the biggest odd number:
for i in range(1,11):
number = list((input(f"please enter the {i}th number: ")))
print(number)
To create a list of numbers given by user we use a for-loop with input to ask for numbers as you almost did correctly (do not forget to cast to int):
numbers = []
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
numbers.append(number)
You can also do this with list comprehension, which will make it shorter but maybe a little harder to understand at the begining (this has exactly the same result as the previous code):
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
Now, to get the largest odd number from a list of numbers you can:
Set a variable with the minimum possible value or to None
Iterate over your list
Update the value of the variable, if a number is an odd number and larger than the one saved in your variable
Let's see this in action considering you have your list of numbers numbers.
odd_largest = 0
for number in numbers:
if number % 2 != 0 and number > odd_largest: # If number is odd and larger
odd_largest = number # update value
print(odd_largest)
What is the difference of setting odd_largest to 0 vs None? If you set it to 0 and the final value of odd_largest is 0, you wouldn't know if it was updated at all, is it a number in the list or just the original value? Imagine the case there is no odd number in the list, for example.
When using None as initial value you will be sure if it was updated. You also need to add an additional condition:
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
When you put everything together you get what is needed.
numbers = [int(input(f"Enter number {i}: ")) for i in range(1, 11)]
odd_largest = None
for number in numbers:
if number % 2 != 0 and (odd_largest is None or number > odd_largest): # If number is odd and larger or None
odd_largest = number
print(odd_largest)
Here some questions arise. First: are we using the list numbers for any other actions? If the answer is yes, then our code is enough. But if this is all that is needed we can actually do better.
Find the largest odd number by comparing the numbers right after input by the user, without even creating a list. Let's check it out!
odd_largest = None
for i in range(1, 11):
number = int(input(f"Enter number {i}: "))
if number % 2 != 0 and (odd_largest is None or number > odd_largest):
odd_largest = number
print(odd_largest)
What do we gain with this? Iterating just once over the numbers instead of twice, saving memory since we are not saving all numbers input just one. Cool uh?
If you have any more questions do not hesitate. Happy coding!
my_list = []
for i in range(1, 11):
my_list.append(int(input(f"please enter the {i}th number: ")
my_list_only_odd_numbers = [n for n in my_list if n % 2]
largest_odd_number = max(my_list_only_odd_numbers)
Get a list of integers from the user, remove all numbers from the list that aren't odd and then get the largest number in that list using max()

Regex Output Count

I am trying to count the output of a regex search I am conducting on a dataset but for some reason my count is off by a lot. I was wondering what I am doing wrong and how I can get an official count. I should have around 1500 matches but I keep getting an error that says "'int' object is not iterable".
import re
with open ('Question 1 Logfile.txt' , 'r') as h:
results = []
count = []
for line in h.readlines():
m = re.search(r'(((May|Apr)(\s*)\w+\s\w{2}:\w{2}:\w{2}))', line)
t = re.search(r'(((invalid)(\s(user)\s\w+)))',line)
i = re.search(r'(((from)(\s\w+.\w+.\w+.\w+)))', line)
if m and t and i:
count += 1
print(m.group(1),' - ',i.group(4),' , ',t.group(4))
print(count)
You want to increment the number of times you satisfy a condition over a series of loop iterations. The confusion here seems to be how exactly to do that, and what variable to increment.
Here's a small example that captures the difficulty you've encountered, as described in OP and in OP comments. It's meant as a learning example, but it does also provide a couple of options for a solution.
count = []
count_int = 0
for _ in range(2):
try:
count += 1
except TypeError as e:
print("Here's the problem with trying to increment a list with an integer")
print(str(e))
print("We can, however, increment a list with additional lists:")
count += [1]
print("Count list: {}\n".format(count))
print("Most common solution: increment int count by 1 per loop iteration:")
count_int +=1
print("count_int: {}\n\n".format(count_int))
print("It's also possible to check the length of a list you incremented by one element per loop iteration:")
print(len(count))
Output:
"""
Here's the problem with trying to increment a list with an integer:
'int' object is not iterable
We can, however, increment a list with additional lists:
Count list: [1]
Most common is to increment an integer count by 1, for each loop iteration:
count_int: 1
Here's the problem with trying to increment a list with an integer:
'int' object is not iterable
We can, however, increment a list with additional lists:
Count list: [1, 1]
Most common is to increment an integer count by 1, for each loop iteration:
count_int: 2
It's also possible to check the length of a list you incremented
by one element per loop iteration:
2
"""
Hope that helps. Good luck learning Python!

How to get list of indices for elements whose value is the maximum in that list

Suppose I have a list l=[3,4,4,2,1,4,6]
I would like to obtain a subset of this list containing the indices of elements whose value is max(l).
In this case, list of indices will be [1,2,5].
I am using this approach to solve a problem where, a list of numbers are provided, for example
l=[1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]
I need to identify the max occurence of an element, however in case more than 1 element appears the same number of times,
I need to choose the element which is greater in magnitude,
suppose I apply a counter on l and get {1:5,2:5,3:4...}, I have to choose '2' instead of '1'.
Please suggest how to solve this
Edit-
The problem begins like this,
1) a list is provided as an input
l=[1 4 4 4 5 3]
2)I run a Counter on this to obtain the counts of each unique element
3)I need to obtain the key whose value is maximum
4)Suppose the Counter object contains multiple entries whose value is maximum,
as in Counter{1:4,2:4,3:4,5:1}
I have to choose 3 as the key whose value is 4.
5)So far, I have been able to get the Counter object, I have seperated key/value lists using k=counter.keys();v=counter.values()
6)I want to get the indices whose values are max in v
If I run v.index(max(v)), I get the first index whose value matches max value, but I want to obtain the list of indices whose value is max, so that I can obtain corresponding list of keys and obtain max key in that list.
With long lists, using NumPy or any other linear algebra would be helpful, otherwise you can simply use either
l.index(max(l))
or
max(range(len(l)),key=l)
These however return only one of the many argmax's.
So for your problem, you can choose to reverse the array, since you want the maximum that appears later as :
len(l)-l[::-1].index(max(l))-1
If I understood correctly, the following should do what you want.
from collections import Counter
def get_largest_most_freq(lst):
c = Counter(lst)
# get the largest frequency
freq = max(c.values())
# get list of all the values that occur _max times
items = [k for k, v in c.items() if v == freq]
# return largest most frequent item
return max(items)
def get_indexes_of_most_freq(lst):
_max = get_largest_most_freq(lst)
# get list of all indexes that have a value matching _max
return [i for i, v in enumerate(lst) if v == _max]
>>> lst = [3,4,4,2,1,4,6]
>>> get_largest_most_freq(lst)
4
>>> get_indexes_of_most_freq(lst)
[1, 2, 5]
>>> lst = [1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]
>>> get_largest_most_freq(lst)
3
>>> get_indexes_of_most_freq(lst)
[2, 4, 7, 14, 17, 19]

For loops python that have a range

So I'm writing a python code and I want to have a for loop that counts from the the 2nd item(at increment 1). The purpose of that is to compare if there are any elements in the list that match or are included in the first element.
Here's what I've got so far:
tempStr = list500[0]
for item in list500(1,len(list500)):
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
However the code doesn't work because the range option doesn't work for lists. Is there a way to use range for a list in a for loop?
You can get a subset of the list with the code below.
tempStr = list500[0]
for item in list500[1:]:
if(tempStr in item):
numWrong = numWrong - 1
amount540 = amount540 - 1
The [1:] tells Python to use all elements of the array except for the first element. This answer has more information on list slicing.
Use a function:
search_linear(mainValues, target)
This is the algorithm you are looking for: http://en.wikipedia.org/wiki/Linear_search
All you need to do is set the starting point equal to +1 in order to skip your first index, and than use array[0] to call your first index as the target value.
def search_linear(MainValues, Target):
result = []
for w in Target:
if (search_linear(MainValues, w) < 0):
result.append(w)
return result

Resources