Python exercise about finding indices of X in the list - python

def leesFormulier(l1):
index = 0
lres = []
for j in range(len(l1)):
for k in range(0,9,2):
if l1[j][k] == 'X':
lres.append(index+1)
index += 1
else:
index += 1
return lres
print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))
result : [2, 5, 6, 8, 9]
Hello everybody,
I'm making an exercise on Python and I have to find the indices of where you can find the 'X'. And I solved it for the most part but the only problem I'm having is the last 'X' that won't be recognized. I put it in Pythontutor and there I could see that on the last time going through the for loops that it goes to the last k for loop but it doesn't check it but instead goes immediately to the j for lus and then ends the iteration and goes to the return part. I don't know what I'm doing wrong, would appreciate it if somebody could help me out.
Thanks in advance!

Don't need all those indexes or nested loops for this problem and you can simplify it a lot
def lessFromulier(l1):
lres = []
new_string = " ".join(l1).split(" ")
for i, letter in enumerate(new_string):
if letter == "X":
lres.append(i+1)
return lres
test = [
"1 X 3 4 X",
"X 7 X X 10",
"11 12 13 14 15",
"16 17 18 19 20",
"21 22 23 24 25",
"26 27 28 29 30",
"31 32 33 34 35",
"36 37 38 39 40",
"41 42 43 44 X",
]
print(lessFromulier(test))
which gives this output
[2, 5, 6, 8, 9, 45]

Your input is really weird to me, but here is a solution to your question
def leesFormulier(l1):
index = 0
lres = []
for i in range(len(l1)):
for j in range(len(l1[i])):
c = l1[i][j]
if c == ' ':
continue
if c == 'X':
index += 1
lres.append(index)
else:
index += 1
return lres
print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))

Related

