Why can a function be usable in determined range? - python

I've been learning Python since a while and developing a function for doing a list of Lucky numbers i made this code:
def lucky(n):
list = []
rem1 = []
rem2 = []
# First verification
for i in range(1,n+1,2):
list.append(i)
print (list)
# Second verification
for i in range(2,m,3):
element = list[i]
rem1.append(element)
list = [x for x in list if x not in rem1]
# Third verification
n=(len(list))+1
for i in range(6,n,7):
element = list[i]
rem2.append(element)
list = [x for x in list if x not in rem2]
return list
My problems begins when running values bigger than 55. Why can Python take as out of range the code after that specific number and how could it be corrected?

The word "list" is a reserved word in python, you should change the name to a non-reserved word.
You have a type on line 16: for i in range(2,m,3): that "m" should be an "n", should it not?
The range you use in your second for loop exceeds the length of the list object. You need to check the length with an if statement.
for i in range(2,n,3):
if len(my_list) > i:
element = my_list[i]
rem1.append(element)

Reading in a math web, i found this problem.
It is solved with this code:
def lucky(n):
# Lista inicial
lista = list(range(1, n + 1, 2))
# Variable inicial
indice = 1
# Ciclo de ejecuciĆ³n
while indice <= len(lista) - 1 and lista[indice] <= len(lista):
lista = [Li for i, Li in enumerate(lista) if (i + 1) % lista[indice]]
indice += 1
# Resultados
return lista
My question here is about how is line 8 working

Related

How can I match element by element of list?

i'm trying to solve the problem of checking the distance between letters by looking at the alphabet. I described it in a dictionary. I gave "l = 10000" so that later I could easily distinguish the correct numerator. I think the idea itself is good, but it gives me the error "if abs (words [text [i] [j]] - words [text [i] [j + 1]] <10):
IndexError: string index out of range "
I will be grateful for every tip.
Code:
words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
l = 0
t = []
for i in range(0,len(text)):
for j in range(0,len(text[i])):
if abs(words[text[i][j]] - words[text[i][j+1]] < 10):
l = l+1
else:
l = 10000
t.append(l)
l = 0
print(t)
The error is raised with the last iteration, when you want to compare the last letter with the letter after the last letter, which doesn't exist. Perhaps start at 1 and compare the current letter with the previous letter like this:
words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
l = 0
t = []
for i in range(0,len(text)):
for j in range(1,len(text[i])):
if abs(words[text[i][j-1]] - words[text[i][j]] < 10):
l = l+1
else:
l = 10000
t.append(l)
l = 0
print(t)
I would recommend using the ord built-in to check distance between letters.
In [1]: ord("i") - ord("g")
Out[1]: 2

Transpositions and Permutations - Runtime error

This is the question I have to answer:
Find a sequence of transpositions of letters that transform the sequence MARINE (letters are numbered 0..5) to the sequence AIRMEN. Transpositions are represented by pairs of integers. For example, the pair (0,1) transforms MARINE to AMRINE. Transpositions are performed from left to right. You should define the sequence by writing something like this (the dots should be replaced by numbers, each pair in parentheses specifies one permutation, and these permutations are performed sequentially, from left to right):
def sequence():
return [(...,...),..., (...,...)]
When I run the program i seem to get a runtime error. I'm unable to find where the error is. It would be very useful, if I could get some help. Thanks! :)
This is my code:
def sequence(original, target):
permutation = []
chars_original = []
for char in original:
chars_original.append(char)
#print('original: ', chars_original)
chars_target = []
for char in target:
chars_target.append(char)
#print('target: ', chars_target)
for i in range(0, len(target)):
if chars_target[i]== chars_original[i]:
continue
else:
temp_list = []
temp_list.append(i)
j = chars_original.index(chars_target[i])
temp_list.append(j)
temp = chars_original[i]
chars_original[i] = chars_original[j]
chars_original[j] = temp
a = tuple (temp_list)
permutation.append(a)
#print(permutation)
#print(chars_original)
return permutation
sequence('MARINE', 'AIRMEN')
Can you try this
def sequence(original, target):
# convert to list so the string becomes mutable
original = list(original)
target = list(target)
seq = []
for i in range(len(original)):
if original[i] != target[i]:
for j in range(i+1, len(original)):
if original[j] == target[i]:
original[i], original[j] = original[j], original[i] # swap if the same
seq.append((i, j))
return seq
sequence('MARINE', 'AIRMEN')
def sequence(y,z):
a=list(y)
b=list(z)
d=0
l=[]
while(d<len(y)):
if(a[d]==b[d]):
d=d+1
else:
e=a.index(b[d])
a[e],a[d]=a[d],b[d]
l=l+[(d,e)]
return l
print(sequence("MARINE","AIRMEN"))

