This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 5 years ago.
I don't understand why my code doesn't work.
The code is:
def trans(old):
length = len(old)
new = []
new = old
for i in range(0,length):
print(old[length-i-1])
for i in range(0,length):
new[i] = old[length-i-1]
print("new:",new[i]," [i]:",i," old:",old[length-i-1]," length-
i-1:",length-i-1)
ihavenoideawhatimdoing = " ".join(new)
return new
Instruction:
1. def trans(old): Input sentence in (old)
2. length(len): Take number of elements in the sentence
3. new = [] and new = old is to make a container with the same size for the new word
4. First for loop = I wanted to see the words in the original sentence backwards
5. My problem is in the second for loop. See the output
6. What comes next is related to the problem I'm solving but not to the problem I'm having
Output
Input sentence: "please help me solve this"
I didn't any label for the next batch of words but it's supposed to be:
old(length-0-1) -> old(5-0-1) -> old(4): this
old(3): solve
old(2): me
old(1):help
old(0): please
Now, what's iffy is in the next for statement at length-i-1 = 1 where instead of being "help", it's "solve."
Both codes are familiar so I'm stuck at what else could be wrong.
Use this:
def trans(old):
new = old.split(" ")
new_str = ""
for i in reversed(new):
new_str = new_str + " " + i
print new_str
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 months ago.
I am a at the very beginning of learning to code in python and am following a tutorial. I attempted to convert this string into an integer to get it to simply add 5 and 6. Here is what I have
No matter what I do, I get 5+6 = 56. Here is what I have:
first_num = (input('Please enter a number '))
second_num = (input('Please enter another number '))
print int((first_num) + int(second_num))
I tried using a comma instead of a plus sign, as a few places suggested. I also tried using int in front of the input line to convert the inputs themselves from strings to integer.
I expect it to add 5 + 6 = 11. I keep getting 56.
I'm not positive what version of Python I'm using, but I know I'm using VS Code and it is Python 3.X. i just don't know what the X is. Here is a screenshot
edit: I have resolved this question. I was not saving the file before I ran it. Therefore every time I tried to change something it was just running the saved, incorrect file. Thanks to those that tried to help me.
In Python when you add two strings together you concatenate the values.
For an easier example:
string_one = "hello"
string_two = " "
string_three = "there"
final = string_one + string_two + string_3
print(final) # hello there
To add them together mathematically, you need to ensure the values are ints, floats, decimals...
one = 1
two = 2
final = one + two
print(final, type(final)) # 3 int
So for your code:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
final = first_num + second_num
print(final) # will give you the numbers added
However, you are casting to ints based on user input, so I would ensure you are also catching the errors that occur when a user enters a value that cannot be cast to an int, like hi. For example:
try:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
print(first_num + second_num) # will give you the numbers added, if ints
except ValueError as ex:
# if any input val is not an int, this will hit
print("Error, not an int", ex)
Try this
first_num = int(input('Please enter a number '))
second_num = int(input('Please enter another number '))
sum=first_num+second_num
print (sum)
This question already has answers here:
python .lower() is not working [duplicate]
(3 answers)
Closed 1 year ago.
I don't know what I'm doing wrong here. Please help.
def AddColon (data):
data.strip() # --> to remove the spaces
result = ''
for i in range (len(data)):
if str(data[i]).isalpha(): # to only include letters
result = result + data[i]
result.lower() # to make everything lowercase
result[0].upper() # to make the first letter uppercase
finalresult = result + ' : Hello'
return finalresult
input1 = input('Insert Data : ')
print(AddColon(str(input1)))
If your input contains any numbers or integers it may not go under if condition and the result will not be updated. To get a exact value, u may need to give only strings as input not alphanumeric.After that remove the indentation in for loop and if condition...try removing that and run your code. Your code and output is ready.
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 2 years ago.
I have a function call as follow:
send_at('AT+CMQPUB=0,"sensor",1,0,0,34',"hex_numbers_here",'OK',10)
I want the "34" and the "hex_numbers_here" to be variables instead of literal inputs, but my attempts to "escape" out of the quotes are failing miserably...
Please help!
I tried:
send_at('AT+CMQPUB=0,"sensor",1,0,0,'+myval+',"'+my_hex+'",'OK',10)
where myval and my_hex are the variables I created earlier in my code.
update:
I tried the following as well now:
mqtt_msg = b'testing mqtt message from sim7020'
output = binascii.b2a_hex(mqtt_msg)
length = len(output)
print(output)
output_text = str(output)
print(output_text)
f1 = 'AT+CMQPUB=0,"sensor",1,0,0,'+str(length)+',"'+output_text+'"'
f2 = 'OK'
f3 = '10'
print(f1)
AT+CMQPUB=0,"sensor",1,0,0,66,"b'74657374696e67206d717474206d6573736167652066726f6d2073696d37303230'"
The only thing noiw is that the output_text variable should not contain the b'' - making me think that the casting to str() of the hex/bit value is now doing what I think it should be doing...
BTW - I HAVE to cast the text to binary/hex - this is what the modem wants...
UPDATE:
OK, I found a way around this that is working now:
mqtt_msg = b'testing mqtt message from sim7020 - and again!'
output = binascii.b2a_hex(mqtt_msg)
length = len(output)
print(output)
output_text = str(output)
print(output_text)
output_text = output_text[2:length+2]
new_len = len(output_text)
f1 = 'AT+CMQPUB=0,"sensor",1,0,0,'+str(new_len)+',"'+output_text+'"'
f2 = 'OK'
f3 = '10'
print(f1)
I'm basically just stripping out the first 2 and last chars from the string.
What about this?
def send_at(p1, p2, p3, p4):
print(p1, p2, p3, p4)
send_at('AT+CMQPUB=0,"sensor",1,0,0,{}'.format(34), '{}'.format('FC0012'), 'ok', 10)
Output:
AT+CMQPUB=0,"sensor",1,0,0,34 FC0012 ok 10
I am creating a cipher script in python without any modules but I have come accross a problem that i cant solve. When I am comparing msg[3] which has the value (space) it should be equal to bet[26] which is also a space. If i compare msg[3] with bet[26] in the shell...
>>>msg[3] == bet[26]
True
The output is True. However when i run the program and output the value of enmsg there is no value 26 where the value 26 should be.
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for x in range(0, len(msg)):
for i in range(0, 26):
if msg[x] == bet[i]:
print(msg[x])
enmsg.append(i)
You should get out of the habit of iterating over a range of indices and then looking up the value at the index. Instead iterate directly over your iterables, using enumerate when necessary.
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for msg_char in msg:
for index, bet_char in enumerate(bet):
if msg_char == bet_char:
print(msg_char)
enmsg.append(index)
Your second loop iterations are too short so it is not reaching the space symbol.
Try with this:
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for x in range(0, len(msg)):
for i in range(len(bet)):
if msg[x] == bet[i]:
print(msg[x])
enmsg.append(i)
The upper bound of range is not inclusive; you'll need to extend this by one to actually check the 26th index of the string. Better yet, iterate up through len(bet) as you did for len(msg) for the outer loop.
Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*