This Code Works Fine.....But it's like static.
I don't know what to do to make it work in dynamic way?
I want:-
When user inputs 3 number of cities it should give
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city
2 and "+li[2]+" as city 3 on your trip"
Similaraly when input is 5 cities it should go to 5 times
li = []
global a
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
li.append(raw_input("Enter City Name -->"))
print li
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city 2 and "+li[2]+" as city 3 on your trip"
print a
a = a.split(" ")
print "\nSplitted First Sentence looks like"
print a
print "\nJoined First Sentence and added 1"
index = 0
for word in a:
if word.isdigit():
a[index] = str(int(word)+1)
index += 1
print " ".join(a)
You should do something like this
a = 'You would like to visit ' + ' and '.join('{0} as city {1}'.format(city, index) for index, city in enumerate(li, 1)) + ' on your trip'
You can build the string with a combination of string formatting, str.join and enumerate:
a = "You would like to visit {} on your trip".format(
" and ".join("{} as city {}".format(city, i)
for i, city in enumerate(li, 1)))
str.join() is given a generator expression as the iterable argument. The curly braces ({}) in the strings are replacement fields (placeholders), which will be replaced by positional arguments when formatting. For example
'{} {}'.format('a', 'b')
will produce the string "a b", as will
# explicit positional argument specifiers
'{0} {1}'.format('a', 'b')
create another for loop and save your cities to an array. afterwords, concat the array using "join" and put put everything inside the string:
cities = []
for i in range(0,len(li), 1):
cities.append("%s as city %i" % (li[i], i))
cities_str = " and ".join(cities)
a = "You would like to visit %s on your trip" % (cities_str) # edited out the + sign
Related
I get a quiz about programming python.
Input: 3 lines of any string. (only 3 lines)
Output: 3 * 5 = 15 lines of string which repeat 3 lines of input 5 rounds
** But this quiz has restricted word: import for while * . sep if else elif list set tuple dict [] {} lambda map filter
I already try it by use asterisk character to repeat string but this is restricted word. It cannot submit.
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C + "\n"
print(STRING_RESULT * 5)
Example
Input:
man
in
middle
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle
Thanks for your helping.
Given your restrictions, recursion sounds like a good approach. Give this a shot!
def repeater(a,n):
n <= 0 and exit(0)
n == 1 and print(a)
print(a)
return(repeater(a,n-1))
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C
repeater(STRING_RESULT, 5)
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle
I created a Python function that takes an argument, fullname, gets fullname's initials and prints them out capitalized. But there's a problem with my code - it only works with two names. It breaks if the fullname has a middle name, i.e. Daniel Day Lewis.
Here is what I tried:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Obviously this attempt only includes two variables, one for the first name and one for the second name. If I add a third variable, like this:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
I get:
IndexError: list index out of range on line 10
(which is the line)
third = name_list[2][0]
Of course this function does work if I change fullname to "Ozzie Smith Jr". But my function has to work regardless of whether there are 1, 2, 3, or 4 names in fullname. I need to say something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
How do I say "if fullname has a second name or third name or fourth name, return the uppercase initial" in Python? Or am I on the right track? Thank you.
You can make use of a list comprehension:
s = ''.join([x[0].upper() for x in fullname.split(' ')])
edit: should probably explain a little more
list comprehensions allow you to build a list as you iterate.
So first we build a list by splitting fullname with a space fullname.split(' '). As we get those values, we take the fist letter x[0] and uppercase it .upper(). Finally we join the list into one with no spaces ''.join(...).
This is a nice one liner that's really fast and will pop up in various forms as you continue working with python.
How about something like:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
return initials
This is my answer:
Splitting the string into a list
Iterate through elements using range and i
Taking index 0 for each element during iteration (Hence words[i][0])
words[i][0].upper for the upper case requirement for the question
def initials(phrase):
words = phrase.split()
result = ""
for i in range(len(words)):
result += words[i][0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
This should work
map(str.upper, zip(*the_persons_name.split())[0])
the other variance of one liner as below, we can join all the initials 1st then do the upper 1 shot at last
''.join(i[0] for i in a.split()).upper()
def initials(name):
words = name.split()
result = ""
for word in words:
result += word[0].upper()
return result
i have created a set of code which can convert the sentence into a list of positions.
sentence = "ask not what you can do for your country ask what your country can do for you"
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
print(values)
i now need for the program to be able to convert multiple sentences
so it would be
sentence = ("ask not what you can do for your country ask what your country can do for you")
sentence2 = ("some people enjoy computing others do not enjoy computing")
sentence3 = ("i will use this as my last sentence as i do not need another sentence")
i need the code to be able to create seperate lists for each of the sentences, without the code being too heavily modified
I think what you are looking for is a function:
def get_positions(sentence):
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
return values
print get_positions(sentence1)
print get_positions(sentence2)
print get_positions(sentence3)
What this does is create a function that takes a sentences as an argument and then converts that into the list you wanted to construct. Any time you want to get the positions for a sentence you can just call your function with the sentence you want to get the positions for as the argument.
Note that I changed the print at the end of your code to a return value. the return statement is what comes back out of the function when you use it. Basically, you pass in some value, do some computation and then spit out another value.
How can I join a data below,
# Convert Spark DataFrame to Pandas
pandas_df = df.toPandas()
print pandas_df
age name
0 NaN Michael
1 30 Andy
2 19 Justin
My current attempt,
persons = ""
for index, row in pandas_df.iterrows():
persons += str(row['name']) + ", " + str(row['age']) + "/ "
print row['name'], row['age']
print persons
Result,
Michael, nan/ Andy, 30.0/ Justin, 19.0/
But I am after (no slash at the end),
Michael, nan/ Andy, 30.0/ Justin, 19.0
If you want to keep your method of looping through each , then you can simply remove the last / by doing rstrip() on it to strip from the right side. Example -
persons = ""
for index, row in pandas_df.iterrows():
persons += str(row['name']) + ", " + str(row['age']) + "/ "
print row['name'], row['age']
person = person.rstrip("/ ")
print persons
Example/Demo -
>>> person = "Michael, nan/ Andy, 30.0/ Justin, 19.0/ "
>>> person = person.rstrip('/ ')
>>> person
'Michael, nan/ Andy, 30.0/ Justin, 19.0'
But if you really do not want the print row['name'], row['age'] inside the loop, then you can convert this into a generator function and let str.join() handle what you want. Example -
person = "/".join(",".join([str(row['name']), str(row['age'])]) for _, row in pandas_df.iterrows())
I think this will do
persons = []
str_pearsons=""
for index, row in pandas_df.iterrows():
persons.append( str(row['name']) + ", " + str(row['age']))
str_pearsons="/ ".join(persons)
You can achieve this easily in a one liner that will be vectorised:
In [10]:
'/ '.join(df['name'] + ', ' + df['age'].astype(str))
Out[10]:
'Michael, nan/ Andy, 30.0/ Justin, 19.0'
I am writing code for a game that takes input from a user and replaces that string input with a slice of code from the original string (old_story) I keep getting this TypeError returned. I want to make it so that my code replaces the replace_this string with the corresponding iteration number in the new_word_list (values were assigned to that list earlier on in the code). Is there any way I can go around this problem? There are multiple replace_this strings, and the same amount of items in the new_word_list. How do I get it so that it runs smoothly? Any advice will be highly appreciated, as the documentation is confusing. I understand this is a very simple problem but I would appreciate any help I can get. This is the error that keeps on returning in IDLE: TypeError: Can't convert 'list' object to str implicitly
import random
old_story = random.choice(open('madlibs.txt').readlines())
new_word_list = [""] #new list where user input will be added to.
end = 0
repetitions = old_story.count('{')
for i in range(repetitions):
start = old_story.find('{', end) + 1
end = old_story.find('}', start)
replace_this = old_story[start:end]
replace_this = input("Please enter a " + replace_this + ":")
new_word_list.append(str(replace))
new_story = old_story
for i, replace_this in enumerate(old_story):
if i > len(new_word_list) - 1:
break
new_story = old_story.replace(replace_this, new_word_list[i])
new_story = new_story.strip()
print(new_story)
You cannot pass the list itself, you need to access the item in the list by index:
s = "foo foobar foo"
l = ["hello world "]
print s.replace("foobar",l[0])
foo hello world foo
l = ["hello world ","different string"]
print s.replace("foobar",l[-1])
foo different string foo
old_story = "This is a {word}."
new_word_list = ["one","two","three","four"]
spl = old_story.split() # split into individual words
for ind, new_s in enumerate(new_word_list):
spl[ind] = new_s # replace element at matching index
print (" ".join(spl)) # rejoin string from updated list
one two three four
old_story = "This {foo} is {a} {foo} {bar}."
new_word_list = ["is","my","final","solution"]
spl = old_story.split()
for ind, word in enumerate(spl):
if word.startswith("{"):
spl[ind] = new_word_list.pop(0)
print (" ".join(spl))
This is is my final solution
If you variables you can use them with str.format:
old_story = " Hello! I {verb} a {noun} today!"
new_word_list = ["is","my","final","solution"]
verb, noun = ["ate","hotdog"]
print( old_story.format(verb=verb,noun=noun))
Hello! I ate a hotdog today!