Session in GAE separated in comma's - python

sample i have a list:
sample = [a, b, c, d]
Then I want to pass the sample to the session:
self.session['sample'] = None #declaring the session...
for item in sample:
self.session['sample'] = str(self.session['sample']) + "," + str(item)
But the output is:
None, a, b, c, d
I want the value of my session['sample'] would be = a, b, c, d

You could do it in one line instead of a loop with join() and list comprehension:
self.session['sample'] = ", ".join(str(item) for item in sample)
If you're happy doing it in a loop, you need to make the first item "" instead of None:
self.session['sample'] = "" # Empty string
for item in sample:
self.session['sample'] += "," + str(item) # Note I've used += here
a += 1 is just a tidy way to write a = a + 1

Related

How to concatenate line space string in python

I have a python code which is on seperate line and want to get a response with "\n". When I write a code
txt="""a
b
c
d"""
txt = str.join(" ", txt.splitlines())
x = txt.split()
s = ""
for item in x:
s += item + "\ n"
print(s)
it gives me response correctly because i have a space:
a\ nb\ nc\ nd\ n
But if i take sspace between \ and n I get response back as
a
b
c
d
I want one blob and should be give me response as a blob of one character.
Great thank you. I just had to add two // and it worked.
txt="""a
b
c
d"""
txt = str.join(" ", txt.splitlines())
x = txt.split()
s = ""
for item in x:
s += item + "\\n"
print(s)

How can you delete similar characters at the same positions in 2 strings

I need to figure out a way to delete common characters from two strings if the common characters are in the same position, but it is not working and I am trying to figure this out. This is what I tried so far, it works for some strings, but as soon as the second string is larger than the first, it stops working. EDIT: I also need a way to store the result in a variable before printing it as I need to use it in another function.
Example :
ABCDEF and ABLDKG would result in the "ABD" parts of both strings to be deleted, but the rest of the string would remain the same
CEF and LKG would be the output
def compare(input1,input2):
if len(input1) < len(input2):
for i in input1:
posi = int(input1.find(i))
if input1[num] == input2[num]:
x = input1.replace(i,"" )
y = input2.replace(i,"" )
num = num+1
print(x)
print(y)
else:
for i in input2:
num = 0
posi = int(input2.find(i))
if input2[num] == input1[num]:
input1 = input1[0:num] + input1[num+1:(len(input1)+ 1 )] # input1.replace(i,"" )
input2 = input2[0:num] + input2[num+1:(len(input1) + 1)]
x = input1
y = input2
num = num + 1
print(str(x))
print(str(y))
you could use
from itertools import zip_longest
a,b = "ABCDEF","ABLDKG"
[''.join(k) for k in zip(*[i for i in zip_longest(a, b, fillvalue = "") if i[0]!=i[1]])]
['CEF', 'LKG']
You can wrap this in a function:
def compare(a, b):
s = zip(*[i for i in zip_longest(a, b, fillvalue = "") if i[0]!=i[1]])
return [''.join(k) for k in s]
compare("ABCDEF","ABLDKG")
['CEF', 'LKG']
compare('asdfq', 'aqdexyz')
['sfq', 'qexyz']
strlist = ["ABCDEF","ABLDKG"]
char_dict = dict()
for item in strlist:
for char in item:
char_dict[char] = char_dict.get(char,0) + 1
new_strlist = []
for item in strlist:
new_strlist.append(''.join([char for char in item if char_dict[char] < 2]))
Note that this will convert strings that have only duplicates into empty strings rather than removing them altogether.

Python find similar sequences in string

