How to join segments of a list - python-3.x

I have found different answers elsewhere that will work, but I can't quite figure out why my code is not working properly. What I am trying to do is take a list of alphabetical characters and join the first 4, second 4, third 4, etc. elements. I'll paste an example below to make this more clear.
If given the following list:
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'I', 'M', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
I want to combine the elements so that I receive the following output:
['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
I thought I identified a good solution on my own, but it doesn't seem to work. What I tried was:
x = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
y = 4
def wrap(string, max_width):
slist = [char for char in string]
new = []
for i in range(0, len(slist), max_width):
new.append(''.join(slist[i:max_width]))
return new
wrap(x, y)
The output that I get from this is:
['ABCD', '', '', '', '', '', '']
I would appreciate if if someone could help me identify what is wrong and help me fix it. Like I said previously, I have found other answers online that will do what I want, but I really want to figure out where I went wrong here.

It looks like there was logic issues in the for loop:
You were trying to add items between i:max_width. However max_width is always 4 and when i is > 4 you get no items return as it is an empty string.
Instead I have added max_width to meaning the grouping is always the same size:
x = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
y = 4
def wrap(string, max_width):
slist = [char for char in string]
new = []
for i in range(0,len(slist),max_width):
new.append(''.join(slist[i:(i+max_width)]))
return new
print(wrap(x, y))

Those earlier posts from #Peter Mason working fine as it just modified 'minimally' original code. However, the original code can be improved further to save a few steps: (the slist = .... is redundant, as string is a character sequence and can be directly index-access)
>>> s = uppers = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
>>> max_width = 4
>>> newStr = []
>>> for i in range(0, len(s), max_width):
newStr.append(''.join(s[i:i+4]))
>>> newStr
['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
>>>
Or, list comprehension:
def wrap(string, max_width):
return [''.join(string[i:i+max_width])
for i in range(0, len(string), max_width)]
>>> wrap(s, 4)
['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
>>>

Related

Pass cracker how not use four loops for four letters combination

I was practising for educational purpose with simply password cracker.
I know that I could use itertool but in my case when I'm learning I
would miss facing problems and learning on them and indeed I've met one
which is not giving me a peace.
What I want to learn is if I need get for example four combinations, so
how to get in a loop first letter 'a',then another step'a' and again 'a'
and 'a', to have 'aaaa' later on'abaa' etc.
So I wrote that:
import string
passe = 'zulu'
mylist = []
#letters = string.ascii_lowercase
letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'q', 'y', 'z']
mineset= set()
for a in letters:
for b in letters:
for c in letters:
for d in letters:
s = a + b + c + d
mylist.append(s)
mineset=set(mylist)
k = sorted(mineset)
print(k)
for i in k:
if i == passe:
print('got it: ', i )
print(passe in k)
It works in someway but the problems are:
I had to made a set from list because combinations
were repeated.
And finally, I was struggling with making it in without creating four
loops for four letters, something like that:
To try to solve those I went with that approach:
letters = ['a','b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'q', 'y', 'z']
password = 'pass'
combin = ''
lista=[]
for x in range(1,5):
for y in letters:
combin +=y
lista.append(combin)
combin=''
mineset=set(lista)
print(mineset)
for i in lista:
if i == password:
print('pass:', i)
But the results are disspainting:
{'abc', 'a', 'ab', 'abcd', 'abcde'}
I was seating on it for a long day but can't even closely achieve
similar effect to 4 loops in previous code.
While I don't recommend this approach as a general rule, for purposes of learning here is a way to achieve what you want:
def getCombos(lts):
rslt = []
for l1 in lts:
for l2 in lts:
for l3 in lts:
for l4 in lts:
s = l1+l2+l3+l4
rslt.append(s)
return rslt
letters = 'abcdefghijklmnopqrstuvwxyz'
getCombos(letters)
As is illustrated by a simple example, this code is of O(n^x) in complexity where n = number of characters and x = length of the letters. This approach, quickly becomes unwieldly as the following example illustrates:
getCombos('abc")
yields 81 entries including:
['aaaa',
'aaab',
'aaac',
'aaba',
'aabb',
'aabc',
'aaca',
'aacb',
'aacc',
'abaa',
'abab',
'abac',
'abba',
'abbb',
'abbc',
'abca',
'abcb',
'abcc',
'acaa',
'acab',
'acac',
'acba',
'acbb',
'acbc',
'acca',
'accb',
'accc',
'baaa',
'baab',
'baac',
'baba',
'babb',
'babc',
'baca',
'bacb',
'bacc',
'bbaa',
'bbab',
'bbac',
'bbba',
'bbbb',
'bbbc',
'bbca',
'bbcb',
'bbcc',
'bcaa',
'bcab',
'bcac',
'bcba',
'bcbb',
'bcbc',
'bcca',
'bccb',
'bccc',
'caaa',
'caab',
'caac',
'caba',
'cabb',
'cabc',
'caca',
'cacb',
'cacc',
'cbaa',
'cbab',
'cbac',
'cbba',
'cbbb',
'cbbc',
'cbca',
'cbcb',
'cbcc',
'ccaa',
'ccab',
'ccac',
'ccba',
'ccbb',
'ccbc',
'ccca',
'cccb',
'cccc']

How to convert a string to a list of characters in Python?

I know the string.split() function. What I want is to convert a particular word into a list. For eg converting a string 'python' to a list ['p', 'y', 't', 'h', 'o', 'n'].
In Python, you have to keep in mind that there are several data types which are iterables. In practice, this means you can go through each element one by one. Strings are no different:
>>> var = 'python'
>>> var[0]
p
>>> var[1]
y
The easiest way to construct a list out of an iterable is by using list:
>>> var = 'python'
>>> new_var = list(var)
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']
But it is not the only way, for example, you could use list-comprehensions to achieve the same (not that I advise you to use them)
>>> var = 'python'
>>> new_var = [c for c in var]
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']
Keeping in mind the idea of iterables is very useful because you can also transform your variable to other data types, such as a set:
>>> var = 'python'
>>> new_var = set(var)
>>> print(new_var)
{'o', 'y', 't', 'n', 'h', 'p'}
Which for the word Python is not very impressive, but if you use another one:
>>> var = 'mississippi'
>>> new_var = set(var)
>>> new_var
{'p', 'i', 's', 'm'}
You just get the used letters.

adding a string to a list is creating a list of characters

I'm trying to make a script that searches for emails inside a list. The problem is when adding the email found to the email list it returns the email string but it is chopped like in .split()
my_list = ['jose', 'ana', 'ana#gmail.com']
email_list = []
for i in my_list:
if '#gmail.com' in i:
print(i)
email_list += i
print(email_list)
the first print() statement returns what I expected 'ana#gmail.com', but when I print the email_list I get it all chopped, output:
ana#gmail.com
['a', 'n', 'a', '#', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm']
You can't add to a list like that. You'll want to use email_list.append(i)
Python does this because you can do mathematical operations on list and do fun things, e.g.
l = []
l = 5 * [2]
l
[2, 2, 2, 2, 2]

(Python) Replace array of string elements

I want to replace an array of string elements,but have a problem:
This is correct!!
However,this is error:
It seem replace first char....
Thanks to your help.
you have to specify dtype to get the expected behavior, else it will choose minimum size,
i think it is choosing chararray and you are trying add numbers/strings.
either use astype or numpy.array(data, dtype="") to set dtype, look at the syntax of numpy.arry below
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
set dtype to string/integer/float whatever you need, refere doucmentation for exact use
I suppose you want to replace some strings in the list with some numbers. You can do this easily with list comprehension like this.
data = ['C', 'C', 'W', 'C', 'H', 'H', 'W', 'C', 'W', 'H']
data = [15 if x == 'C' else 30 if x == 'W' else x for x in data]
# Output : [15, 15, 30, 15, 'H', 'H', 30, 15, 30, 'H']
I think you are using numpy with method array https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.array.html
The constructure has dtype, If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
So:
>>> data
['C', 'W', 'C', 'C', 'W', 'H']
>>> values = numpy.array(data)
>>> values
array(['C', 'W', 'C', 'C', 'W', 'H'], dtype='<U1')
values with dtype='<U1', that mean unicode length 1
Solution is set dtype is Unicode with length you want:
>>> values = numpy.array(data, dtype='<U256')
>>> values
array(['C', 'W', 'C', 'C', 'W', 'H'], dtype='<U256')
>>> values[values=='C'] = 15
>>> values
array(['15', 'W', '15', '15', 'W', 'H'], dtype='<U256')
That's right!

problems with a random number/letter generating script using the python random module

So I'm a bit of a Python beginner and I am wondering if there is a way to modify or fix this script so that it generates random number/letter sequences. I think I've got the actual generation solved, but I need some help on how to print the result to the console. Here is my code:
def main():
import random
random.random() * 10
myList = ["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"]
random.choice(myList)
print(random.random() * 10 + random.choice(myList))
main()
Can any of you guys help me out? as I said before, I am a beginner, so it might be a basic mistake and examples in answers would be great.
Error edited in:
line 9, in main
print(random.random() * 10 + random.choice(myList))
TypeError: unsupported operand type(s) for +: 'float' and 'str'
If you want to print a float, make a string from it:
def main():
import random
# random.random() * 10 # does nothing, you do not use the return
myList = ["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"]
# random.choice(myList) # does nothing, you do not use the return
print(str(random.random() * 10) + random.choice(myList))
# prints a [0.0-1.0[ * 10 + one character
main()
You can benefit from using a constant from string instead of your list - and probably want to use some other functions to draw from the list:
import string
import random
# prints random 20 lowercase chars w/o repeat
print(random.sample(string.ascii_lowercase,20)) # see doku for sample()
# print random 20 lowercase chars with repeat
print(random.choices(string.ascii_lowercase,k=20)) # see doku for choices()
# prints the same char multiple times
print(random.choice(string.ascii_lowercase) * random.randint(5,20))
Output:
['i', 'q', 's', 'z', 'g', 'v', 'r', 'j', 'h', 'u', 'y', 'p'
, 'n', 't', 'k', 'c', 'm', 'a', 'x', 'd']
['f', 'x', 'u', 'x', 'a', 'l', 'f', 'u', 'l', 'x', 'j', 'i'
, 'v', 'f', 'd', 'u', 'l', 'x', 'j', 'w']
rrrrrrrr # this one varies in char and amounts...
Doku of random - functions read up about sample, choices and random
Doku of string - constants
your lower case list is already a constant there.

Resources