a line of numbers (python) [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm not a programmer, I'm just starting to learn python 2.
I wanted to know how can I write a code in python 2 to get an input that consists a line of numbers seperated by space from the user and do operations with each number sepeately and print the output of each number, again, as a line of numbers seperated by space?

The below example will loop complete the action you were looking for, just replace the "+5" with the operation you want
userInput = raw_input("Enter Numbers:")#Get user input
seperateNumbers = userInput.split(" ")#Seperate data based off of spaces
numbersAfterOperations = []#Create a lsi to hold the values after operation applied
for i in range(0, len(seperateNumbers)): #loop throgh all values
numbersAfterOperations.append(int(seperateNumbers[i]) + 5) #add new value
printedValue = ""
for i in range(0, len(numbersAfterOperations)):
printedValue += str(numbersAfterOperations[i]) + " "
print printedValue

You will start with a string containing all your numbers, so you will have something like this:
line_of_num = "0 1 2 3 4 5 6 7 8 9"
You will have to split the elements of this string. You can do it using the split method of the string class, using a space as separator. It will return a list of the items with your numbers, but you can't operate them as integers yet.
list_of_num = line_of_num.split(" ")
You can't operate them yet because the elements of your list are strings. Before operating them, you have to cast them into integers. You can do it using list comprehentions.
list_of_int = [int(element) for element in list_of_num]
Then you can operate them using common operations through elements of a list. Finally, when you have the results, you can return them as a string separated by spaces using the join method of the string class using a space as separator. The join method has as input an iterable (list, for example) of strings.
results = " ".join(["1", "2", "3", "4", "5"])
Your resulted string will be something like "1 2 3 4 5".

Related

How to convert the output into a single line [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
#python
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
rev=arr[::-1]
for i in range(n):
final=0
final+=rev[i]
print(final)
Given an array of integers, print the elements in reverse order as a single line of space-separated numbers.
You are calling input() many times which is not required, also you can use the join function with " " separator to print all the elements of array in one line. Please note that join expects all elements as str so you will have to map it back to str, so it's better to avoid the map to int at the initial stage as we will have to map it back to str
Here is one of the approach:
n = input("Enter the sequence of numbers: ").strip()
arr = n.split()
print (" ".join(arr[::-1]))
Output:
Enter the sequence of numbers: 1 3 5 7 9
9 7 5 3 1
u may use join method for concat string sequences
but in your case u need to transform integers to string type
in the end code will be like this:
reversed_string = ' '.join(map(str, rev))

Read input and return three strings in reverse order (only 1 string so far) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
def rev(one, two, three):
print("Reverse of the third string is",three[::-1])
# returning concatenation of first two strings
return one+two
def main():
# Taking user input of 3 strings
first = input("Enter first string:")
second = input("Enter second string:")
third = input("Enter third string:")
# calling function, passing three arguments
print("Reverse of third string is",rev(first, second, third))
main()
Assignment
Write a Python function that will accept as input three string values
from a user. The method will return to the user a concatenation of the string values in reverse order. The function is to be called from the main method.
In the main method, prompt the user for the three strings.
If the input of the strings is Hello, World, and Car, then the output should be raCdlroWolleH
Your rev function could contain just one line of code (you should call it in the main function). It is as simple as :
return three[::-1]+two[::-1]+one[::-1]
I think the problem is that you're doing two separated prints, one for the first two words and other to the third word. If what you pretende is to join all of the three words and return that, then all you have to do is
New = one + two + three
return New[::-1]

create list of increasing number of repeated characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to create this kind of output in Python
["k", "kk", "kkk", "kkkk", ...]
["rep", "reprep", "repreprep", ...]
That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element.
I can't find a way to do this easily, without loops..
Thanks,
Here you have a generator using itertools.count, remember the property of "multiplying" strings in python by a number, where they will be replicated and concatenated nth times, where for example "a"*3 == "aaa" :
import itertools
def genSeq(item):
yield from (item*i for i in itertools.count())
Here you have a live example
repeating_value = "k" #Assign the value which do you want to be repeated
total_times=5 #how many times do you want
expected_list=[repeating_value*i for i in range(1,total_times+1)]
print(expected_list)
character = 'k'
_range = 5
output = [k*x for k in character for x in range(1, _range + 1)]
print(output)
I would multiple my character by a specified number in the range, and then I would simply iterate through the range in a list comprehension. We add 1 to the end of the range in order to get the full range.
Here is your output:
['k', 'kk', 'kkk', 'kkkk', 'kkkkk']
The following is by far the easiest which I have built upon the comment by the user3483203 which eliminates initial empty value.
var = 'rep'
list = [var * i for i in range(1,x,1)]
print(list)

python find repeated substring in string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am looking for a function in Python where you give a string as input where a certain word has been repeated several times until a certain length has reached.
The output would then be that word. The repeated word isn't necessary repeated in its whole and it is also possible that it hasn't been repeated at all.
For example:
"pythonpythonp" => "python"
"hellohello" => "hello"
"appleapl" => "apple"
"spoon" => "spoon"
Can someone give me some hints on how to write this kind of function?
You can do it by repeating the substring a certain number of times and testing if it is equal to the original string.
You'll have to try it for every single possible length of string unless you have that saved as a variable
Here's the code:
def repeats(string):
for x in range(1, len(string)):
substring = string[:x]
if substring * (len(string)//len(substring))+(substring[:len(string)%len(substring)]) == string:
print(substring)
return "break"
print(string)
repeats("pythonpytho")
Start by building a prefix array.
Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1.
Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl' example, where the proposed algorithm would return appl . For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl' you return 'appl' +'e' = 'apple' . If no such strings are found, you return the whole word since there are no repetitions.
def repeat(s):
prefix_array=[]
for i in range(len(s)):
prefix_array.append(s[:i])
#see what it holds to give you a better picture
print prefix_array
#stop at 1st element to avoid checking for the ' ' char
for i in prefix_array[:1:-1]:
if s.count(i) > 1 :
#find where the next repetition starts
offset = s[len(i):].find(i)
return s[:len(i)+offset]
break
return s
print repeat(s)

How would I create a Python program that reads a list of numbers, and counts how many of them are positive [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to create a Python program that will count how many positive numbers there are in a list of numbers. The list of numbers has to be typed in by someone. The end result must be the number of elements in the list that were > 0
For an example, this is what you would see on the screen:
>>>Please enter a list of numbers separated by commas: 1,2,-3,-4,5,-6
>>>3
The answer would be 3 in this example. I am sorry if the question seems stupid, but I am a beginner and I am trying my best.
raw_input() for Python 2.x (input() for Python 3) then split() the string at , and then count positive numebers, Example -
s = raw_input("Please enter a list of numbers separated by commas:")
print(len([i for i in s.strip().split(',') if int(i) >= 0]))
You can try like this. input returns tuple
>>> vals = input('get: ')
get: 1,2,-3,-4,5,-6
>>> len([item for item in vals if item > 0])
3
Python 3, input returns string
>>> vals = input('get: ')
get: 1,2,-3,-4,5,-6
>>> len([item for item in vals.split(',') if int(item) > 0])
3
By the way, zero is neither positive nor negative.

Categories