I want a code to return sum of all similar sequences in two string. I wrote the following code but it only returns one of them
from difflib import SequenceMatcher
a='Apple Banana'
b='Banana Apple'
def similar(a,b):
c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks()
return sum( [c[i].size if c[i].size>1 else 0 for i in range(0,len(c)) ] )
print similar(a,b)
and the output will be
6
I expect it to be: 11
get_matching_blocks() returns the longest contiguous matching subsequence. Here the longest matching subsequence is 'banana' in both the strings, with length 6. Hence it is returning 6.
Try this instead:
def similar(a,b):
c = 'something' # Initialize this to anything to make the while loop condition pass for the first time
sum = 0
while(len(c) != 1):
c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks()
sizes = [i.size for i in c]
i = sizes.index(max(sizes))
sum += max(sizes)
a = a[0:c[i].a] + a[c[i].a + c[i].size:]
b = b[0:c[i].b] + b[c[i].b + c[i].size:]
return sum
This "subtracts" the matching part of the strings, and matches them again, until len(c) is 1, which would happen when there are no more matches left.
However, this script doesn't ignore spaces. In order to do that, I used the suggestion from this other SO answer: just preprocess the strings before you pass them to the function like so:
a = 'Apple Banana'.replace(' ', '')
b = 'Banana Apple'.replace(' ', '')
You can include this part inside the function too.
When we edit your code to this it will tell us where 6 is coming from:
from difflib import SequenceMatcher
a='Apple Banana'
b='Banana Apple'
def similar(a,b):
c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks()
for block in c:
print "a[%d] and b[%d] match for %d elements" % block
print similar(a,b)
a[6] and b[0] match for 6 elements
a[12] and b[12] match for 0 elements
I made a small change to your code and it is working like a charm, thanks #Antimony
def similar(a,b):
a=a.replace(' ', '')
b=b.replace(' ', '')
c = 'something' # Initialize this to anything to make the while loop condition pass for the first time
sum = 0
i = 2
while(len(c) != 1):
c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks()
sizes = [i.size for i in c]
i = sizes.index(max(sizes))
sum += max(sizes)
a = a[0:c[i].a] + a[c[i].a + c[i].size:]
b = b[0:c[i].b] + b[c[i].b + c[i].size:]
return sum

Too many values to unpack or 0 values to unpack

I have this code and I am trying to use the list splits
but either I get Too many values to unpack or need more than 0 values to unpack
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
temp1 = []
for i in splits:
temp = list(i)
for j in range(0,len(temp)):
temp1.append(temp[j])
splits = temp1
for s in splits:
print s
#here
deletes = [a + b[1:] for a, b in splits if b]
return set(deletes)

Check the elements of the lists

a = ["000000001111111110101010","111111110000111111000011"]
what I need to do is check my list(a),
for item in a:
for elements in range(len(a[item])):
if "0" in a or "1" in a:
random change one elements in a[item](0 change to 1 or 1 change to 0) just one element,how can I do this
in my question if all elements changed should be:
a = ["111111110000000001010101","000000001111000000111100"]
if just one elements changed should be:
a =["000000001111101110101010","111111110000111111001011"]
just random pick 0 or 1 to change to 1 or 0
The source code below works for me:
a = ['000000001111111110101010',"111111110000111111000011"]
print(a)
ret = []
for item in a:
r = ''
for i in item:
b = int(i, base=2)
c = str(int(not b))
r = r + c
ret.append(r)
print(ret)
And the output is:
['000000001111111110101010', '111111110000111111000011']
['111111110000000001010101', '000000001111000000111100']
Here are both, flipping all digits and flipping one random digit:
import random
def flip_all(s):
s = list(s)
return ''.join([str(1 - int(c)) for c in s])
def flip_one(s):
s = list(s)
rand_i = random.randint(0, len(s)-1)
s[rand_i] = str(1 - int(s[rand_i]))
return ''.join(s)
a = ["000000001111111110101010","111111110000111111000011"]
print("a: ", a)
print("flip all: ", [flip_all(word) for word in a])
print("flip one: ", [flip_one(word) for word in a])
Output:
a: ['000000001111111110101010', '111111110000111111000011']
flip all: ['111111110000000001010101', '000000001111000000111100']
flip one: ['000000001101111110101010', '111111110000111110000011']

Categories

Resources