Adding an x in front of and after words in a list - python-3.x

It's basic as far as Python goes, but I need to create a function List of words as an input parameter and outputs them as a single String formatted as a sentence with a period at the end and lower case 'x's around each word.
e.g.
Input: ["This", "is", "a", "sentence"]
Returns: "xThisx xisx xax xsentencex.
I think I need a for loop, but I keep getting errors in trying them.
Thanks in advance!
The closest I've come is through:
quote = ["This","is","a","sentence"]
def problem3(quote):
blue='x x '.join(quote)
return(blue)
which returns "Thisx x isx x ax x sentence"

quote = ["This","is","a","sentence"]
s = ""
for word in quote:
s = s + "x" + word + "x "
s = s[:-1]
print(s)
Out[17]: 'xThisx xisx xax xsentencex'

list_ = ["This", "is", "a", "sentence"]
string =''
for item in list_:
string += ' x' +item+'x'
string = string.strip()
print(string)

Map the initial list
>>> list_ = ["This", "is", "a", "sentence"]
>>> newlist = list(map(lambda word: f"x{word}x", list_))
>>> print(newlist)
['xThisx', 'xisx', 'xax', 'xsentencex']
And then reduce it to get the complete sentence
>>> import functools
>>> result = functools.reduce(lambda a,b : f"{a} {b}", newlist2)
>>> print(result)
xThisx xisx xax xsentencex

Related

What does int(n) for n mean?

In order to put the input into a list:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Can someone explain what does 'int(n) for n in' mean?
How do I improve this question?
The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Given your code:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Lets say you run the code provided, you get a prompt for input:
Enter numbers: 10 8 25 33
Now what happens is, Python's input() function returns a string, as documented here:
https://docs.python.org/3/library/functions.html#input
So the code has now essentially become this:
numbersList = [int(n) for n in "10 8 25 33".split()]
Now the split() function returns an array of elements from a string delimited by a given character, as strings.
https://www.pythonforbeginners.com/dictionary/python-split
So now your code becomes:
numbersList = [int(n) for n in ["10", "8", "25", "33"]]
This code is now the equivalent of:
numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
numberList.append(int(n))
The int(n) method converts the argument n from a string to an int and returns the int.
https://docs.python.org/3/library/functions.html#int
For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']
int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.
let us try to understand this list comprehension expression though a simple piece of code which means the same thing.
nums = input('Enter numbers: ') # suppose 5 1 3 6
nums = nums.split() # it turns it to ['5', '1', '3', '6']
numbersList = [] # this is list in which the expression is written
for n in nums: # this will iterate in the nums.
number = int(n) # number will be converted from '5' to 5
numbersList.append(number) # add it to the list
print(numbersList) # [5, 1, 3, 6]

How to split a string using any word from a list of word

How to split a string using any word from a list of word
I have a list of string
l = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']
I need to split for example 'XCVI' based on this list like
'XC-V-I'
Here's one solution but I'm not sure if it's the best way to do that:
def split(s, l):
tokens = []
i = 0
while i < len(s):
if s[i:i+2] in l:
tokens.append(s[i:i+2])
i += 2
else:
tokens.append(s[i])
i += 1
return '-'.join(tokens)
where s is the input string such as "XCVI".
Result:
l = ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']
>>> split('XCVI', l)
XC-V-I
>>> split('IXC', l)
IX-C
>>> split('IXXC', l)
IX-XC

Reordering character triplets in Python

I've been trying to solve this homework problem for days, but can't seem to fix it. I started my study halfway through the first semester, so I can't ask the teacher yet and I hope you guys can help me. It's not for grades, I just want to know how.
I need to write a program that reads a string and converts the triplets abc into bca. Per group of three you need to do this. For examplekatzonbecomesatkonz`.
The closest I've gotten is this:
string=(input("Give a string: "))
for i in range(0, len(string)-2):
a = string[i]
b = string[i + 1]
c = string[i + 2]
new_string= b, c, a
i+=3
print(new_string)
The output is:
('a', 't', 'k')
('t', 'z', 'a')
('z', 'o', 't')
('o', 'n', 'z')
The code below converts for example "abc" to "bca". It works for any string containing triplets. Now, if input is "abcd", it is converted to "bcad". If you input "katzon", it is converted to "atkonz". This is what I understood from your question.
stringX = input()
# create list of words in the string
listX = stringX.split(" ")
listY = []
# create list of triplets and non-triplets
for word in listX:
listY += [[word[i:i+3] for i in range(0, len(word), 3)]]
# convert triplets, for example: "abc" -> "bca"
for listZ in listY:
for item in listZ:
if len(item)==3:
listZ[listZ.index(item)] = listZ[listZ.index(item)][1:] + listZ[listZ.index(item)][0]
listY[listY.index(listZ)] = "".join(listZ)
# create final string
stringY = " ".join(listY)
print(stringY)

How to create a dictionary with values representing the amount of times a word is repeated in a list?

x = ["hi", "hi", "bye", "see", "you", "later"]
for i in x:
sum = x.count(i)
y = dict((i, sum) for i in x)
print(y)
When I print this code it gives me a dictionary with key values of 1. However, what I am trying to achieve is for the values in the dictionary to be the number of times each word in the list is repeated. So, for this example: {'hi':2, 'bye':1, 'see':1, 'you':1, 'later':1} is what I am trying to achieve for my output given the input x. Can anyone help me? Thanks :)
you can have something like this
x = ["hi", "hi", "bye", "see", "you", "later"]
y = {i:x.count(i) for i in x}
print(y)
and the results will be
{'bye': 1, 'hi': 2, 'later': 1, 'see': 1, 'you': 1}
defaultdict is suitable for this kind of task.
from collections import defaultdict
x = ["hi", "hi", "bye", "see", "you", "later"]
y = defaultdict(int)
for key in x:
y[key] += 1
print(y)
print(dict(y))
Add Counter ver. as in comments (much easier than defaultdict).
from collections import Counter
x = ["hi", "hi", "bye", "see", "you", "later"]
y = Counter(x)
print(y)
Add without importing modules.
x = ["hi", "hi", "bye", "see", "you", "later"]
y = dict()
for key in x:
if not key in y:
# y.update({key: 1})
y[key] = 1
else:
y[key] += 1
print(y)

How to insert a String as Integer to a List in Python

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]
Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.
Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful
You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Resources