Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
For example, if the string is pyeneapple then the answer should be p since p is the first element that is present again in the string (and not e).
Can someone help with the Python code for this?
Here is my attempt:
thestring = "pyeneapple"
list_a = []
list_b = []
for i in thestring:
if i in list_a:
list_b.append(i)
else:
list_a.append(i)
print(list_b[0])
The problem is that this code prints e as the answer instead of p.
You can replace comparing characters from string and then compare it to the string.
s = "pyeneapple"
a = []
for i in s:
if i in s.replace(i, "", 1):
a.append(i)
print(a[0])
Output: p
Use a character counter to make it easier to implement and improve readability.
from collections import Counter
counts = Counter(s)
for i in s:
if counts[i]>1:
print(i)
break
You can use the built-in function enumerate():
for i, c in enumerate(thestring):
if thestring[:i+1].count(c) > 1:
print(c)
break
As there is a split point of view in the comment, I'm writing about the code giving the first element that repeats itself again in the behind strings.
thestring = "supercalifragi"
for i in range(len(thestring)):
if thestring[i] in thestring[i+1:]:
element = thestring[i]
break
element
Out[10]: 'r'
i would try with the buid-in count function for the list-type like this :
t = "pyeneapple"
for i in list(t):
if t.count(i)>0:
print(i)
break
>>> p
You could find the first location using re.search where the string matches 2 of the same characters using a capture group and a backreference
import re
m = re.search(r"(.)\1", "pyeneapple")
if m:
print(m.group(1))
Output
p
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want find the first unique number in a list, but I have a error.
My code:
s=[1,2,1,2,3,5]
mydict={}
for i in s:
if(i in mydict):
mydict[i]=mydict[i]+1
else:
mydict=1
for key in mydict:
if (mydict[key]==1):
print(key)
Error:
Traceback (most recent call last):
File "C:/Users/abdul_saboor/PycharmProjects/sleneiumpythonsession/Selenium sessions/firstuniquenumber.py", line 4, in <module>
if(i in mydict):
TypeError: argument of type 'int' is not iterable
You missed the [i] at line 7.
This is what propably what throws the error.
You could also make this faster with numpy.
mydict = {num: count for num, count in zip(np.unique(s))}
This is exactly what you want to do.
Then to find the first unique number you can do:
for num in s:
if mydict[num] == 1:
break
num is afterwards the first occuring unique number.
You can find the answer for your problem by looking for counting occurrences in lists.
Anyway, here are a couple ways for you to get it:
1 (using a For Loop)
# Stops at the first unique number
s = [1,2,1,2,3,5]
for n in s:
r = s.count(n)
if r == 1:
print(f'{n} is unique')
break
2 (using Comprehension List)
# Without stopping at the first unique
s = [1,2,1,2,3,5]
[ print(f'{n} is unique') for n in s if s.count(n) == 1 ]
3 (using Comprehension List)
# Stopping at the first unique number and exit the program
import sys
s = [1,2,1,2,3,5]
[ [ print(f'{n} is unique'), sys.exit() ] for n in s if s.count(n) == 1 ]
4 (the most elegant way)
# This doesn't stop the loop and doesn't exit the program
print(f'{[ n for n in s if s.count(n) == 1 ][0]} is unique')
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am having a problem with the output my code is giving me and I am stumped. The output should look like this:
1,2,3,4 = 10
But instead, I am getting this:
[1,2,3,4] = 10
Can anyone review my code and tell me why its outputting that?
Here it is:
def sumList(NumList):
NumList = [int(input('Enter the number: ')) for i in range(4)]
print(NumList, "=" ,sum(NumList))
sumList(4)
NumList is a list object, which is denoted by the squared brackets, that's why when you print it shows [1,2,3,4].
If you want to print it like 1,2,3,4 = 10 you will need to treat it first with something like
NewList = [str(i) for i in NumList]
NewList = ','.join(NewList)
then your final function should be
def sumList(NumList):
NumList = [int(input('Enter the number: ')) for i in range(4)]
NewList = [str(i) for i in NumList]
NewList = ','.join(NewList)
print(NewList, "=" ,sum(NumList))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to build a function that will return the sum of the first item in the data list and every tenth item after, so I write the script below, however, the result is always the first data in my list. How should I modify my code and fix it?
def Sum10th(data):
sum=0
for i,d in enumerate(data):
if (i % 10 == 0): sum = sum+d
return sum
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(Sum10th(p))
The desired result should be 31, however the computer only returns the value of 1.
You can try
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def Sum10th(data):
return sum([v for i, v in enumerate(p) if (i + 1) % 10 == 0 or i == 0])
print(Sum10th(p))
Output
31
By using the list comprehension with an if, at the end of it, you can get all the first item with the tenth item following it from a list.
Try this way:
def sum10thdata(data):
sum = 0
l = len(data)
for i in range(0,l,10):
sum+=data[i]
return sum
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!
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 1 year ago.
Improve this question
there are two strings:
str1 = "black_red_yellow"
str2 = "blue_red_green"
which python library can I use to check these two strings have a substring"_red_" in common? thank you in advance.
Something like this should work if you don't know the actual string you're searching for
import difflib
str1 = "black_red_yellow"
str2 = "blue_red_green"
difference = difflib.SequenceMatcher()
difference.set_seqs(str1, str2)
for match in difference.get_matching_blocks():
print str1[match[0]:match[0] + match[2]]
test for presence of common substring, including length 1:
if set(str1).intersection(set(str2)): print "yes we can!"
if you can't find anything else, then there's at least this naive implementation:
str1 = "black_red_yellow"
str2 = "blue_red_green"
if len(str1) < len(str2):
min_str = str1
max_str = str2
else:
min_str = str2
max_str = str1
matches = []
min_len = len(min_str)
for b in xrange(min_len):
for e in xrange(min_len, b, -1):
chunk = min_str[b:e]
if chunk in max_str:
matches.append(chunk)
print max(matches, key=len)
prints _red_
You can use difflib to compare strings in that way. However, if you know the string you're looking for you could just do '_red_' in str1 and '_red_' in str2. If you don't know the string, then do you look for a specific length of match? E.g. would 'red' match 'blue' because they both contain 'e'? The shortest, simplest way of checking for any match at all would be
bool([a for a in str1 if a in str2])
Edit: Or, more efficiently,
any(a for a in str1 if a in str2)