List containing lists (matrix) as input() with python 3 - python-3.x

I'm trying to convert a given input to a list containing lists as shown in the command-line code below:
matrix = input('asking')
asking[[2, 0, 4],[1, 2, 4],[4, 4, 2]]
matrix
'[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
desired output:
[[2,0,4],[1,2,4],[4,4,2]]
Attempts
list(matrix)
['[', '[', '2', ',', ' ', '0', ',', ' ', '4', ']', ',', ' ', '[', '1', ',', ' ', '2', ',', ' ', '4', ']', ',', ' ', '[', '4', ',', ' ', '4', ',', ' ', '2', ']', ']']
x = [int(a) for a in matrix]
builtins.TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
matrix.split(',')
['[[2', '0', '4]', '[1', '2', '4]', '[4', '4', '2]]']
Code:
fin_result = 0
def perform_check():
print("Enter form \n [[a,b,c] \n [d,e,f] \n [g,h,i]]")
#ask_for_input = [[4,-1,1],[4,5,3],[-2,0,0]]
ask_for_input = [[2,0,4],[1,2,4],[4,4,2]]
print(type(ask_for_input))
#call function to cont
calculate_determinate_matrix(ask_for_input)
def calculate_determinate_matrix(matrix3x3):
matrix_list2x2 = []
matrix_list2x2.append([[matrix3x3[1][1], matrix3x3[1][2]], [matrix3x3[2][1], matrix3x3[2][2]]])
matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][2]],[matrix3x3[2][0], matrix3x3[2][2]]])
matrix_list2x2.append([[matrix3x3[1][0], matrix3x3[1][1]],[matrix3x3[2][0], matrix3x3[2][1]]])
count = 0
for count, matrix_2x2 in enumerate(matrix_list2x2):
if count % 2 == 1:
calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count] * -1)
else:
calculate_2x2_matrix(matrix_2x2, matrix3x3[0][count])
def calculate_2x2_matrix(matrix, mult):
global fin_result
result = matrix[0][0] * matrix[1][1]
result_2 = matrix[0][1] * matrix[1][0]
fin_result += mult * (result - result_2)
def main():
perform_check()
print(fin_result)
if __name__ == "__main__":
main()
Clearly this code needs work, but I can't figure this in terms of list comprehension.

Use json loads() method:
matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = json.loads(matrix)
type(matrix)
<type 'list'>
And in case you want to check for errors in input you can wrap it in try-except:
try:
matrix = json.loads(matrix)
except ValueError:
#code goes here

An alternative to json.loads is ast.literal_eval. It has the advantage that it recognizes Python syntax even if it was invalid JSON, like single-quoted strings. In your exact case, it doesn't make a difference:
import ast
matrix = '[[2, 0, 4],[1, 2, 4],[4, 4, 2]]'
matrix = ast.literal_eval(matrix)

Related

Values in a list to a range()

I have a user input which comes in as follows:
j = ['1', '2', '3', '4', '5-6', '7-9']
I want to go through this list, identify any 'ranges' such as 7-8, or 5-99 etc.
With these remove the - and put the first and second values into range()
So far I have the following, I just can't figure out how to get the values into the right place, perhaps I need to select the number before the - and after the - ?
for item in j:
if "-" in item:
item = item.split("-")
# list(map(str, range(244, 247)))
for r in item:
print(r)
print('next')
# something like this?
list(map(str, range(int(item[0]), int(item[1]))))
EDIT
Taking into account jonrsharpe's comment:
for item in j:
if "-" in item:
start, stop = item.split("-")
print('start:' + start + ' end: ' + stop)
list(map(str, range(int(start), int(stop))))
This returns a type error TypeError: 'str' object is not callable
Assuming the output expected is j = [1, 2, 3, 4, 5, 6, 7, 8, 9]
You can create a blank list, process each element depending on whether or not it has a "-"
l = ['1', '2', '3', '4', '5-6', '7-9']
ll = []
for element in l:
if '-' in element:
sublist = element.strip().split('-')
sublist = list(range(int(sublist[0]), int(sublist[1]) + 1))
ll += sublist
else:
ll.append(int(element))
One approach is to create a list of items for both single numbers and ranges, and then use this as the argument to range:
j = ['1', '2', '3', '4', '5-6', '7-9']
for item in j:
if '-' in item:
rng = [int(x) for x in item.split('-')]
else:
# Start and stop are the same
rng = [int(item)] * 2
# Pad the stop number
rng[1] += 1
for i in range(*rng):
print(i)

