Repeated Character Whose First Appearance in Python [duplicate] - python

This question already has answers here:
Code to output the first repeated character in given string?
(10 answers)
Closed 2 years ago.
You are given a string S
Your task is to find the first occurrence of an alphanumeric character in S(read from left to right) that has consecutive repetitions.
Input Format
A single line of input containing the string S.
Output Format
Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
For example,
If I input the below string
..12345678910111213141516171820212223
the result is
1
I solved this problem but that's not correct.
My code is
def firstRepeatedChar(str):
h = {}
for ch in str:
if ch in h:
return ch;
else:
h[ch] = 0
return -1
n = input()
print(firstRepeatedChar(n))
but if I input the ^^cmmit^^, the result is not correct.
How can I solve this problem with python? Please help me.

A pythonic way to do something like this is to use zip() to make consecutive pairs of tuples (like (1, 2), (2, 3) ... and then just return the first one where both are equal and alphanumeric.
next() takes an optional parameter for what to return when there's nothing left, to which here you can pass -1. isalnum() can be used to test is a string is alphanumeric:
def firstRepeatedChar(s):
return next((j for j, i in zip(s, s[1:]) if j == i and j.isalnum()), -1)
firstRepeatedChar("..12345678910111213141516171820212223")
# 1
firstRepeatedChar("^^cmmit^^")
# 'm'
firstRepeatedChar("^^cmit^^")
# -1

Related

What does "[1:][::-1]" mean, for example (str) a[1:][::-1]? [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed last month.
This is actually a problem on leetcode, I found this part of code in the solution. But I couldn't understand how does this part of code work. The problem was just basically reverse a given integer, for example: x = 123, then the result should return 321.
This is the code:
class Solution:
def reverse(self, x: int) -> int:
s = str(x)
def check(m):
if ans > 4294967295/2 or ans < -4294967295/2:
return 0
else:
return ans
if x < 0:
ans = int('-' + s[1:][::-1])
return check(ans)
else:
ans = int(s[::-1])
return check(ans)
I'm a beginner in programming so I have never seen anything like that in a string in python.
These are Python string slices.
There are three parts to a string slice - the starting position, the end position and the step. These take the form string_obj[start_position:end_position:step].
When omitted the start position will default to the start of the string, then end position will default to the end of the string, and the step will default to 1.
The expression s[1:][::-1] is doing two slice operations.
s[1:] uses index 1 as the start position and leaves the end position blank (which defaults to the end of the string). It returns a string that's the same as s only without the first character of the string.
This new string is then fed into the second slicing operation. [::-1] has no start or end position defined so the whole string will be used, and the -1 in the step place means that the returned string will be stepped through backwards one step at a time, reversing the string.
I will explain with an example
x = 123
s = str(x) #index will be 0, 1, 2
print(s[1:])
This will print 23 as the output. ie, The index starts from 0, when you put s[1:] the index starts from 1 and goes till the end gets printed out.
s[::-1] will reverse the string. ":" means starting from the beginning and going till the ending ":" with a step of -1. This means that it will start from the ending and goes to the start as the step is -1.
In this particular problem, we need to reverse the integer. When the number becomes less than zero. -123 when reversed using string ie, s[::-1] gets converted to 321-. In order to reverse the negative integer as -321, s[1:] is used to remove "-" and converting the 123 to 321
ans = int('-' + s[1:][::-1])
When the integer value is less than 0.
The above line of code converts the -123 to -321. "-" gets neglected when reversing the string and gets added up when '-' + s[1:][::-1] this string operation works. Taking int() the string will convert "-321" to -321, ie, string to integer form.
When the integer value is above 0
We only need to reverse the integer using s[::-1]
def check(m):
if ans > 4294967295/2 or ans < -4294967295/2:
return 0
else:
return ans
This is a constraint given in the problem that the values of the reversed integer should be between -2^31 and 2^31 otherwise it should be returned 0.

How to find maximum value of two numbers in python? [duplicate]

This question already has answers here:
How do I compare version numbers in Python?
(16 answers)
Closed 6 years ago.
I want to get the maximum value from a list.
List = ['1.23','1.8.1.1']
print max(List)
If I print this I'm getting 1.8.1.1 instead of 1.23.
What I am doing wrong?
The easiest way is, to use tuple comparison.
Say:
versions = ['1.23','1.8.1.1']
def getVersionTuple(v):
return tuple(map(int, v.strip().split('.')))
Now you can use, print(max(map(getVersionTuple, versions))) to get the maximum.
EDIT:
You can use '.'.join(map(str, m)) to get the original string (given m holds the max tuple).
These aren't numbers, they are strings, and as such they are sorted lexicographically. Since the character 8 comes after 2, 1.8.1.1 is returned as the maximum.
One way to solve this is to write your own comparing function which takes each part of the string as an int and compares them numerically:
def version_compare(a, b):
a_parts = a.split('.')
b_parts = b.split('.')
a_len = len(a_parts)
b_len = len(b_parts)
length = min(a_len, b_len)
# Compare the parts one by one
for i in range(length):
a_int = int(a_parts[i])
b_int = int(b_parts[i])
# And return on the first nonequl part
if a_int != b_int:
return a_int - b_int
# If we got here, the longest list is the "biggest"
return a_len - b_len
print sorted(['1.23','1.8.1.1'], cmp=version_compare, reverse=True)[0]
A similar approach - assuming these strings are version numbers - is to turn the version string to an integer list:
vsn_list=['1.23', '1.8.1.1']
print sorted( [ [int(v) for v in x.split(".")] for x in vsn_list ] )
When you compare strings, they are compared character by character so any string starting with '2' will sort before a string starting with '8' for example.

how to find the length of a list in python without using len() [duplicate]

This question already has answers here:
String length without len function
(17 answers)
Closed 6 months ago.
I want to write a function which will find out the length of a list based on user input. I don't want to use the in-built function len().
Function which i have written is working for strings but for lists it is failing.
#function for finding out the length
def string_length(a):
for i in a:
j+=1
return j
#taking user input
a = input("enter string :")
length = string_length(a)
print("length is ", length)
You probably need to initialize your variable j (here under renamed counter):
def string_length(my_string):
"""returns the length of a string
"""
counter = 0
for char in my_string:
counter += 1
return counter
# taking user input
string_input = input("enter string :")
length = string_length(string_input)
print("length is ", length)
This could also be done in one "pythonic" line using a generator expression, as zondo has pointed out:
def string_length(my_string):
"""returns the length of a string
"""
return sum(1 for _ in my_string)
It's quite simple:
def string_length(string):
return sum(1 for char in string)
1 for char in string is a generator expression that generates a 1 for each character in the string. We pass that generator to sum() which adds them all up. The problem with what you had is that you didn't define j before you added to it. You would need to put j = 0 before the loop. There's another way that isn't as nice as what I put above:
from functools import reduce # reduce() is built-in in Python 2.
def string_length(string):
return reduce(lambda x,y: x+1, string, 0)
It works because reduce() calls the lambda function first with the initial argument, 0, and the first character in the string. The lambda function returns its first argument, 0, plus one. reduce() then calls the function again with the result, 1, and the next character in the string. It continues like this until it has passed every character in the string. The result: the length of the string.
you can also do like this:
a=[1,2,2,3,1,3,3,]
pos=0
for i in a:
pos+=1
print(pos)
Just a simple answer:
def mylen(lst):
a = 0
for l in lst: a+=1
return a
print(mylen(["a","b",1,2,3,4,5,6,67,8,910]))

trying to find if a character appears successively in a string

Simple script to find if the second arguement appears 3 times successively in the first arguement. I am able to find if the second arguement is in first and how many time etc but how do i see if its present 3 times successively or not ?
#!/usr/bin/python
import string
def three_consec(s1,s2) :
for i in s1 :
total = s1.count(s2)
if total > 2:
return "True"
print three_consec("ABABA","A")
total = s1.count(s2) will give you the number of s2 occurrences in s1 regardless of your position i.
Instead, just iterate through the string, and keep counting as you see characters s2:
def three_consec (string, character):
found = 0
for c in string:
if c == character:
found += 1
else:
found = 0
if found > 2:
return True
return False
Alternatively, you could also do it the other way around, and just look if “three times the character” appears in the string:
def three_consec (string, character):
return (character * 3) in string
This uses the feature that you can multiplicate a string by a number to repeat that string (e.g. 'A' * 3 will give you 'AAA') and that the in operator can be used to check whether a substring exists in a string.

Create Your Own Find String Function

For a school project I have to create a function called find_str that essentially does the same thing as the .find string method, but we cannot use any string methods in our definition.
The project description reads: "Function find_str has two parameters (both strings). It returns the lowest index where the second parameter is found within the first parameter (it returns -1 if the second parameter is not found within the first parameter)."
I have spent a lot of time working on this project and have yet to come to a solution. This is the current definition that I have come up with:
def find_str (string, substring):
index = 0
length = len (substring)
for ch in string:
if ch == substring [0]:
subindex1 = 0
subindex2 = index
for i in range (length):
if ch == substring [i]:
subindex1 +=1
if subindex1 == length:
return index
ch = string [(subindex2)+1]
subindex2 +=1
index += 1
return "-1"
This sample of code only works in some instances, but not all.
For example:
print (find_str ("hello", "llo"))
returns:
2
as it should.
But
print (find_str ("hello", "el"))
returns:
ch = string [(subindex2)+1]
IndexError: string index out of range
I feel like I am overthinking this and there must be is an easier way to do it. Any input or help would be great! Thanks.
FFUsing a sub function to clear your thoughts often help.
def find_str (string, substring):
index = 0
length = len (substring)
for j in range(len(string)):
if is_next_sub(string, substring, j):
return j
return "-1"
def is_next_sub(string, substring, index):
for i in range(len(substring)):
if substring[i] != string[index + i]:
return False
return True
I'm not sure we should be helping you with 'homework'
How about this:
def find_str(string, substring):
for off in xrange(len(string)):
if string[off:].startswith(substring):
return off
return -1
I haven't checked through your code in detail, but it looks like you're trying to compare characters that don't exist.
Suppose you're searching "aaaaa" for the substring "aaa", and you need to find all matches...
String : aaaaa
Match at 0 : aaa..
Match at 1 : .aaa.
Match at 2 : ..aaa
Even though the characters always match, and there five characters in the string, there are only three positions that you might need to consider.
So before you look at the actual characters at all, you can restrict the number of start positions you might need to consider based on the lengths of the string and substring. You only loop for those start positions. That means you're not looping for start positions that cannot match. Also, if you don't do this...
String : aaaaa
Match at 0 : aaa..
Match at 1 : .aaa.
Match at 2 : ..aaa
Match at 3 : ...aa!
Match at 4 : ....a!!
Those exclamation points are places where you try to match a character in the substring with a character that doesn't exist, after the end of the string. You can check for that within the loop to avoid the error each time it occurs, but why not eliminate all those cases at once by not looping for the match positions that cannot occur?
The number of start positions you may need to check is len(fullstring) + 1 - len(substring), so you can derive a range of possible start positions using range(0, len(fullstring) + 1 - len(substring)).

Categories

Resources