Splitting multiple, spaced-list values in Python [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
How do I make a flat list out of a list of lists?
(34 answers)
Closed 1 year ago.
I have a very simple list where it looks like this:
['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
What I would like to do is to split the values within each list where the values are displayed as follows:
[20,32,35,47,64,15,17,25,32,53,07,10,12,61,65,..]
myvallist = myvalues.split(" ")
print (myvallist)
For some reason, when I attempt to use the .split(), pyCharm is throwing an error.
Traceback (most recent call last):
File "C:\Users\VFARETR.CENTRAL\Desktop\pyCharm\megaTest", line 25, in <module>
myvallist = myvalues.split(" ")
AttributeError: 'list' object has no attribute 'split'
Any help would be great!
You're trying to split the list, not the string. Try this:
input_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
complete_list = []
for sub_list in input_list:
current_items = sub_list.split()
complete_list.extend([i for i in current_items])
It says so because your list consists of strings. You have to acces the string inside the list before you split the string.
mylist = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65',
'08 14 31 58 68', '01 10 44 47 56']
myvallist = []
for item in mylist:
myvallist += item.split(' ') # adds the numbers of the current string to myvallist
print(myvallist)
I don't know if you want the entries to be integers or strings but here's a solution with them as strings.
my_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
my_new_list = [item for sublist in [item.split(" ") for item in my_list] for item in sublist]
The inner list comprehension splits each string by spaces and then the outer list comprehension then flattens the array produced.

subtract two columns in a data frame if they have the same ending in a loop

If my data looks like this
Index Country ted_Val1 sam_Val1 ... ted_Val10 sam_Val10
1 Australia 1 3 ... 20 5
2 Bambua 12 33 ... 15 56
3 Tambua 14 34 ... 10 58
df = pd.DataFrame([["Australia", 1, 3, 20, 5],
["Bambua", 12, 33, 15, 56],
["Tambua", 14, 34, 10, 58]
], columns=["Country", "ted_Val1", "sam_Val1", "ted_Val10", "sam_Val10"]
)
I'd like to subtract all 'val_' columns from all 'ted_' values using a list, creating a new column starting with 'dif_' such that:
Index Country ted_Val1 sam_Val1 diff_Val1 ... ted_Val10 sam_Val10 diff_val10
1 Australia 1 3 -2 ... 20 5 -15
2 Bambua 12 33 12 ... 15 56 -41
3 Tambua 14 34 14... 10 58 -48
so far I've got:
calc_vars = ['ted_Val1',
'sam_Val1',
'ted_Val10',
'sam_Val10']
for i in calc_vars:
df_diff['dif_' + str(i)] = df.['ted_' + str(i)] - df.['sam_' + str(i)]
but I'm getting errors, not sure where to go from here. As a warning this is dummy data and there can be several underscores in the names
IIUC you can use filter to choose the columns for subtraction (assuming your columns are properly sorted like your sample):
print (pd.concat([df, pd.DataFrame(df.filter(like="ted").to_numpy()-df.filter(like="sam").to_numpy(),
columns=["diff"+i.split("_")[-1] for i in df.columns if "ted_Val" in i])],1))
Country ted_Val1 sam_Val1 ted_Val10 sam_Val10 diff1 diff10
0 Australia 1 3 20 5 -2 15
1 Bambua 12 33 15 56 -21 -41
2 Tambua 14 34 10 58 -20 -48
try this,
calc_vars = ['ted_Val1', 'sam_Val1', 'ted_Val10', 'sam_Val10']
# extract even & odd values from calc_vars
# ['ted_Val1', 'ted_Val10'], ['sam_Val1', 'sam_Val10']
for ted, sam in zip(calc_vars[::2], calc_vars[1::2]):
df['diff_' + ted.split("_")[-1]] = df[ted] - df[sam]
Edit: if columns are not sorted,
ted_cols = sorted(df.filter(regex="ted_Val\d+"), key=lambda x : x.split("_")[-1])
sam_cols = sorted(df.filter(regex="sam_Val\d+"), key=lambda x : x.split("_")[-1])
for ted, sam in zip(ted_cols, sam_cols):
df['diff_' + ted.split("_")[-1]] = df[ted] - df[sam]
Country ted_Val1 sam_Val1 ted_Val10 sam_Val10 diff_Val1 diff_Val10
0 Australia 1 3 20 5 -2 15
1 Bambua 12 33 15 56 -21 -41
2 Tambua 14 34 10 58 -20 -48

Replace w/Alphabet Position Challenge in Code Wars: getting right result but not passing any tests?

I am working on the "Replace With Alphabet Position" challenge in Code Wars. For some reason, I have been getting the exact same results as the sample tests but I'm not passing any of the sample tests. I'm thinking that maybe my output type is still a list even though I tried converting it to a string? Any advice?
from string import *
def alphabet_position(text):
alphabet_dict = {}
alphabet = 'abcdefghijklmnopqrstuvwxyz'
value = 0
spaceless_list = []
# assigns values to letters
for letter in alphabet:
value += 1
alphabet_dict.update( {letter : value} )
# checks dictionary keys for letter value and adds letter value to list; excludes spaces and "
for unit in text:
if unit.lower() in alphabet_dict.keys():
letter_value = alphabet_dict.get(unit.lower(), unit)
spaceless_list.append(letter_value)
elif unit == ' ' or "'":
del unit
continue
else:
continue
list_to_str = ' '.join([str(elem) for elem in spaceless_list])
print(f"'{list_to_str}'")
Test Results:
Log: '20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
None should equal '20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
I was printing my code rather than returning it. Question is solved.

Printing a rather specific matrix

I have a list consisting of 148 entries. Each entry is a four digit number. I would like to print out the result as this:
1 14 27 40
2 15 28 41
3 16 29 42
4 17 30 43
5 18 31 44
6 19 32 45
7 20 33 46
8 21 34 47
9 22 35 48
10 23 36 49
11 24 37 50
12 25 38 51
13 26 39 52
53
54
55... and so on
I have some code that work for the first 13 rows and 4 columns:
kort_identifier = [my_list_with_the_entries]
print_val = 0
print_num_1 = 0
print_num_2 = 13
print_num_3 = 26
print_num_4 = 39
while (print_val <= 36):
print kort_identifier[print_num_1], '%10s' % kort_identifier[print_num_2], '%10s' % kort_identifier[print_num_3], '%10s' % kort_identifier[print_num_4]
print_val += 1
print_num_1 += 1
print_num_2 += 1
print_num_3 += 1
print_num_4 += 1
I feel this is an awful solution and there has to be a better and simpler way of doing this. I have searched through here (searched for printing tables and matrices) and tried those solution but none seems to work with this odd table/matrix behaviour that I need.
Please point me in the right direction.
A bit tricky, but here you go. I opted to manipulate the list until it had the right shape, instead of messing around with indexes.
lst = range(1, 149)
lst = [lst[i:i+13] for i in xrange(0, len(lst), 13)]
lst = zip(*[lst[i] + lst[i+4] + lst[i+8] for i in xrange(4)])
for row in lst:
for col in row:
print col,
print
It might be overkill, but you could just make a numpy array.
import numpy as np
x = np.array(kort_identifier).reshape(2, 13, 4)
for subarray in x:
for row in subarray:
print row

Reading non-uniform data from file into array with NumPy

Suppose I have a text file that looks like this:
33 3
46 12
23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16
33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19
41 32 41 33 42 32 42 33
I would like to read each line into a separate array of integers, as in (pseudo code):
for line in textfile:
currentArray = firstLine
do stuff with currentArray
where in the first iteration, currentArray would be
array([33, 3])
and in the second iteration, currentArray would be
array([46, 12])
until the last iteration, when currentArray would be
array([41, 32, 41, 33, 42, 32, 42, 33])
Basically, I would like to have the functionality of the numpy function loadtxt:
currentArray = loadtxt('scienceVertices.txt', usecols=() )
Except instead of usecols, being able to specify the row, e.g.,
currentArray = loadtxt('scienceVertices.txt', userows=(line) )
Here's a one-liner:
arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]
arrays is a list of numpy arrays.
for line in textfile:
a = np.array([int(v) for v in line.strip().split(" ")])
# Work on your array
You can also use numpy.fromstring()
for line in f:
a = numpy.fromstring(line.strip(), dtype=int, sep=" ")
or -- if you want full flexibility -- even numpy.loadtxt():
for line in f:
a = numpy.loadtxt(StringIO.StringIO(line), dtype=int)
For long lines, these solution will perform better than the Python code in the other answers.
f = open("file", "r")
array = []
line = f.readline()
index = 0
while line:
line = line.strip("\n")
line = line.split()
array.append([])
for item in line:
array[index].append(int(item))
line = f.readline()
index += 1
f.close()
print array

Categories