I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:
letterlist = np.array([" ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY"
My goal is convert the letters to integer in order like A=1,B=2...Z=26 and " "=0. Then assign them to 1x3 arrays. like
But I couldn't even make a progress. First I tried make for loops to match same letter in the letter list and samplestr. Then if they are same, give the order in the letterlist as integer. But I didn't get any output.
for letter in samplestr:
for letter2 in letterlist:
if letter2==letter:
print("x") ## To see if I get any match
I don't know where did I wrong and how should I continue this. Would making dictionary make it easier to assign letters to integers? Need some advices. Thanks for your time.
The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'
Code looks like this:
from math import ceil
samplestr = "MEET ME MONDAY"
# Pad string to be dividable by 3
samplestr = samplestr.ljust(ceil(len(samplestr)/3) * 3)
# "MEET ME MONDAY "
# Convert to number reprensentation
samplestr = [0 if c == ' ' else (ord(c)-64) for c in samplestr]
# [13, 5, 5, 20, 0, 13, 5, 0, 13, 15, 14, 4, 1, 25, 0]
# Split in chunks of 3
matrix = [samplestr[i:i+3] for i in range(0, len(samplestr), 3)]
print(matrix)
This produces the following output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Yes, dictionary will make it easier to assign letters to integers but if your final goal is to convert the letters to integer in order like A=1, B=2...Z=26 and " "=0, then assigning indices to the letters will also do the job.
I don't have much knowledge of numpy, so I will do it simply like this:
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY "
l = []
s = []
for i in samplestr:
s.append(letterlist2.index(i))
if len(s) == 3:
l.append(s)
s = []
if s != []:
l.append(s)
print(l)
Output:
[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]
Use a dictionary (with a single list comprehension) to convert the letters to numbers (would probably be the fastest) and then reshape to have 3 columns (-1 will take care of number of rows):
convert = dict(zip(letterlist, np.arange(27)))
converted = np.array([convert[char] for char in samplestr])
#[13 5 5 20 0 13 5 0 13 15 14 4 1 25]
from math import ceil
#resize to closes upper multiple of 3
converted.resize(ceil(converted.size/3)*3)
#reshape to have 3 columns
converted = converted.reshape(-1,3)
output:
[[13 5 5]
[20 0 13]
[ 5 0 13]
[15 14 4]
[ 1 25 0]]
Here is another solution with a simple dictionary mapping and list comprehensions. Note that you don't need to hardcode letters, it's in the standard library.
from string import ascii_uppercase
chars = " " + ascii_uppercase
encode = {char:"{}".format(i) for i, char in enumerate(chars)}
def str2num(s):
return [[encode[char] for char in s[i:i+3]] for i in range(0, len(s), 3)]
s = "MEET ME MONDAY"
print(str2num(s))
which returns:
[['13', '5', '5'],
['20', '0', '13'],
['5', '0', '13'],
['15', '14', '4'],
['1', '25']]
Related
Could someone, please, explain why .join() behaves in the following way:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join(str(input))
print(a)
And the result is:
[ 1 , 0 , 5 , 3 , 4 , 1 2 , 1 9 ]
Not only is there still a list, but also an additional space.
How come?
When I use map() it works:
a = " ".join(list(map(str, input)))
But I would like to know what is wrong with the .join method I'm using.
str(input) returns one string '[1, 0, 5, 3, 4, 12, 19]', so then join uses each character of the string as input (a string is an iterable, like a list), effectively adding a space between each.
The effect is more visible if we join with a -: '[-1-,- -0-,- -5-,- -3-,- -4-,- -1-2-,- -1-9-]'
In contrast, list(map(str, input)) converts each number to string, giving a list of strings (['1', '0', '5', '3', '4', '12', '19']), which join then converts to '1 0 5 3 4 12 19'
See #mozway's answer to understand .join()'s behavior.
To get what you want (using join), you should try this:
input = [1, 0, 5, 3, 4, 12, 19]
a = " ".join([str(i) for i in input])
print(a)
Output:
1 0 5 3 4 12 19
Well, I have a numpy array like that:
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
My desired output is:
b=['87654321','161514131211109','2423222120191817']
For it, I need first to split "a" into arrays of 8 elements and then I have a list like that:
np.split(a) = [array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int8),
array([9, 10, 11, 12, 13, 14, 15, 16], dtype=int8),
array([17, 18, 19, 20, 21, 22, 23, 24], dtype=int8)]
so, I need to invert each array into it and join the numbers to make like a list of joint numbers.
No need for numpy, though it will work for an array as well. One way:
>>> [''.join(str(c) for c in a[x:x+8][::-1]) for x in range(0, len(a), 8)]
['87654321', '161514131211109', '2423222120191817']
Try this. You reshape your data and then convert it to string elements. Loop it and append it to new list.
import numpy as np
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
lst = list(np.array(a).reshape(3,8).astype("U"))
my_lst = []
for i in lst:
my_lst.append("".join(i[::-1]))
print(my_lst)
The simplest way is first to reverse the original array (or create a reversed copy), and then to split:
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
acopy = a[::-1]
splitted = np.array_split(acopy, 3)
print(splitted[0]) # [24 23 22 21 20 19 18 17]
print(splitted[1]) # [16 15 14 13 12 11 10 9]
print(splitted[2]) # [8 7 6 5 4 3 2 1]
Now when lists are reversed, you can join elements of each list to make strings:
str1 = ''.join(str(x) for x in splitted[0]) # '2423222120191817'
str2 = ''.join(str(x) for x in splitted[1]) # '161514131211109'
str3 = ''.join(str(x) for x in splitted[2]) # '87654321'
I am trying to create a class that takes a string of digits with hard coded line breaks and outputs a matrix and details about that matrix. In the first instance i just want to be able to create the matrix but I am struggling. I'm aware that I could probably do this very easily with numpy or something similar but trying to practice.
class Matrix:
def __init__(self, matrix_string):
self.convert_to_list = [int(s) for s in str.split(matrix_string) if s.isdigit()]
self.split = matrix_string.splitlines()
I think i want to combine the two things I have already done but I cant figure out how to apply my convert_to_list method to every element in my split method.
Getting very confused.
SAMPLE INPUT/OUTPUT
Input = " 1 8 7 /n 6 18 2 /n 1 9 7 "
Desired Output = [[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It looks like you want a list of lists. For that you can use nested list comprehension.
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
lst = [[int(x) for x in r.split()] for r in s.split('/n')]
print(lst)
Output
[[1, 8, 7], [6, 18, 2], [1, 9, 7]]
It's not that hard actually:
s = " 1 8 7 /n 6 18 2 /n 1 9 7 "
print([i.split() for i in s.split('/n')])
easier way but longer:
s = s.split('/n')
new = []
for i in s:
new.append(i.split())
print(new)
output:
[['1', '8', '7'], ['6', '18', '2'], ['1', '9', '7']]
I am having a problem in my code first see the code I have a list
numbers = [3, 10, 12 ,14, 15, 17, 20]
I want to print all the numbers in the list but I want to have the number of the element before the element so my output should be
1 3
2 10
3 12
and so on I have tried this
for m in range(1 , len(numbers) + 1)
print(m , end = '')
for i in numbers:
print(numbers)
How can I acomplish this
The print statement accepts multiple arguments and prints them with a space in between.
print("hi", "there")
-> "hi there"
So you want:
for i in range(len(numbers)):
print(i, numbers[i])
Note, Python indexes from 0, not 1.
You can use enumerate, which will give you the index first. (and add 1 if you want the location).
numbers = [3, 10, 12 ,14, 15, 17, 20]
for idx,m in enumerate(numbers):
print(idx+1,' ',m)
Output:
1 3
2 10
3 12
I think you are beginner so here is simple solution
numbers = [3, 10, 12 ,14, 15, 17, 20]
count =0
for i in numbers:
count+=1
print(str(count)+ " " + str(i))
say I have a string n = '22' and another number a = 4 so that n is a str and a is an int. I would like to create a group of lists like:
list1 = [22, 12, 2] #decreasing n by 10, the last item must be single digit, positive or 0
list2 = [22, 11, 0] #decreasing n by 11, last item must be single digit, positive or 0
list3 = [22, 21, 20] #decreasing n by 1, last item must have last digit 0
list4 = [22, 13] #decreasing n by 9, last item must be single digit. if last item is == a, remove from list
list5 = [22, 32] #increasing n by 10, last item must have first digit as a - 1
list6 = [22, 33] #increasing n by 11, last item must have first digit as a - 1
list7 = [22, 23] #increasing n by 1, last item must have last digit a - 1
list8 = [22, 31] #increasing n by 9, last item must have first digit a - 1
I am struggling on how to start this. Maybe you can give me an idea of how to approach this problem?
By the way if a condition cannot be satisfied, then only n will be on that list. say n = '20', a = 4:
list3 = [20]
Also this is for a school project, for indexes in a list which has list items. I can't think of a better way to approach the problem.
This should get you started:
def lbuild( start, inc, test ):
rslt = [start]
while not test(start,inc):
start += inc
rslt.append( start )
return rslt
n = '22'
a = 4
nval = int(n)
print lbuild( nval, -10, lambda(x,y): (x<10 and x>=0) )
print lbuild( nval, 1, lambda(x,y): x%10 == a-1 )