Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to change 'a,b,c,d,e,f,g,e' to 'a,b#c,d#e,f#g,e'.
Input:
'a,b,c,d,e,f,g,e'
Output:
'a,b#c,d#e,f#g,e'
Is it possible?
For the regex lovers:
import re
input = 'a,b,c,d,e,f,g,e'
output = re.sub(r',([^,]*),', r',\1#', input)
You can try this, though its a little complex:
a = 'a,b,c,d,e,f,g,e'
l = a.split(',')
res=''.join([i+',' if num%2==0 else i+'#' for num,i in enumerate(l)]).strip('#').strip(',')
Yes it is possible, here is another method that just involves creating a new string and changing what gets added depending on the condition.
def func(s):
res = ''
i = 0
for c in s:
if c == ',':
i += 1
res += '#' if c == ',' and i % 2 == 0 else c
return res
>>> a = 'a,b,c,d,e,f,g,e'
>>> func(a)
'a,b#c,d#e,f#g,e'
try this-
>>> a = 'a,b,c,d,e,f,g,e'
>>> z=','.join([val if (idx)%2!=0 else '#'+val for idx,val in enumerate(a.split(','))]).replace('#','',1).replace(',#','#')
>>> print z
>>> a,b#c,d#e,f#g,e
You can use stepped slicing, zip, and str.join to achieve this pretty readily.
a = 'a,b,c,d,e,f,g,e'
pairs = zip(a.split(',')[::2], a.split(',')[1::2])
print '#'.join(','.join(p) for p in pairs)
# a,b#c,d#e,f#g,e
This assumes that there are an odd number of commas and the "pairs" are meant to be demarcated by # (as noted in the comment).
a = 'a,b,c,d,e,f,g,e'
b = a.split(',')
it = iter(b[ 1: -1])
result = []
while True:
try:
result.append("{0}#{1}".format(next(it), next(it)))
except StopIteration:
break
print(",".join([b[0]] + result + [b[-1]]))
Output:
a,b#c,d#e,f#g,e
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Let's say I have s1={'bread'} and I have a l1 = [{'milk', 'yogurt', 'eggs'}, {'bread', 'milk'}]. Since 'bread' is in the second set I want it to return True. If I put it in a for-loop, it will check if s1 is in the first element, then it will check if s1 is in the second element. How can I do it like simultaneously? Something like:
s1.issubset(l1[0]) or s1.issubset(l1[1]) or .... s1.issubset(l[n])
so that the result will be True
You could use any:
s1 = {'bread'}
l1 = [{'milk', 'yogurt', 'eggs'}, {'bread', 'milk'}]
print(any(s1.issubset(e) for e in l1))
Output
True
If I understand your question correctly another option is to convert l1 into one large set. You can do this with itertools.chain
from itertools import chain
s1 = {'bread'}
s2 = {'toast'}
l1 = [{'milk', 'yogurt', 'eggs'}, {'bread', 'milk'}]
print(s1 <= set(chain(*l1)))
print(s2 <= set(chain(*l1)))
will print
True
False
You can use for loop to check every element and use or
s1 = {'bread'}
l1 = [{'milk', 'yogurt', 'eggs'}, {'bread', 'milk'}]
result = False
for item in l1:
result = result or s1.issubset(item)
print(result)
or you use if to check if it is true and exit loop using break
s1 = {'bread'}
l1 = [{'milk', 'yogurt', 'eggs'}, {'bread', 'milk'}]
result = False
for item in l1:
if s1.issubset(item):
result = True
break # exit loop because there is no need to check rest items
print(result)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
my_str = 'I am want you'
l = ['my_str']
for value in l:
print value
I would like to fetch the value stored in my_str.
Expected output
I am want you
You can use eval.Otherwise use dictionary is good approach
my_string = 'I am want you'
l = ['my_string']
for value in l:
print eval(value)
#output
I am want you
"eval" seems a better solution, but "exec" is also feasible.
>>> my_string = 'hello world'
>>> l = ['my_string']
>>> for each in l:
... exec 'print ' + each
... exec 'a = ' + each
... print 'a = %s' % a
...
hello world
a = hello world
I also agree that it is an bad idea to use eval/exec for this purpose. Using dictionary might be a better way.
I am not 100% sure what your intention is. But if you want to get integer values from a string in python there are some solutions.
>>> import re
>>> string1 = "498results should get"
>>> map(int, re.findall(r'\d+', string1))
[498]
Solution from jamylak
This groups all numbers with the help of a regular expression and then maps them, thus inserting them into an array.
You then just could iterate over this array
>>> arr = map(int, re.findall(r'\d+', string1))
>>> for num in arr:
>>> print num
498
Edit: Yeah, seems like I misunderstood your question
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
>>> M = 91
>>> G = 2.5
>>> R = 0.14
>>> J = -0.033
>>> S = [1,2]
>>> def sigs(com):
for i in com:
return ((4*3.14)/3)*((1/i) + ((i*R + J*i-M**2))/((i-M**2)**2))
>>> print(sigs(S))
4.18616097606284
You have returned a value for first element , instead you can use a list so store the result , and then return that list :
def sigs(com):
l=[]
for i in com:
l.append(((4*3.14)/3)*((1/i) + ((i*R + J*i-M**2))/((i-M**2)**2)))
return l
or you can use yield to return a generator :
def sigs(com):
for i in com:
yield ((4*3.14)/3)*((1/i) + ((i*R + J*i-M**2))/((i-M**2)**2))
print list(sigs(S))
Use yield smth. Than your function becomes an iterator.
You can use it like this
def func(smth):
for I in smth:
yield I
for n in func([1,2,3,4]):
print n
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?
There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.
The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length
You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's say I have an IBAN: NL20INGB0001234567
How can I change all digits except the last 4 into *:
Input: NL20INGB0001234567
Output: NL20INGB******4567
all digits but NL*20*
Using regex:
>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'
Simplest?
import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)
Result:
'NL20INGB****4567'
tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
if i.isdigit():
tmp += '*'
else:
tmp += i
iban = iban[:4] + tmp + iban[-4:]
>>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'
s = "IBAN: NL20INGB0001234567"
s = [ele for ele in s.split(':')[-1] if ele.strip()]
mask = [1 for ele in range(len(s) - 10)] + [0] * 6 + [1] * 4
print ''.join(["*" if mask[i] == 0 else ele for i, ele in enumerate(s)])
Output:
NL20INGB******4567
Based on the way you worded the question, I'm assuming you want to format an IBAN string from
##################
to
########******####
Based on this, a simple solution is to write this function:
def ConverterFunction(IBAN):
return IBAN[:8]+"******"+IBAN[14:]
and call it with this line:
ConverterFunction(<your IBAN here>)
Of course, attaching assignments or prints where necessary.
EDIT: A bit of an explanation might be necessary, too.
Whatever you are using as IBAN is a string, and strings can be sliced. By slicing, a person can pick up parts of a string and leave others behind. It uses the index of each letter's position, like so:
This is OK
0123456789
Note, the index always starts at 0, not 1.
Example of taking string slices:
examplestring = "EXAMPLE!"
print examplestring[:3] # "[:3]" means "from beginning to position 3"
print examplestring[5:] # "[5:]" means "from position 5 to end of string"
print examplestring[3:5] # "[3:5]" means "from position 3 to position 5"
Output:
>> EXAM
>> LE!
>> MPL
So in my solution, what the function ConverterFunction(IBAN) does is:
#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle
Understand?
Happy coding!