This question already has answers here:
Python error: "IndexError: string index out of range"
(4 answers)
Closed 3 years ago.
Here is my program I want to find the weather it is a sum string or not based on the following condition
1)the string length must be >3
example:"12358" --- 1+2=3,2+3=5,3+5=8
I tried this program I am getting the index error please help me.Thank you in adavnce.
Given below is my code:
y="12358"
for i in range(len(y)-1):
if y[i]+y[i+1]==y[i+2]:
print "sum stringgg"
The upper bound of the range should be the length of y minus 2 instead to accommodate the comparison with the item of the index plus 2. You should also convert each character in the string to an integer for arithmetic addition and comparison. Finally, you should use the for-else construct to break whenever the former two digits do not add up to the latter digit, and only output 'sum string' if the loop finishes without break:
y = "12358"
digits = list(map(int, y))
for i in range(len(digits) - 2):
if digits[i] + digits[i + 1] != digits[i + 2]:
break
else:
print('sum string')
Related
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:
Generate random numbers only with specific digits
(3 answers)
Closed 2 years ago.
How would you generate a random number string in Python based on the following conditions.
The string must be between the length of 3 and 7
The string must only contain numbers from 1-7
The string must not have spaces
I tried the following for the string output but I am struggling with the conditionals
letters = string.digits
print ( ''.join(random.choice(letters) for i in range(10)) )
The output I received was:=
9432814671
If you could be kind enough to help me out and guide me I would be grateful to you.
The solution is self-explanatory, and you were close to it:
length = random.randint(3, 7)
"".join(str(random.randint(1, 7)) for _ in range(length))
#'724613'
Given question - Given a list of 10 numbers, find the average of all such numbers which is a multiple of 3
num = []
newlist = []
for i in range(1, 11):
num.append(input())
for i in num:
if i%3==0:
newlist.append(i)
length = len(newlist)
total = sum(newlist)
average = total/length
print(average)
Getting this type error below at line 9 i.e. if i%3==0
not all arguments converted during string formatting
input() returns a string, so i%3 will actually perform printf-style string formatting. Since your input doesn't have any formatting specifiers, but the % operator's right operand is not empty, you get the error, because you attempted to format a sting that doesn't have enough formatting specifiers.
To solve this, convert your input to integers:
num.append(int(input()))
When you num.append(input()), the value of input() is a string. You need to first convert that to an int and handle any possible errors before continuing. One way to do this is to change it to:
num.append(int(input()))
Since all the values in num are strings, i % 3 tries to perform old-string formatting, which is not what you expect.
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Return middle part of string
(2 answers)
Swap list / string around a character python
(1 answer)
Python code to swap first and last letters in string
(4 answers)
Write a function swap_halves(s) that takes a string s, and returns a new string in which the two halves of the string have been swapped
(3 answers)
Closed 3 years ago.
In python, how would you swap the first and last parts of a string but leave the middle character in the same place? For example, if I have ABCDE, then the result would be DECAB.
def swap(str1):
return str1[-1]+str1[1:-1]+str1[:1]
print(swap("Hello"))
With this, I am only able to swap the first and last letter of the string. So the result for 'Hello' is 'oellH'.
You can obtain the index of the middle character with the floor division //:
5 //2
# 2
So, you can change your code like this:
def swap(str1):
middle = len(str1) // 2
return str1[middle+1:] + str1[middle] + str1[:middle]
print(swap("ABCDE"))
# DECAB
Note that this only works for strings with an odd number of characters. We could modify the function to also handle strings with even numbers of chars, just swapping both halves in this case:
def swap(str1):
middle = len(str1) // 2
if len(str1) % 2 == 0:
# even length
return str1[middle:] + str1[:middle]
else:
# odd length
return str1[middle+1:] + str1[middle] + str1[:middle]
print(swap("ABCDE"))
# DECAB
print(swap("ABCDEF"))
# DEFABC
I have 2 question regarding searching for strings in MATLAB
If I have to find a string in a cell array of strings I can do the following to get the location of 'PO' in the cell array
find(strcmpi({'PO','FOO','PO1','FOO1','PO1','PO'},'PO'))
% 1 6
But, I really want to search for multiple strings ({'PO1', 'PO'}) at the same time (not using a for loop). What is the best way to do this?
Is there any function like histc() which can tell me how many times the string has occurred. Again for one string, I could do:
length(strfind({'PO','FOO','PO1','FOO1','PO1','PO'},'PO'))
But this obviously doesn't work for multiple strings at a time.
If you want to find multiple strings, then just use the second output of ismember instead to tell you which string it is. If you really need case-insensitive matching, I've added the upper call to force all inputs to be upper-case. You can omit this if you think it's already uppercase.
data = {'PO','FOO','PO1','FOO1','PO1','PO', 'PO'};
[tf, inds] = ismember(upper(data), {'PO1', 'PO'});
% 2 0 1 0 1 2 2
You can then use the second output to determine which string was found where:
% PO1 Occurrences
find(inds == 1)
% 3 5
% PO Occurrences
find(inds == 2)
% 1 6 7
If you want the equivalent of histc, you can use accumarray to do that. We can pass it all of the values of inds that are non-zero (i.e. the ones that you were actually searching for).
accumarray(inds(tf).', ones(sum(tf), 1))
% 2 3
If instead you want to get the histogram of all strings (not just the ones you're searching for) you could do the following:
[strings, ~, inds] = unique(data, 'stable');
occurrences = accumarray(inds, ones(size(inds)));
% 'PO' [3]
% 'FOO' [1]
% 'PO1' [2]
% 'FOO1' [1]