Create a function based on the input and output. Look at the examples, there is a pattern.
My code:
def secret(a):
b=a[:-2]
a_list=list(a)
last_number=int(a_list[-1])
Final_recurr=last_number+last_number
d="{} ".format(b)*Final_recurr
j=d.split()
for i,k in enumerate(j):
if int(i)%2!=0:
m="{}".format("</" + b+ ">")*Final_recurr
return m
if int(i)%2==0:
m="{}".format("<" + b+ ">")*Final_recurr
return m
I am not able to put / in every second iteration. Please tell me the mistake in current code and short version of this.
You can use str.split or str.partition to split the string into separate parts:
>>> "div*2".partition("*")
('div', '*', '2')
>>> tag_name, _, mult = "div*2".partition("*")
>>> tag_name
'div'
>>> mult
'2'
Use string formatting to insert tag_name into a template:
>>> "<{}></{}>".format(tag_name, tag_name)
'<div></div>'
"multiply" the formatted string with int(mult):
>>> "<{}></{}>".format(tag_name, tag_name) * int(mult)
'<div></div><div></div>'
>>>
You probably should familiarize more with programming basics before trying to solve challenges.
In this case, you have to understand that a return statement inside a function just exits the function even if it is in a loop.
Thus, at the first iteration of your for i, k in enumerate(j): loop, the code passes in the second condition and exits the function when it reaches the return statement.
So there is never a second loop and your loop is just inoperant.
Just fixing this problem won't be sufficient to get a working solution. I would advice to clarify in your head the steps needed to achieve what your want and even write them in the form of comments in an empty function (you could take steps suggested by #Qwerty in comment):
def secret(expression):
# split the argument into the bits before and after *
# combine the required string
# return the resulting string
Then try to address each comment, one at a time. Other responses should help you a lot in doing this.
Here are some links to the documentation of functions and concepts that could help you:
str.split
str.format
unpacking
This is the function that can help you, try it out:
s = 'div*2'
>>> def secret(s):
tag, n = s.split('*') # parse it into two parts
ans = f'<{tag}></{tag}>' # get complementary part
return ans * int(n) # final result
>>> secret(s)
'<div></div><div></div>'
>>> secret('p*1')
'<p></p>'
>>>
Related
def Change(_text):
L = len(_text)
_i = 2
_text[_i] = "*"
_i += 2
print(_text)
How can I add a mark e.g:* every two Index In String
Why are you using _ in your variables? If it is for any of these reasons then you are OK, if it is a made up syntax, try not to use it as it might cause unnecessary confusion.
As for your code, try:
def change_text(text):
for i in range(len(text)):
if i % 2 == 0: # check if i = even (not odd)
print(text[:i] + "*" + text[i+1:])
When you run change_text("tryout string") the output will look like:
*ryout string
tr*out string
tryo*t string
tryout*string
tryout s*ring
tryout str*ng
tryout strin*
If you meant something else, name a example input and wished for output.
See How to create a Minimal, Complete, and Verifiable example
PS: Please realize that strings are immutable in Python, so you cannot actually change a string, only create new ones from it.. if you want to actually change it you might be better of saving it as a list for example. Like they have done here.
Are you trying to separate every two letters with an asterix?
testtesttest
te*st*te*st*te*st
You could do this using itertools.zip_longest to split the string up, and '*'.join to rebuild it with the markers inserted
from itertools import zip_longest
def add_marker(s):
return '*'.join([''.join(x) for x in zip_longest(*[iter(s)]*2, fillvalue='')])
If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332
I am trying to parse a JSON page in Python, it is contained in a variable reddit_front.
I am trying to get the sum of all "ups" in this page. I do have the right answer which is the following:
def total_ups():
j=json.loads(reddit_front)
return sum(c["data"]["ups"] for c in j["data"]["children"])
However why does the following loop give me only 1 item and not iterate over?
def total_ups():
j=json.loads(reddit_front)
for c in j["data"]["children"]:
i = c["data"]["ups"]
a = +i
return a
PS: ok, all good points and thx for the negative reputations points, it's fair call I wasn't precise in my question.
return will stop the loop, try appending it to a list then you can join it or whatever you need to so you can get the data.
Example:
def total_ups():
a = list()
j=json.loads(reddit_front)
for c in j["data"]["children"]:
i = c["data"]["ups"]
a.append(+i)
return a
print(total_ups()) # returns list
print(", ".join(total_ups)) # returns a string separated by commas
Maybe...
def total_ups():
children = json.loads(reddit_front)["data"]["children"]
return sum(c["data"]["ups"] for c in children)
Can anyone help me with the assignment - I have to reverse a string by using def. I am not allowed to use approaches like [::-1] or .reversed...
The following function works, but prints vertically:
def ex1(name):
for x in range(len(name)-1,-1,-1):
print(name[x])
k
r
o
Y
w
e
N
how do I put the letters back into horizontal order?? Anyone? Thanks!
You can use str.join and a list comprehension like so:
>>> def ex1(name):
... return "".join([name[x] for x in range(len(name)-1,-1,-1)])
...
>>> print(ex1('abcd'))
dcba
>>>
Also, notice that I made the function return the string instead of print it. If your teachers want you to use def for this job, then they probably want that too. If not, then you can always replace return with print if you want.
You were very close:
def ex1(name):
reverseName=""
for x in range(len(name)-1,-1,-1):
reverseName+=name[x]
print reverseName
The print statement prints a newline character (a line break) after each line, this is why you get your characters in vertical. The solution is not to print the character in each loop, but to collect them in a string and print the final string at once at the end.
Note that there are more efficient ways of doing this (see the other answers), but it might be the most straightforward way and the closest one to what you have already done.
Here is another way that you can reverse a string.
def ex1(name):
length = len(name)
return "".join([name[length-x-1] for x in range(0, length)])
print ex1("hello world")
name=input("Whats your name ?")
def reversemyname(name):
x=name[::-1]
return x
reversedname=reversemyname(name)
print(reversedname)
print(name[x]), # <= add that comma
if you want the output like this kroy wen then try this:
sys.stdout.write(name[x])
remember to import sys
I write my code that way, I want to assign matched values to 'm'
but lst[1] may not including the pat I want.
if it does, so I'll keep do something about 'm'
eg: m.group(2).split() ....
if re.match(pat, lst[1]):
m=re.match(pat, lst[1])
But I don't want to repeat the re.match(pat, lst[1]) twice.
I want to achieve in that way
if m = re.match(pat, lst[i])
but it shows me "invalid syntax error.
any ideas?
Just assign the value beforehand and check if it's None:
m = re.match(pat,lst[1])
if not m:
del m
You can abuse for for your task.
def for_if(expression):
if expression:
yield expression
for m in for_if(re.match(pat, lst[1])):
# work with m
or just
for m in (i for i in (re.match(pat, lst[1]),) if i):
# do the same
This is not really helpful for readability, but is the only way to combine assignment and test.