So I wrote a function slanted(grid) which takes in a grid and returns the combination of letters horizontally.
For instance, if grid is
['q','q','d'],
['s','d','e'],
['e','g','h']
then slanted(grid) should return
['d','qe','qdh','sg','e']
I tried to do this by writing up this code for slanted(grid)
def slanted(grid):
results = []
for j in range(len(grid)-1):
tmp = ""
for i in range(len(grid)):
tmp += [j+i][i]
results.append(tmp)
return results
print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))
but I'm getting an error message saying:
TypeError: can only concatenate str (not "int") to str
what changes to my code should I make to get the right output as indicated above?
[j + i][i] creates a singleton list with one integer, and then attempts to access that integer. You should try to access an element of grid, e.g. by doing grid[j + i][i], but this causes an IndexError.
Here is my approach to your task. You can think of this as reading a series of diagonals, each starting from a different start row / column index. For each start index, we extract that given diagonal:
def extract_diagonal(grid, start_row, start_col):
row = start_row
col = start_col
letters = []
while row < len(grid) and col < len(grid[0]):
letters.append(grid[row][col])
row += 1
col += 1
return ''.join(letters)
def slanted(grid):
results = []
for col in range(len(grid) - 1, -1, -1):
results.append(extract_diagonal(grid, 0, col))
for row in range(1, len(grid)):
results.append(diagonal(grid, row, 0))
return results
# Prints ['d','qe','qdh','sg','e'].
print(slanted([['q','q','d'],['s','d','e'],['e','g','h']]))
Note that we're using ''.join() rather than repeated string concatenation here, as the former has a better time complexity. For more discussion on this, see this answer.
I just start to learn python and i have a problem:
arr = [1,3,3,3,0,1,1]
def solution(arr):
a=[]
for r in range(len(arr)-1):
if arr[r] == arr[r+1]:
a.append(r+1)
print(a)
for i in range(len(a)):
k = int(a[i])
arr[k] = -1
arr.remove(-1)
return arr
There's a message
IndexError: list index out of range for ''arr[k] = -1''
Can you please tell me the reason for the Error and correct it?
Of course, it results in a Runtime exception. The list a stores indices. For each element v in a, you are trying to remove the value arr[v]. Doing this will reduce the size of arr by one every time. So, in the next iteration, v can be greater than the size of arr. Hence, it results in List index out of bound exception.
Your code, corrected:
arr = [1,3,3,3,0,1,1]
def solution(arr):
a=[]
for r in range(len(arr)-1):
if arr[r] == arr[r+1]:
a.append(r+1)
print(a)
c = 0
for i in range(len(a)):
k = int(a[i])
arr[k - c] = -1
arr.remove(-1)
c += 1
return arr
print(solution(arr))
It looks like you are trying to remove consecutive duplicates from the list. This can be easily solved using the following code.
def remove_duplicates(arr):
stack = [arr[0]]
for i in range(1, len(arr)):
if stack[-1] != arr[i]:
stack.append(arr[i])
return stack
print(remove_duplicates([1,3,3,3,0,1,1]))
In short, you cannot modify the array shape when you have determined the indices based on the unmodified array to index into it.
Here is something that you might be looking for:
def solution(arr):
a = []
for r in range(len(arr) - 1):
if arr[r] == arr[r + 1]:
a.append(r + 1)
print(a)
for i in range(len(a)):
k = int(a[i])
arr[k] = -1
# In the following line, you cannot modify the array length
# when you have already computed the indices based on the unmodified array
# arr.remove(-1)
arr = [x for x in arr if x != -1] # This is a better way to deal with it
return arr
print(solution(arr=[1, 3, 3, 3, 0, 1, 1]))
You don’t want to mess with the original list. Otherwise you’ll run into index errors. Index errors mean the item you were looking for in the list no longer exists. Most likely this line was the culprit arr.remove(-1).
arr = [1,3,3,3,0,1,1]
solution = []
for i, v in enumerate(arr):
if i == 0 or v != arr[i -1]:
solution.append(v)
print(solution)
This should get you what you are after. enumerate tells you want index you are at when looping through the list. More information can be found here: https://realpython.com/python-enumerate/
Well, you've probably already know what wrong happened here, removing the element inside the loop:
for i in range(len(a)):
k = int(a[i])
arr[k] = -1
arr.remove(-1)
You can fix the whole thing just changing the line to this list filter+lambda implementation, well, not inside the loop, but after the completion of loop iterations, just like follows:
for i in range(len(a)):
k = int(a[i])
arr[k] = -1
arr = list(filter(lambda x: x != -1, arr))
And you'll get what you want just from your solution!
The code :
import pandas as pd
import numpy as np
import csv
data = pd.read_csv("/content/NYC_temperature.csv", header=None,names = ['temperatures'])
np.cumsum(data['temperatures'])
printcounter = 0
list_30 = [15.22]#first temperature , i could have also added it by doing : list_30.append(i)[0] since it's every 30 values but doesn't append the first one :)
list_2 = [] #this is for the values of the subtraction (for the second iteration)
for i in data['temperatures']:
if (printcounter == 30):
list_30.append(i)
printcounter = 0
printcounter += 1
**for x in list_30:
substract = list_30[x] - list_30[x+1]**
list_2.append(substraction)
print(max(list_2))
Hey guys ! i'm really having trouble with the black part.
**for x in list_30:
substract = list_30[x] - list_30[x+1]**
I'm trying to iterate over the elements and sub stracting element x with the next element (x+1) but the following error pops out TypeError: 'float' object is not iterable. I have also tried to iterate using x instead of list_30[x] but then when I use next(x) I have another error.
for x in list_30: will iterate on list_30, and affect to x, the value of the item in the list, not the index in the list.
for your case you would prefer to loop on your list with indexes:
index = 0
while index < len(list_30):
substract = list_30[index] - list_30[index + 1]
edit: you will still have a problem when you will reach the last element of list_30 as there will be no element of list_30[laste_index + 1],
so you should probably stop before the end with while index < len(list_30) -1:
in case you want the index and the value, you can do:
for i, v in enumerate(list_30):
substract = v - list_30[i + 1]
but the first one look cleaner i my opinion
if you`re trying to find ifference btw two adjacent elements of an array (like differentiate it), you shoul probably use zip function
inp = [1, 2, 3, 4, 5]
delta = []
for x0,x1 in zip(inp, inp[1:]):
delta.append(x1-x0)
print(delta)
note that list of deltas will be one shorter than the input
I'm building a slot machine simulator in Python. I have setup the reels as follows:
Reels = [[10,9,4,5,7,4,9,2,6,7,3,4,9,3,4,9,6,5,4,11,8,9,11,2,4,1,9,10,4,9,10,6,4,9,1,5,4,9,1,10,3,8,6,4,9,1,8],
[4,3,5,4,3,5,2,8,4,1,8,10,1,2,9,8,11,2,8,5,6,11,3,4,2,8,4,7,6,10,8,7,9,4,1,6,8,4,2,9,8,3,5,4,10,8],
[1,9,4,2,5,1,6,9,2,5,9,2,10,9,4,8,9,11,2,5,8,9,10,4,1,10,9,2,10,5,9,7,5,6,8,9,7,3,10,6,2,9,5,8,3,1,10,3],
[8,10,3,8,7,3,9,8,10,11,3,10,9,6,8,10,11,6,5,3,8,1,4,9,5,8,1,4,3,8,1,5,9,10,8,3,9,4,3,8,9,4,6,11,3,8,9,7,10,11],
[4,11,1,6,3,9,5,10,9,5,8,11,10,3,1,4,10,3,9,4,7,3,9,10,4,3,1,5,10,6,5,8,4,6,9,1,5,10,8,9,5,4,6,8,9,4,8,5,7,9]]
Now I need to iterate through them from 1 through 5 and build a 3X5 matrix. I want to start by producing a random number that determines where on that reel to stop. That value will be the middle value on that reel. Then, I need to add the top and bottom values (but have to account for the middle number potentially being at the beginning or end of the reel strip. I'm getting the error "list index out of range" on the if StopValue == Reels[i][len(Reels[i])]: line:
def spin():
SpinValues = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
for i, object in enumerate(Reels):
length = len(Reels[i])
StopValue = random.randint(0,length)
SpinValues[i][1] = Reels[i][StopValue]
if StopValue == 0:
SpinValues[i][0] = Reels[i][len(Reels[i])]
else:
SpinValues[i][0] = Reels[i][StopValue - 1]
if StopValue == Reels[i][len(Reels[i])]:
SpinValues[i][2] = Reels[i][0]
else:
SpinValues[i][2] = Reels[i][StopValue +1]
print(SpinValues)
spin()
Initially I thought I could do this with just "for i in reels," but I read a post here suggesting to use the "for index, object in enumerate(Reels)" method.
len(Reels[i]) is not a valid index for Reels[i]. The last valid index is len(Reels[i]) - 1
To refer to the last item in a list called my_list, you must use
my_list[-1]
or
my_list[len(my_list)-1]
and not:
my_list[len(my_list)]
The reason is that in Python, all indexing starts from 0, and not from 1
This is a follow up question to this response and the pseudo-code algorithm that the user posted. I didn't comment on that question because of its age. I am only interested in validating whether or not a string can be split into words. The algorithm doesn't need to actually split the string. This is the response from the linked question:
Let S[1..length(w)] be a table with Boolean entries. S[i] is true if
the word w[1..i] can be split. Then set S[1] = isWord(w[1]) and for
i=2 to length(w) calculate
S[i] = (isWord[w[1..i] or for any j in {2..i}: S[j-1] and
isWord[j..i]).
I'm translating this algorithm into simple python code, but I'm not sure if I'm understanding it properly. Code:
def is_all_words(a_string, dictionary)):
str_len = len(a_string)
S = [False] * str_len
S[0] = is_word(a_string[0], dictionary)
for i in range(1, str_len):
check = is_word(a_string[0:i], dictionary)
if (check):
S[i] = check
else:
for j in range(1, str_len):
check = (S[j - 1] and is_word(a_string[j:i]), dictionary)
if (check):
S[i] == True
break
return S
I have two related questions. 1) Is this code a proper translation of the linked algorithm into Python, and if it is, 2) Now that I have S, how do I use it to tell if the string is only comprised of words? In this case, is_word is a function that simply looks a given word up in a list. I haven't implemented it as a trie yet.
UPDATE: After updating the code to include the suggested change, it doesn't work. This is the updated code:
def is_all_words(a_string, dictionary)):
str_len = len(a_string)
S = [False] * str_len
S[0] = is_word(a_string[0], dictionary)
for i in range(1, str_len):
check = is_word(a_string[0:i], dictionary)
if (check):
S[i] = check
else:
for j in range(1, i): #THIS LINE WAS UPDATED
check = (S[j - 1] and is_word(a_string[j:i]), dictionary)
if (check):
S[i] == True
break
return S
a_string = "carrotforever"
S = is_all_words(a_string, dictionary)
print(S[len(S) - 1]) #prints FALSE
a_string = "hello"
S = is_all_words(a_string, dictionary)
print(S[len(S) - 1]) #prints TRUE
It should return True for both of these.
Here is a modified version of your code that should return good results.
Notice that your mistake was simply in the translation from pseudocode array indexing (starting at 1) to python array indexing (starting at 0) therefore S[0] and S[1] where populated with the same value where S[L-1] was actually never computed. You can easily trace this mistake by printing the whole S values. You will find that S[3] is set true in the first example where it should be S[2] for the word "car".
Also you could speed up the process by storing the index of composite words found so far, instead of testing each position.
def is_all_words(a_string, dictionary):
str_len = len(a_string)
S = [False] * (str_len)
# I replaced is_word function by a simple list lookup,
# feel free to replace it with whatever function you use.
# tries or suffix tree are best for this.
S[0] = (a_string[0] in dictionary)
for i in range(1, str_len):
check = a_string[0:i+1] in dictionary # i+1 instead of i
if (check):
S[i] = check
else:
for j in range(0,i+1): # i+1 instead of i
if (S[j-1] and (a_string[j:i+1] in dictionary)): # i+1 instead of i
S[i] = True
break
return S
a_string = "carrotforever"
S = is_all_words(a_string, ["a","car","carrot","for","eve","forever"])
print(S[len(a_string)-1]) #prints TRUE
a_string = "helloworld"
S = is_all_words(a_string, ["hello","world"])
print(S[len(a_string)-1]) #prints TRUE
For a real-world example of how to do English word segmentation, look at the source of the Python wordsegment module. It's a little more sophisticated because it uses word and phrase frequency tables but it illustrates the recursive approach. By modifying the score function you can prioritize longer matches.
Installation is easy with pip:
$ pip install wordsegment
And segment returns a list of words:
>>> import wordsegment
>>> wordsegment.segment('carrotfever')
['carrot', 'forever']
1) at first glance, looks good. One thing: for j in range(1, str_len): should be for j in range(1, i): I think
2) if S[str_len-1]==true, then the whole string should consist of whole words only.
After all S[i] is true iff
the whole string from 0 to i consists of a single dictionary word
OR there exists a S[j-1]==true with j<i, and the string[j:i] is a single dictionaryword
so if S[str_len-1] is true, then the whole string is composed out of dictionary words