How the loop should iterate. I'm a beginner trying to create a Python program to print a word backwards based on old knowledge from a few years ago. It does a few other things but they are just printed statements are don't pose a problem. Here is my code:
count = 0
while count < 100:
word_var = input("Enter ONE word with NO spaces:")
def split(word_var):
return list(word_var)
word_array = split(word_var)
m = 0
i = len(word_array)-1-m
print("The number of letters in your word is:", i)
while m < len(word_array):
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
print(''.join(word_array))
count = count + 1
print("You've typed:",count,"word(s).")
Here is the problem section:
if m < i:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
else:
break
m = m + 1
My main problem is that it seems like the second while loop is not iterating when the word is more than five letters long. For example, if I input the word "should" into the program I get back out dhouls. It seems as if only one interchange of letters is being performed. I figure this is a problem with the if statement in that nested while loop, but I can't seem to find what is wrong with it. I carefully sketched out how I think the if statement works in the photo attached.
Your if condition is wrong. You want to compare the two indices that you will use in the list, but the second one is not i, but i-m. So change it to:
if m < i - m:
This corrects your issue. It should be noted that in Python you can reverse string just like this:
print(word_var[::-1])
There are two issues:
The counting of the letters isn't correct. You should just output the length of word_array.
You're iterating the while loop too many times. You should terminate it when m equals or exceeds len(word_array) // 2. Otherwise, you'll unreverse the letters and get the original word back.
i = len(word_array)-1
print("The number of letters in your word is:", len(word_array))
while m < len(word_array) // 2:
word_array[m], word_array[i - m] = word_array[i - m], word_array[m]
m = m + 1
This outputs:
Enter ONE word with NO spaces:should
The number of letters in your word is: 6
dluohs
You've typed: 1 word(s).
I like your project and appreciate your efforts.
This a another way to reverse a string using a list variable and the insert() method.
word_array = []
word_var = input('Your word : ')
word_array = []
for c in word_var:
word_array.insert(0, c)
word_reversed = ''.join(word_array)
print(word_var, '->', word_reversed)
output :
should -> dluohs
I have a small unit of code which is given below :
round = 4
chars = 68
for k in range(round):
if (k % 2) == 0:
Title = 'Start '+chr(chars)
else:
Title = 'Reached ' + chr(chars)
chars = chars - 1
print(Title)
Using this i am getting output like :
Start D
Reached C
Start B
Reached A
What i actually want is i want result like :
Start C
Reached B
Start B
Reached A
how can i get the title in this way please help me in related to this
chars = 67
counter = 1
while counter <= 4:
if (counter % 2) != 0:
title = 'Start '+chr(chars)
counter += 1
chars -= 1
else:
title = 'Reached ' + chr(chars)
counter += 1
print(title)
OUTPUT (as desired):
Start C
Reached B
Start B
Reached A
EXPLANATION:
I used a while loop to iterate over the loop, and incremented the counter variable by 1 after every iteration to make sure the loop will be iterated 4 times. For the first iteration, counter = 1, such that it is an odd number, and will print "Start " + chr(chars) . Chars is set to 67 by default, which represents the letter "C". I then subtracted 1 from chars to make it equal 66, or "B". On the next iteration, counter is equal to 2, so it will print "Reached B". No need to subtract from chars in this iteration, because we want chars to stay as "B" for the next iteration. I basically just repeated this logic in a loop and iterated over it 4 times, to achieve the desired output. Hope this helps!
round = 4
chars = 67
start = True
for k in range(round):
if(start):
print('start '+chr(chars))
start = False
chars = chars-1
else:
print('reached '+chr(chars))
start = True
this code gets your result
start C
reached B
start B
reached A
There are a few things that need to be fixed:
chr(68) represents the letter 'D', so you should initialize the variable chars = 67.
You also want the range to loop through values 1 to 4, so you want range(1,5) instead of range(4) which will loop through the values 0 to 3.
The print statement should be outside of your if/else statements so that it prints on each iteration of the loop.
round = 4
chars = 67
for k in range(1, round+1):
if (k % 2) == 0:
Title = 'Start '+chr(chars)
else:
Title = 'Reached ' + chr(chars)
chars = chars - 1
print(Title)
Output:
Reached C
Start B
Reached B
Start A
A few things to consider while coding. You want to avoid defining variables that have same name as a python function. For example round is a function in python and you have a variable round assigned to 4. I changed it to r instead.
Also chr(68) is D so started the program at 67 to get you the desired result. When it loops first time, the value of k will be 0. That results in the if (k % 2 == 0 to true. That's why you should start with 67.
Also, your print(Title) was not indented correctly. I moved it outside the if-else statement so it can print correctly.
The only change you had to do to your code was in two places. chars = 67 and subtract the value of chars before you assign the new value to Title with Reached.
r = 4 #changed the variable name to r. round is a function
chars = 67 #started with 67 to give you C instead of D
for k in range(r): #used r instead of round
if (k % 2) == 0:
Title = 'Start '+ chr(chars)
else:
chars = chars - 1 #moved this line before you reassign value to Title
Title = 'Reached ' + chr(chars)
print(Title) #modified the indentation to print after each iteration
Output:
Start C
Reached B
Start B
Reached A
Hope this helps you understand the changes and implementation of your code.
I assume I am tackling this problem from the wrong angles or lack the proper understanding of built-in functions and syntax to resolve my issues despite my trying. I also discovered using:
input("Enter input: ")
is dangerous and should use raw_input instead, but can't seem to get this functioning correctly.
I want to write a script that can take user input, convert it into a list, multiply each individual element by 3, scan the solution to that problem for any "3" and remove all occurences of "3" while maintaining all other figures in their respective elements in the list, to then print or return the final result.
ex. entering 1 2 3 would output 6 9 as 1 * 3 = 3 which would be omitted.
ex. entering 2 6 11 would output 6 18 as 11 * 3 = 33 and both 3's would be omitted.
If for instance, user was to input x where x * 3 = 2381193 - I want for this to be converted to 28119.
I believe the simplest way to do this would be to convert to a string?
I started with something like this:
userInput = input("list element seperated by space: ")
nums = userInput.split()
x = int(nums[0]) * 3
y = int(nums[1]) * 3
z = int(nums[2]) * 3
output = x, y, z
negate = list(output)
if "3" in str(x):
del negate[0]
if "3" in str(y):
del negate[1]
if "3" in str(z):
del negate[2]
print(negate)
and now I've re-thought it to:
userInput = raw_input("list element seperated by space: ")
nums = userInput.split()
for x in list(nums):
numsList = int(x) * 3
output = list(numsList)
y = "3"
while y in str(output): output.remove(y)
print(output)
But overall, I am unable to achieve the desired result.
Could you please provide feedback?
It would be greatly appreciated :)
In your case, your first snippet was close to making a solution to your problem. The only thing you would want to do, is to change the conditional statement into an interative statement, like so:
nums = str(input("list element seperated by space: ")).split(" ")
num_list = []
if len(nums) != 1:
num_list = [*(int(num.replace("3", "")) * 3 for num in nums)]
else:
num_list = [nums[0]]
for x in num_list:
if x != 3:
print(str(x).replace("3", "") + " ", end="")
else:
print("0 ", end="")
If you input 11 you would receive 0 and if for instance you had 133 - you would want to remove the 3 but keep the 1.
This part of your question is not clear/elaborated enough hence i did not include this logic in my snippet above. So anyone is free to edit my answer and include it once the point above is clear.
[EDIT]: So i made changes to my snippet above. I have not tested this so there is a chance for it to be wrong. If that is the case, then inform me of any specific patterns/tests that would end as unwanted.
I am working through the book "Introduction to Computation and Programming Using Python" by Dr. Guttag. I am working on the finger exercises for Chapter 3. I am stuck. It is section 3.2, page 25. The exercise is: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sume of the numbers in s.
The previous example was:
total = 0
for c in '123456789':
total += int(c)
print total.
I've tried and tried but keep getting various errors. Here's my latest attempt.
total = 0
s = '1.23,2.4,3.123'
print s
float(s)
for c in s:
total += c
print c
print total
print 'The total should be ', 1.23+2.4+3.123
I get ValueError: invalid literal for float(): 1.23,2.4,3.123.
Floating point values cannot have a comma. You are passing 1.23,2.4,3.123 as it is to float function, which is not valid. First split the string based on comma,
s = "1.23,2.4,3.123"
print s.split(",") # ['1.23', '2.4', '3.123']
Then convert each and and every element of that list to float and add them together to get the result. To feel the power of Python, this particular problem can be solved in the following ways.
You can find the total, like this
s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))
If the number of elements is going to be too large, you can use a generator expression, like this
total = sum(float(item) for item in s.split(","))
All these versions will produce the same result as
total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
total += float(current_number)
Since you are starting with Python, you could try this simple approach:
Use the split(c) function, where c is a delimiter. With this you will have a list numbers (in the code below). Then you can iterate over each element of that list, casting each number to a float (because elements of numbers are strings) and sum them:
numbers = s.split(',')
sum = 0
for e in numbers:
sum += float(e)
print sum
Output:
6.753
From the book Introduction to Computation and Programming using Python at page 25.
"Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s
= '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s."
If we use only what has been taught so far, then this code is one approach:
tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
if ch != ',':
tmp = tmp + ch
elif ch == ',':
num = num + float(tmp)
tmp = ''
# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
total = total + float(c)
print(total)
Works Like A Charm
Only used what i have learned yet
s = raw_input('Enter a string that contains a sequence of decimal ' +
'numbers separated by commas, e.g. 1.23,2.4,3.123: ')
s = "," + s+ ","
total =0
for i in range(0,len(s)):
if s[i] == ",":
for j in range(1,(len(s)-i)):
if s[i+j] == ","
total = total + float(s[(i+1):(i+j)])
break
print total
This is what I came up with:
s = raw_input('Enter a sequence of decimal numbers separated by commas: ')
aux = ''
total = 0
for c in s:
aux = aux + c
if c == ',':
total = total + float(aux[0:len(aux)-1])
aux = ''
total = total + float(aux) ##Uses last value stored in aux
print 'The sum of the numbers entered is ', total
I think they've revised this textbook since this question was asked (and some of the other's have answered.) I have the second edition of the text and the split example is not on page 25. There's nothing prior to this lesson that shows you how to use split.
I wound up finding a different way of doing it using regular expressions. Here's my code:
# Intro to Python
# Chapter 3.2
# Finger Exercises
# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
total = total + float(s)
print(total)
I've never considered myself dense when it comes to learning new things, but I'm having a hard time with (most of) the finger exercises in this book so far.
s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
if c != ',':
x = x + c
else:
sum = sum + float(x)
x = ''
sum = sum + float(x)
print(sum)
This is using just the ideas already covered in the book at this point. Basically it goes through each character in the original string, s, using string addition to add each one to the next to build a new string, x, until it encounters a comma, at which point it changes what it has as x to a float and adds it to the sum variable, which started at zero. It then resets x back to an empty string and repeats until all the characters in s have been covered
Here's a solution without using split:
s='1.23,2.4,3.123,5.45343'
pos=[0]
total=0
for i in range(0,len(s)):
if s[i]==',':
pos.append(len(s[0:i]))
pos.append(len(s))
for j in range(len(pos)-1):
if j==0:
num=float(s[pos[j]:pos[j+1]])
total=total+num
else:
num=float(s[pos[j]+1:pos[j+1]])
total=total+num
print total
My way works:
s = '1.23, 211.3'
total = 0
for x in s:
for i in x:
if i != ',' and i != ' ' and i != '.':
total = total + int(i)
print total
My answer is here:
s = '1.23,2.4,3.123'
sum = 0
is_int_part = True
n = 0
for c in s:
if c == '.':
is_int_part = False
elif c == ',':
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
sum = 0
is_int_part = True
n = 0
else:
sum *= 10
sum += int(c)
if is_int_part == False:
n += 1
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
print total
I have managed to answer the question with the knowledge gained up until 3.2 the section for loop
s = '1.0, 1.1, 1.2'
print 'List of decimal number'
print s
total = 0.0
for c in s:
if c == ',':
total += float(s[0:(s.index(','))])
d = int(s.index(','))+1
s = s[(d+1) : len(s)]
s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total
This is the answer to the question i feel that the split function is not good for beginner like you and me.
Considering the fact that you might not yet be exposed to more complex functions, simply try these out.
total = 0
for c in "1.23","2.4",3.123":
total += float(c)
print total
My answer:
s = '2.1,2.0'
countI = 0
countF = 0
totalS = 0
for num in s:
if num == ',' or (countF + 1 == len(s)):
totalS += float(s[countI:countF])
if countF < len(s):
countI = countF + 1
countF += 1
print(totalS) # 4.1
This only works if the numbers are floats
Here is my answer. It is similar to the one by user5716300 above, but since I am also a beginner I explicitly created a separate variable s1 for the split string:
s = "1.23,2.4,3.123"
s1 = s.split(",") #this creates a list of strings
count = 0.0
for i in s1:
count = count + float(i)
print(count)
If we are just sticking with the content for that chapter, I came up with this: (though using that sum method mentioned by theFourthEye is also pretty slick):
s = '1.23,3.4,4.5'
result = s.split(',')
result = list(map(float, result))
n = 0
add = 0
for a in result:
add = add + result[n]
n = n + 1
print(add)
I just wanna to post my answer because I am reading this book now.
s = '1.23,2.4,3.123'
ans = 0.0
i = 0
j = 0
for c in s:
if c == ',':
ans += float(s[i:j])
i = j + 1
j += 1
ans += float(s[i:j])
print(str(ans))
Using knowledge from the book:
s = '4.58,2.399,3.1456,7.655,9.343'
total = 0
index = 0
for string in s:
index += 1
if string == ',':
temp = float(s[:index-1])
s = s[index:]
index = 0
total += temp
temp = 0
print(total)
Here I used string slicing, and by slicing the original string every time our 'string' variable is equal to ','. Also using an index variable to keep track of the number that is before the comma. After slicing the string, the number that gets input into tmp is cleared with the comma in front of it, the string becoming another string without that number.
Because of this, the index variable needs to be reset every time this happens.
Here's mine using the exact string in the question and only what has been taught so far.
total = 0
temp_num = ''
for char in '1.23,2.4,3.123':
if char == ',':
total += float(temp_num)
temp_num = ''
else:
temp_num += char
total += float(temp_num) #to catch the last number that has no comma after it
print(total)
I know this isn't covered in the book up to this point but I happened to learn the use of the eval() function on my own prior to getting to this question and used it to solve.
total = 0
s = "1.23,2.4,3.123"
x = eval(s)
y = sum(x)
print(y)
I think this is the easiest way to answer the question. It uses the split command, which is not introduced in the book at this moment but a very useful command.
s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
sList = s.split(',') #create a list of these values
print(sList) #to check if list is correctly created
total = 0 #for creating the variable
for each in sList:
total = total + float(each)
print(total)
total =0
s = {1.23,2.4,3.123}
for c in s:
total = total+float(c)
print(total)