Trouble with a python loop

I'm having issues with a loop that I want to:
a. see if a value in a DF row is greater than a value from a list
b. if it is, concatenate the variable name and the value from the list as a string
c. if it's not, pass until the loop conditions are met.
This is what I've tried.
import pandas as pd
import numpy as np
df = {'level': ['21', '22', '23', '24', '25', '26', '27', '28', '29', '30']
, 'variable':'age'}
df = pd.DataFrame.from_dict(df)
knots = [0, 25]
df.assign(key = np.nan)
for knot in knots:
if df['key'].items == np.nan:
if df['level'].astype('int') > knot:
df['key'] = df['variable']+"_"+knot.astype('str')
else:
pass
else:
pass
However, this only yields the key column to have NaN values. I'm not sure why it's not placing the concatenation.
You can do something like this inside the for loop. No need of any if conditions:
df.loc[df['level'].astype('int') > 25, 'key'] = df.loc[df['level'].astype('int') > 25, 'variable'] + '_' + df.loc[df['level'].astype('int') > 25, 'level']

How to Sort a SubList containing String and Int as string

I need to Sort the list according to the integer which are in form of string and list also contains stings alphabets.
li = [['dr','3','mn'],['fs','1','a'],['2','rt',c]]
I need the output like:
li = [['fs','1','a'],['2','rt',c],['dr','3','mn']]
or
li = [[1,'fs','a'],[2,'rt',c],[3,'dr','mn']]
in any of the format like these.
This code supposes the numbers are integers and in each list there's at least one number:
li = [['11','rt','c'],['dr','3','mn'],['fs','1','a'],['2','rt','c']]
def is_number(s):
try:
i = int(s)
return True
except ValueError:
return False
print([li[i[-1]] for i in sorted([[int(j), ii] for ii, i in enumerate(li) for j in i if is_number(j)])])
Prints:
[['fs', '1', 'a'], ['2', 'rt', 'c'], ['dr', '3', 'mn'], ['11', 'rt', 'c']]

Python - match dictionary value within string & print key in string order

I asked a similar question to this earlier on but Im still having a hard time figuring this out. I have the following code:
d = {'k' : '10', 'a' : '20', 'r' : '30', 'p' : '401'}
string = '401203010'
text = ''
for i, j in d.items():
if j in string:
text += i
print(text) #prints karp
desired output: park
the output I get is karp, however I would like the output to be in order of value match in the string, Thanks!
try this maybe?
d = {'k' : '10', 'a' : '20', 'r' : '30', 'p' : '40'}
string = '40203010'
text = ''
keylen = len(''.join(d.keys()))
while len(text) != keylen:
found_val = 0
for i, j in d.items():
jl = len(j)
if string[:jl] == j:
text += i
string = string[jl:]
found_val += 1
if found_val == 0:
break
print(text)
for the sake of clarity, this is really not an algorithm you want to use here. For example one of the downfalls is if it isn't guaranteed that a part of the string will be in the dictionary values then the loop will never end. I don't want to spend the mental resources to fix that potential pitfall because I have some reading to do but perhaps you can figure out a way around it.
edit, never mind that wasn't that difficult but you should test various edge cases.
You could first split up string into substrings of 2, and then switch the keys ad values of d in a temporary dictionary, then just add the values from that:
d = {'k' : '10', 'a' : '20', 'r' : '30', 'p' : '40'}
string = '40203010'
text = ''
split_string = [string[i:i+2] for i in range(0, len(string), 2)]
# ['40', '20', '30', '10']
new_dict = dict((y,x) for x,y in d.items())
# {'30': 'r', '10': 'k', '20': 'a', '40': 'p'}
text = "".join(new_dict[string] for string in split_string)
print(text)
# park

