On websites like hackerrank, which I have just recently been introduced to, there are some problems where the input is:
1 5 9
And they want these to be different variables.
Is there a way to read this input with
input()
But then make the three parts of the input different variables?
I have tried:
list_input = input().split(' ')
But this only creates a list of strings.
Is there a better way to create different variables from only one line of input?
Thanks
One way you can do this:
>>> variables = input ("Enter an input separated by space: ")
Enter an input separated by space: 1 5 9
>>> variables
'1 5 9'
>>>
>>> variables = variables.split (' ')
>>> variables
['1', '5', '9']
>>> variables [1]
'5'
>>>
>>> for var in variables:
print (var)
1
5
9
>>>
Related
I am trying to replace a specific character at a specific position in a string.
This need to be accomplished without for loop and use of functions.
Here is an example - need to replace 5th character with x
s = "0123456789012345689"
Output needs to be - "01234x67890x23456x89"
I have tried replace(), split() but may be I am not using them in correct context. The string could be n characters long so I can't hardcode where I get the specific position and break them down in substrings. String are supposed to be immutable in python so are there any other alternatives?
Any help would be appreciated. Thanks.
I guess, if you strictly want to avoid for loops, the easiest way is converting to a list, replacing items, and then converting back.
This would be:
s = "0123456789012345689"
lst = list(s) # result: ['0', '1', '2', ..., '9']
lst[0:-1:5] = ["x"]*len(lst[0:-1:5])
Result then is:
In [43]: lst
Out[43]:
['x',
'1',
'2',
'3',
'4',
'x',
'6',
'7',
'8',
'9',
'x',
'1',
'2',
'3',
'4',
'x',
'6',
'8',
'9']
For getting it back to string you would simply use a join:
In [44]: "".join(lst)
Out[44]: 'x1234x6789x1234x689
The part lst[0:-1:5] select every 5th element in the list, beginning with the very first entry, denonted by 0:. If you want it to start at the 5th element, then simply do lst[5:-1:5]. The -1 part means "until the end", the last :5 stands for "every fifth".
Assigning values with ["x"]*len(lst[0:-1:5]) is needed, since "x" here would try to assign a single value to a slice of the original list with the length len(lst[0:-1:5]), because this is exactly how many items we selected in the first place.
EDIT:
Giving it a second look the expected outcome is actually to change every 6th character, not every 5th (while preserving 5 characters in between the changed ones from the original string).
One would then, of course, need to adjust the slicing to select every 6th character:
lst[5:-1:6] = ["x"]*len(lst[5:-1:6])
^ ^
Result:
In [12]: "".join(lst)
Out[12]: '01234x67890x23456x9'
Every sixth character now is being replaced, while preserving the 5 ones in between from the original string.
My solution to this would be this:
def replace_position(message, replacement, n):
lis = list(message) # get a list of all characters.
lis.pop(n) # delete the chosen character from the list.
lis.insert(n, replacement) # replace it at the given position.
return ''.join(lis)
Example use:
>>> a = 'Hello world, the 6th character is an x!'
>>> replace_postion(a, 'x', 6)
'Hello xorld, the 6th character is an x!'
However, this only gets the first one in that position. In order to do that, this is what I would do:
def replace_position(message, replacement, n):
lis = list(message)
for i in range(n, len(message), n + 1):
lis.pop(i)
lis.insert(i, replacement)
return ''.join(lis)
The only difference is that we are now iterating over the entire message, and replacing each of them as we go. Similar use:
>>> a = 'Hello world, every 6th character is an x!'
>>> replace_position(a, 'x', 6)
'Hello xorld, xvery 6xh charxcter ix an x!'
Hope this helps.
Try
s = "01234567890123456789012345"
pieces = []
for i in range((len(s)-1)//5):
pieces.append(s[i*6:i*6+5])
result = 'x'.join(pieces)
assert(result == '01234x67890x23456x89012x45')
We iterator over every window of six characters in the string, and then collect the first five characters in each window. We then join all of the windows together, using the string x as a separator.
To avoid using loops, you can convert the above into a list comprehension. I'll leave this step for you to complete.
I'm working on an assignment and the problem draws a grid of squares A-J and 1-7. A function exists which randomly generates co-ordinates, e.g.
[['I5'],
['E1', 'F1', 'E2', 'F2'],
['J5', 'J6'],
['G7', 'H7']]
The problem to solve requires a function to read the elements in each list and draw a tile there using Turtle.
How can I separate the letter from the number in each list?
Just for testing, I'm trying to print each co-ordinate (so that I can get a better understanding, the end result actually needs to be goto(x,x) and then call a function I've already defined to draw something):
for instructions in fixed_pattern_16:
print(instructions[0][1])
Which outputs:
5
1
5
7
But because each list is a different length, I get a out of range error when trying to access elements that are in a position that is longer than the the length of the shortest list. E.g.:
print(instructions[2][0])
Try regular expressions and some nested list comprehension:
import re
lists = [['I5'],['E1', 'F1', 'E2', 'F2'],['J5', 'J6'],['G7', 'H7']]
### General format to unpack the list of lists
for i in lists: # Go through each list element
for x in i: # Go through each element of the element
print(x) # Print that element to the console
### Flattening that gives us our list comprehension,
### which we can use to unpack this list of lists
[print(x) for i in lists for x in i]
### We want to find a single alphabetic value and capture a single numeric value
### In short, \w looks for a word (letter) and \d looks for a number
### Check out https://regexr.com/ for more info and an interactive canvas.
letter_number_pat = r'\w(\d)'
### We can use re.sub(<pattern>, <replacement>, <string>) to capture and keep our
### numeric value (\1 since it is the first capture group
### Then, we'll anticipate the need to return a list of values, so we'll go with
### the traditional newline (\n) and split our results afterward
number_list = '\n'.join([re.sub(letter_number_pat, r'\1', x) for i in lists for x in i]).split('\n')
Input: number_list
Output: ['5', '1', '1', '2', '2', '5', '6', '7', '7']
You can get unique values by calling the set() function and wrapping that in list() and sorted() functions from the standard library:
Input: sorted(list(set(number_list)))
Output: ['1', '2', '5', '6', '7']
I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)
You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]
Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].
This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.
There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)
You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!
Why one formatted String literals is able to print without print() but the other not?
>> price = 11.23
>> f"Price in Euro: {price}"
>> for article in ["bread", "butter", "tea"]:
print(f"{article:>10}:")
Interactive sessions print the result of the last top-level statement. A format string is an expression and thus has a result, but a for loop is not and produces no result to display.
>>> 3 # expression
3
>>> a = 3
>>> a # expresion
3
>>> a + 4 # expression
7
>>> if a:
... 9
>>> f"{a}" # expression
3
It's pretty unclear what you want to do with your code, but this should work
for article in ['bread', 'butter']:
print(f"{article}")
Can you please properly format your code and edit your question?
For example,
lst = ['120 abc','123 abc','256 abc','125 bcd','326 bcd','426 bcd']
I want to count how many time 2 is the second digit in each item.
In the lst above:
2 occurs 2 times for items ending in abc
2 occurs 3 times for itmes ending in bcd
My question is related to an assignment on Benford's law. The text file given is structured similar to the lst above. The numbers represent ballots count and the letters represent name of cities.
My program reads the file and put each ballots count and the corresponding city as an item in a list.
Since each item in the list is a string, i know to to index through each item for the desired digit, and count the number of occurrences. But i don't know how to separate each item into similar group of items.
I'm an absolute beginner to programming. I'm not looking for actual codes but ideas on how to approach the problem.
Indexing helps you to rapidly retrieve an element of a sequence. First item has always the zero index. Both list and string are sequences, so:
>>> lst[2]
'256 abc'
>>> lst[2][1]
'5'
With the knowledge of indexing you can easily get all the second characters of a list in a new list with a generator expression:
>>> [x[1] for x in lst]
['2', '2', '5', '2', '2', '2']
Now you only have to count the twos there:
>>> [x[1] for x in lst].count('2')
5
If you only want those which ends witha a specific string, use this genexp:
>>> [x[1] for x in lst if x.endswith('abc')]
['2', '2', '5']
What you want to do is to just itterate the list and when you find an index that matches more then once just add to it's place in the list. This snippet should give you the idea of how it is done.
lst = ['120 abc','123 abc','256 abc','125 bcd','326 bcd','426 bcd']
list2 = {}
for listItem in lst:
if listItem.index('2') == 1:
t = listItem.split()
if t[1] in list2:
list2[t[1]] = list2[t[1]] + 1
else:
list2[t[1]] = 1
print(list2)
listItem.split() is a standard function that divides the string on a whitespace, after that we can use "abc" as a key and place the value in a dictionary and sum up the number of times that any particular string occured.