How can I take a list and append each element to a new list depending on its position?

So my first list created via a for loop looks like the following
["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"].
I then want it to be appened to new list depending on their position.
so List1 will be [1variable1]
List2 will be [1variable2]
etc
Then the next step of the loop will create another
["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]
I then want to append that to the previous list to make;
List1 will be [1variable1, 1variable2]
List2 will be [1variable2, 2variable2]
etc.
At the moment I have it so that it simply used square brackets to pull out each part of the list but I don't know how to get this in a loop, maybe next time I run it there will be more than 4 entries and I will miss the 5th.
lst1 = [item[0] for item in Genres]
lst2 = [i[1] if len(i) > 1 else '' for i in Genres]
lst3 = [i[2] if len(i) > 2 else '' for i in Genres]
lst4 = [i[3] if len(i) > 3 else '' for i in Genres]
lst5 = [i[4] if len(i) > 4 else '' for i in Genres]
If the next list doesn't have as many as a previous list then it should fill in a blank space as they all need to be in the same position
The lists are created as follows;
my_list = my_list[1:]
length = len(my_list)
my_list = my_list[0:3]
for film in my_list:
filmIndex = my_list.index(film) + 1
query = film + " imdb"
for j in search(query, tld="co.in", num=10, stop=1, pause=2):
page = requests.get(j)
response = page.status_code
if response == 200:
soup = BeautifulSoup(page.content, "lxml")
genreData = soup.find_all("div",{"class":"subtext"})
Then
for h in genreData:
a = h.find_all('a')
aLength = len(a)
a1 = a[0]
for b in range(0,aLength - 1):
r = a[b].string
genres.append(r)
I then want to add each genre into a seperate column, genre1, genre2 etc. up to how ever many max is. Obviously some of these mull be NULL if the max is 4 and one film only has 1
Then for each film will create a list of all the genres for that film and I want to put them into separate columns
One possible method is to create a list of lists.
Creating a list of lists lets you iterate through the list to insert and place each variable into the list at the variable's index. Of course, if you've got a big list or are doing your first pass, you'll hit an index you haven't encountered yet, so you'll need to init an empty list at that index.
list1 = ["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"]
list2 = ["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]
biglist = []
#insert list1
#this for loop can be repeated for every list you want to enter - maybe
#put those into a list of lists, too?
for i in range(0, len(list1)):
#check to see if there's a list in this entry
if 0 <= i < len(biglist):
#there's already a list here, add this to it
biglist[i].append(list1[i])
else:
#there's no list here yet, create one and add its first variable
biglist.append([])
biglist[i].append(list1[i])
#repeat for the second list, and so on - you can nest these
for i in range(0, len(list2)):
if 0 <= i < len(biglist):
biglist[i].append(list2[i])
else:
biglist.append([])
biglist[i].append(list2[i])
for l in biglist:
print(l)
Demo

indexError: list indexing error and wrongful tracking of counters

The goal of the program is to define a procedure that takes in a string of numbers from 1-9 and outputs a list with the following parameters:
Every number in the string should be inserted into the list.
If a number x in the string is less than or equal to the preceding number y, the number x should be inserted into a sublist. Continue adding the following numbers to the sublist until reaching a number z that is greater than the number y.
Then add this number z to the normal list and continue.
#testcases
string = '543987'
numbers_in_lists(string)
result = [5,[4,3],9,[8,7]]
def numbers_in_lists(string):
# Convert the sequence of strings into an array of numbers
i = 0
conv_str_e = []
while i < len(string):
conv_str_e.append(int(string[i]))
i += 1
#official code starts here
normal_list = []
list_of_small_nums = [[]]
# This will help me keep track of elements of the normal_list.
previous_e_pos = -1
e_pos = 0
# this one will be used to decide if the element should go into the
#normal_list or list_of_small_nums
check_point = 0
for e in conv_str_e:
#The first element and every elements bigger the element with
#check_point as it's index
#will be put into the normal_list as long as the list inside
#list_of_small_nums is empty
if e_pos == 0 or e > conv_str_e[check_point]:
#If the list inside list_of_small_nums is not empty
if list_of_small_nums[0] != []:
#concatenate the normal_list and list_of_small_nums
normal_list = normal_list + list_of_small_nums[0]
#Clear the list inside list_of_small_nums
list_of_small_nums[0] = []
#Add the element in the normal_list
normal_list.append(e)
# Update my trackers
e_pos += 1
previous_e_pos += 1
# (not sure this might be the error)
check_point = e_pos
#The curent element is not bigger then the element with the
#check_point as index position
#Therefor it goes into the sublist.
list_of_small_nums[0].append(e)
e_pos += 1
previous_e_pos += 1
return list
What you were doing wrong was exactly what you pointed out in your comments. You just kept increasing e_pos and so check_point eventually was greater than the length of the list.
I took the liberty of changing some things to simplify the process. Simple programs make it easier to figure out what is going wrong with them. Make sure you always try to think about the simplest way first to solve your problem! Here, I replaced the need for e_pos and previous_e_pos by using enumerate:
string = '543987'
# Convert the sequence of strings into an array of numbers
conv_str_e = [int(i) for i in string]
#official code starts here
normal_list = []
list_of_small_nums = []
# this one will be used to decide if the element should go into the
#normal_list or list_of_small_nums
check_point = 0
for ind, e in enumerate(conv_str_e):
#The first element and every elements bigger the element with
#check_point as it's index
#will be put into the normal_list as long as the list inside
#list_of_small_nums is empty
if ind == 0 or e > conv_str_e[check_point]:
#If the list inside list_of_small_nums is not empty
if list_of_small_nums != []:
#concatenate the normal_list and list_of_small_nums
normal_list.append(list_of_small_nums)
#Clear the list inside list_of_small_nums
list_of_small_nums = []
#Add the element in the normal_list
normal_list.append(e)
# Update my trackers
check_point = ind
else:
#The curent element is not bigger then the element with the
#check_point as index position
#Therefore it goes into the sublist.
list_of_small_nums.append(e)
# If there is anything left, add it to the list
if list_of_small_nums != []:
normal_list.append(list_of_small_nums)
print(normal_list)
Result:
[5, [4, 3], 9, [8, 7]]
I am sure you can change it appropriately from here to put it back in your function.

How turn my loop results into a list

I have no idea how to use put these results into a list and sort it using python3.
def get_new(x):
i = 0
while i < 6:
i = i+1
print (x)
x = (x*31334)%31337
get_new(7546)
One way to do this is to create a list and append the values of x. Then return this list from your function:
def get_new(x):
lst = []
i = 0
while i < 6:
i = i+1
x = (x*31334)%31337
lst.append(x)
return lst
print (get_new(7546))
#[8699, 5240, 15617, 15823, 15205, 17059]
For calculating and sorting the calculated list, do this using list append and sort.
def get_new(x):
new_list = []
i = 0
while i < 6:
i = i+1
#print (x)
x = (x*31334)%31337
new_list.append(x) # append the each new value of x to `new_list`
return new_list
a = get_new(7546) # returns the unsorted calculated list
a.sort() # sorting using sort() function
print (a)
#OUTPUT [5240, 8699, 15205, 15617, 15823, 17059]

Categories

Resources