Python: replace list items and produce all possible permutations

I am trying to implement morse decode for partial morse code.Say for example the representation of word TEST in morse code is ['-','.','...','-'] however if the first character of every morse code string is missing and represented by x then partial morse code for TEST will become ['x','x','x..','x'].Thus in order to decode this partial message, we will have to replace x with either. or - for every occurrence of x in above partial morse code.With 'x' unknown the permutations of TEST word on decoding would be ETST,EEDT,ETSE etc.I have implemented the morse partial decode function as below:
def morsePartialDecode(inputStringList):
with open('words.txt','a') as wordfile:
dictionaryFileLoc = './dictionary.txt'
message_received = inputStringList
message_received = ' '.join(inputStringList)
for i in range(len(message_received)):
x = 'x'
y = '.'
message = message_received.replace(x, y)
message1 = message.split(",")
message_converted = morseDecode(message1)
print message_converted
print >> wordfile, (message_converted)
for i in range(len(message_received)):
x = 'x'
y = '-'
message = message_received.replace(x, y)
message2 = message.split(",")
message_converted = morseDecode(message2)
print >> wordfile, (message_converted)
elements = []
wordfile.closed
return message_converted
def partialMorseCodeTest():
test = ['x', 'x', 'x..', 'x']
print morsePartialDecode(test)
partialMorseCodeTest()
Output:
EESE
TTDT
I need all the combinations of ['x','x','x..','x'] with x replaced by . or -.And my morseDecode() will convert each combination to respective words like EESE, TTDT etcmorsedecode)What to do.Thanks in advance!
Great case for itertools
Example using itertools.product:
from itertools import product
def replace_x_with_all_combinations(morse):
# only works with 1 and 1 only 'x' in each element
all_perm = list()
for v in morse:
if 'x' in v:
# create a list of permutations per element of the morse list
# and append them to the all_perm list
all_perm.append([v.replace('x','.'), v.replace('x','-')])
else:
# if no x found, then append the original element
all_perm.append([v])
# all_perm = [['.', '-'], ['.', '-'], ['...', '-..'], ['.', '-']]
# the list all_perm needs to be unpacked before passing
# to the product() generator, hence the *
return list(product(*all_perm))
partial = ['x','x','x..','x']
result = replace_x_with_all_combinations(partial)
for e in result:
print(e)
Output:
('.', '.', '...', '.')
('.', '.', '...', '-')
('.', '.', '-..', '.')
('.', '.', '-..', '-')
('.', '-', '...', '.')
('.', '-', '...', '-')
('.', '-', '-..', '.')
('.', '-', '-..', '-')
('-', '.', '...', '.')
('-', '.', '...', '-')
('-', '.', '-..', '.')
('-', '.', '-..', '-')
('-', '-', '...', '.')
('-', '-', '...', '-')
('-', '-', '-..', '.')
('-', '-', '-..', '-')
[EDIT]
Although I put the restriction in the above code myself, the "works only for 1 x in the morse character" bugged me, so the following example will take more than one digit missing from a morse character, more than one 'x'
from itertools import product
def replace_x_in_morse_charcter(morse_character):
all_perm = [['.','-'] if c == 'x' else [c] for c in morse_character]
p = list(product(*all_perm))
return [''.join([v for v in e]) for e in p]
def replace_x_in_morse_word(morse):
all_perm = [replace_x_in_morse_charcter(c) for c in morse]
return list(product(*all_perm))
partial = ['x','x','x..','xx']
result = replace_x_in_morse_word(partial)
for e in result:
print(e)
[EDIT] for fun a one liner:
morse_word = ['x','x','x..','xx']
result = list(product(*[[''.join([v for v in e]) for e in list(product(*[['.','-'] if c == 'x' else [c] for c in cm]))] for cm in morse_word]))

Resources