Do you ♥ these questions and want to support my work?
Please consider sending me some crypto to the following addresses, it would help alot with my codebyte membership and hosting fees.
Bitcoin:
15RCQ6QtrjB73QHKUM8aqV7i1yWk8RdeWo
Etherium:
0x3647f0ddef0de30428833cf187b0b9ffcc494b9d
Litecoin:
MUMQtK5cFeZynW9DCkrNq6AAtNTm3W1mnt
Dash (DASH):
Xfw8v6wCjmYaT7q71jmJnbD4QmDxHoDYbg
Bitcoin Cash SV (BSV):
1Nr3W8MDy7QU8ph3u65rRsASXq5Bctq9cA
IN: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
OOUT: 7-4-6-10-6
ArrayMatching(strArr)
read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers.
Example:
if strArr =
["[1, 2, 5, 6]", "[5, 2, 8, 11]"]``
then both elements in the input represent two integer arrays, and your goal for this challenge is to add the elements in corresponding locations from both arrays.
For the example input, your program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]
.
Your program should finally return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17
.
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array (example shown below).
Both arrays will be in the format: [e1, e2, e3, ...]
where at least one element will exist in each array.
Example
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2
def ArrayMatching(strArr):
l1 = strArr[0][1:-1].split(", ")
l2 = strArr[1][1:-1].split(", ")
l1 = list(map(int, l1))
l2 = list(map(int, l2))
if len(l1) != len(l2):
n = max(len(l1), len(l2))
l1.extend([0] * (n - len(l1)))
l2.extend([0] * (n - len(l2)))
res = [str(a+b) for a,b in zip(l1, l2)]
return "-".join(res)
or
def ArrayMatching(strArr):
x = [int(i) for i in strArr[0][1:-1].split(',')]
y = [int(i) for i in strArr[1][1:-1].split(',')]
sums = []
for i in range(max(len(x), len(y))):
total = 0
if i < len(x):
total += x[i]
if i < len(y):
total += y[i]
sums.append(str(total))
return '-'.join(sums)
or
def ArrayMatching(sa):
for i in range(len(sa)):
sa[i] = sa[i].strip("[] ")
for i in range(len(sa)):
sa[i] = sa[i].split(",")
for j in range(len(sa[i])):
sa[i][j]= int(sa[i][j])
m = 0
for i in range(len(sa)):
if len(sa[i]) > m:
m = len(sa[i])
for i in range(len(sa)):
while len(sa[i]) < m:
sa[i].append(0)
z = str()
for i in range(len(sa[0])):
k = 0
for j in range(len(sa)):
k+= sa[j][i]
z+=str(k) + "-"
return z[:-1]
or
def ArrayMatching(strArr):
liste1=[int(n) for n in str(strArr[0]).replace('[','').replace(']','').split(',')]
liste2=[int(n) for n in str(strArr[1]).replace('[','').replace(']','').split(',')]
if len(liste1) >=len(liste2):
listeMax=liste1
listeTwo=liste2
else:
listeMax=liste2
listeTwo=liste1
for i in range(0, len(listeTwo)):
listeMax[i]+=listeTwo[i]
return '-'.join(str(x) for x in listeMax)
StringPeriods(str)
1 Determine if there is some substring K
2 that can be repeated N > 1 times
3 to produce the input string exactly as it appears.
Your program should return the longest substring K,
and if there is none it should return the string -1.
Example:
If str is "abcababcababcab"
then your program should return abcab because that is the longest substring that is repeated 3 times to create the final string.
Another example:
If str is "abababababab"
then your program should return ababab because it is the longest substring.
If the input string contains only a single character, your program should return the string -1.
Examples
Input: "abcxabc"
Output: -1
Input: "affedaaffed"
Output: -1
def StringPeriods(s):
if len(s)==1:
return "-1"
if s == s[0]*len(s):
r = len(s)//2
return s[:r]
choice = []
for i in range(1,len(s)-1):
if s[0] == s[i]:
l = s[:i]
x = int((len(s))/(i))
n = l*x
if n==s:
choice.append(l)
if len(choice) == 0:
return "-1"
subst = ""
for k in range(len(choice)):
if len(choice[k]) > len(subst):
subst = choice[k]
return subst
or
def StringPeriods(s):
for i in range(int(len(s)/2), 0,-1):
a = s[:i]
count = 2
b = ''
while len(b) < len(s):
b = a * count
if b == s:
return a
count += 1
return -1
or
def StringPeriods(string):
for i in range(len(string) // 2, 0, -1):
if len(string) % i:
continue
substring = string[0:i]
result = substring
repeatNumber = (len(string) // i) - 1
for j in range(repeatNumber):
substring += result
if substring == string:
return result
return "-1"
or
stringPeriodsHolder = []
def substringMakesOriginalString(substring, originalString, expected=None):
concatString = ""
while len(concatString) < len(originalString):
concatString = concatString + substring
output = substring != originalString and concatString == originalString
if expected != None:
assert expected == output, "substringMakesOriginalString " + str(output)
return output
def breakWord(substring, originalString, output, visitedNodes, expected=None):
visitedNodes.append(substring)
if len(substring) == 1:
if substringMakesOriginalString(substring, originalString):
output[substring] = ""
return output
if len(substring) == 0:
return output
smallerSubstring = substring[1:]
breakWord(smallerSubstring, originalString, output, visitedNodes)
if substringMakesOriginalString(substring, originalString):
output[substring] = ""
if expected != None:
assert expected == visitedNodes, "breakWord " + str(visitedNodes)
return output
def tests():
substringMakesOriginalString("aba", "abaaba", True)
substringMakesOriginalString("a", "abaaba", False)
substringMakesOriginalString("a", "a", False)
substringMakesOriginalString("abaaba", "abaaba", False)
dict1 = breakWord("ababab", "abababab", {}, [], ["ababab", "babab", "abab", "bab", "ab", "b"])
assert dict1 == {"abab":"", "ab":""}, "dict1 " + str(dict1)
dict2 = breakWord("gg", "gg", {}, [], ["gg", "g"])
assert dict2 == {"g":""}, "dict2 " + str(dict2)
dict3 = breakWord("g", "g", {}, [], ["g"])
assert dict3 == {}, "dict3 " + str(dict3)
def StringPeriods(string):
tests()
dictionary = breakWord(string, string, {}, [])
if len(dictionary) == 0:
return -1
sortedSubstrings = sorted(dictionary.items(), key=lambda tup: len(tup[0]), reverse=True)
return sortedSubstrings[0][0]
Have the function RemoveBrackets(str) take the str string parameter being passed, which will contain only the characters "(" and ")", and determine the minimum number of brackets that need to be removed to create a string of correctly matched brackets.
For example:
If str is "(()))" then your program should return the number 1.
The answer could potentially be 0, and there will always be at least one set of matching brackets in the string.
Examples
Input: "(())()((("
Output: 3
Input: "(()("
Output: 2
def RemoveBrackets(str):
# code goes here
stack = list()
for i in str:
if len(stack) == 0:
stack.append(i)
else:
if i == ')' and stack[-1] == '(':
stack.pop()
else:
stack.append(i)
return len(stack)
or
def RemoveBrackets(str):
scopes = []
for i in str:
if i == '(':
scopes.append(i)
elif i == ')':
if len(scopes) > 0:
if scopes[-1] == '(':
scopes.pop()
else:
scopes.append(i)
return len(scopes)
or
def RemoveBrackets(s):
details = []
count = 0
for i in range(len(s)):
if s[i] == "(":
details.append(s[i])
else:
if len(details)>0 and details[-1] == "(":
details.pop()
else:
count +=1
return count + len(details)
or
def RemoveBrackets(string):
for _ in range(len(string)):
string = string.replace("()", "")
return len(string)
In: "after badly"
Out: false
Return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once
(ie. "lane borrowed" would result in true because there is exactly three characters between a and b).
Otherwise return the string false.
Examples
Input: "after badly"
Output: false
Input: "Laura sobs"
Output: true
Tags
string manipulationregular expression
def ABCheck(a_string):
for index in xrange(len(a_string) - 4):
if a_string[index] == 'a':
if a_string[index + 4] == 'b':
return True
elif a_string[index] == 'b':
if a_string[index + 4] == 'a':
return True
return False
or
def ABCheck(str):
for i in range(0,len(str)):
if i < len(str)-4:
if str[i]=="a" and str[i+4]=="b":
return "true"
if str[i]=="b" and str[i+4]=="a":
return "true"
return "false"
print(ABCheck(input()))
or
def ABCheck(str):
str = "00000" + str + "00000"
for i, char in enumerate(str):
if char == "a":
if str[i+4] == "b" or str[i-4] == "b":
return "true"
return "false"
or
def ABCheck(str):
a = [pos for pos, char in enumerate(str) if char in ('a', 'A')]
b = [pos for pos, char in enumerate(str) if char in ('b', 'B')]
for pos_a in a:
for pos_b in b:
if abs(pos_a - pos_b) == 4:
return 'true'
return 'false'
or
def ABCheck(str):
chaine=str.lower()
chaine=(" " * 4 )+ chaine + (" " * 4 )
test="false"
for index in range(len(chaine)-1):
if chaine[index] == "a":
if chaine[index+4] == "b" or chaine[index-4] == "b":
test="true"
return test
return the string with the letters in alphabetical order:
Assume numbers and punctuation symbols will not be included in the string.
Input: "coderbyte"
Output: bcdeeorty
Input: "hooplah"
Output: ahhloop
def AlphabetSoup(a_string):
list_of_chars = []
for char in a_string.lower():
list_of_chars.append(char)
ordered_list = sorted(list_of_chars)
alphabetical_string = ''.join(ordered_list)
return alphabetical_string
or
def AlphabetSoup(str):
data = []
for x in range(len(str)): # Turns a string into a list where each index is where a char is located
data.append(str[x])
data = sorted(data) # Sorts the list in alphabetical order
return ''.join(data) # Combines the list into a stirng
or
https://github.com/gregorymcintyre/r-dailyprogrammer/blob/master/AlphabetSoup.py
def AlphabetSoup(str):
return ''.join(sorted(list(str)))
print(AlphabetSoup("coderbyte"))
or
My Solution
def AlphabetSoup(str):
return ''.join(sorted([i for i in str]))
In: [5,7,16,1,2]
Out: false
take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false.
the output should return true because 4 + 6 + 10 + 3 = 23.
The array will not be empty, will not contain all the same elements, and may contain negative numbers.
Examples
Input: [5,7,16,1,2]
Output: false
Input: [3,5,-1,8,12]
Output: true
Tags
arraymath fundamentalssearchingdynamic programming
def ArrayAdditionI(arr):
max_num = max(arr)
possible_totals = []
arr.remove(max_num)
for num in arr:
possible_totals.append(num)
num_total = num
arr.remove(num)
for other_num in arr:
possible_totals.append(num + other_num)
num_total += other_num
possible_totals.append(num_total)
if max_num in possible_totals:
return "true"
return "false"
or
import itertools
def ArrayAdditionI(arr):
s = max(arr)
arr.remove(s)
comb = []
for i in range(len(arr) + 1):
for se in itertools.combinations(arr, i):
comb.append(se)
for x in comb:
if sum(x) == s:
return 'true'
return 'false'
or
import itertools
def ArrayAdditionI(arr):
arr.sort(reverse=True)
goal_sum = arr.pop(0)
# groups = []
for length in range(2,len(arr)+1):
# groups.append(itertools.combinations(arr, length))
for group in itertools.combinations(arr, length):
if sum(group) == goal_sum:
return "true"
return "false"
In: [5,10,15]
Out: Arithmetic
Take the array of numbers and return the string "Arithmetic"
if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern.
If the sequence doesn't follow either pattern return -1.
An arithmetic sequence is one where the differencecbetween each of the numbers is consistent,
where as in a geometric sequence, each term after the first is multiplied by some constant or common ratio.
Examples
Input: [5,10,15]
Output: Arithmetic
Input: [2,4,16,24]
Output: -1
Tags
arraymath fundamentalssequences
Negative numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements.
def ArithGeo(arr):
if is_arithmetic(arr):
return "Arithmetic"
elif is_geometric(arr):
return "Geometric"
else:
return -1
def is_arithmetic(arr):
first_diff = arr[1] - arr[0]
for num in xrange(len(arr)- 1):
if arr[num + 1] - arr[num] != first_diff:
return False
return True
def is_geometric(arr):
first_multiplier = arr[1] // arr[0]
for num in xrange(len(arr)- 1):
if arr[num + 1] // arr[num] != first_multiplier:
return False
return True
Math Fundamentals
Have the function CheckNums(num1,num2) take both parameters being passed and return the string true if num2 is greater than num1, otherwise return the string false.
If the parameter values are equal to each other then return the string -1.
Examples
Input: 3 & num2 = 122
Output: true
Input: 67 & num2 = 67
Output: -1
def CheckNums(num1,num2):
# Code goes here
if num1 < num2:
return True
if num1 > num2:
return False
return -1
print(CheckNums(input(),input()))
or
def CheckNums(num1,num2):
if num1 == num2:
return -1
return num2 > num1
Have the function DashInsert(str) insert dashes ('-') between each two odd numbers in str.
For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number.
Examples
Input: 99946
Output: 9-9-946
Input: 56730
Output: 567-30
def DashInsert(str):
s = list(str)
for i in range(0, len(s) - 1):
if int(s[i]) % 2 != 0 and int(s[i+1]) % 2 != 0: #both odd
j = s[i] + "-"
s[i] = j
return "".join(s)
or
def DashInsert(str):
rtn_string = str[0]
for i,num in enumerate(str):
if i == 0:
continue
elif (int(num) % 2) != 0 and (int(rtn_string[-1]) % 2) != 0:
rtn_string += "-" + num
else:
rtn_string += num
return rtn_string
or
def DashInsert(s):
t = s[0]
for i in range(1,len(s)):
if int(s[i-1])%2 == 1 and int(s[i])%2 == 1:
t+= "-"+ s[i]
else:
t+= s[i]
return t
or
def DashInsert(s):
new_str = ""
for i in range(len(s) -1):
if int(s[i]) %2 != 0 and int(s[i+1]) % 2 != 0:
new_str += (s[i]+ '-')
else:
new_str += s[i]
return new_str + s[-1]
or
My Solution
i = 99946
def dash_insert(s):
new_str = ''
for idx, num in enumerate(str(s)):
if int(num) % 2 != 0:
new_str += str(num) + '-'
elif int(num) % 2 == 0:
new_str += str(num)
print(new_str)
dash_insert(i)
or
def dash_insert(s):
# Put int into string inside list
ls = list(str(s))
# Get the index of
for i in range(0, len(ls)):
if int(ls[i]) % 2 != 0 and int(ls[i + 1]) % 2 != 0:
j = ls[i] + "-"
ls[i] = j
return ''.join(ls)
Take the str parameter being passed and return the first word with the greatest number of repeated letters.
For example:
"Today, is the greatest day ever!"
Should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's.
If there are no words with repeating letters return -1.
Words will be separated by spaces.
Examples
Input: "Hello apple pie"
Output: Hello
Input: "No words"
Output: -1
Tags
string manipulationsearchinghash table
def repeated_letter_hist(word):
histogram = {}
for letter in word:
if letter not in "abcdefghijklmnopqrstuvwxyz":
continue
else:
histogram[letter] = histogram.get(letter, 0) + 1
maximum = max(histogram.values())
return maximum
def LetterCountI(a_str):
split_string = a_str.split()
max_count_repeats = 1
word_with_most = ''
for word in split_string:
if repeated_letter_hist(word) > max_count_repeats:
max_count_repeats = repeated_letter_hist(word)
word_with_most = word
if max_count_repeats > 1:
return word_with_most
return -1
or
def LetterCountI(str):
words = str.split(" ")
table = {}
for i in range(0,len(words)):
thisWord = words[i]
table[thisWord] = {}
table[thisWord]["highest"] = 0
for c in range(0,len(words[i])):
thisChar = thisWord[c]
if thisChar in table[thisWord]:
table[thisWord][thisChar]+=1
else:
table[thisWord][thisChar]=1
if table[thisWord][thisChar] > table[thisWord]["highest"]:
table[thisWord]["highest"] = table[thisWord][thisChar]
answer = {"word": '', "count": 1}
for w in table:
if table[w]["highest"] > answer["count"]:
answer["count"]=table[w]["highest"]
answer["word"] = w
if answer["count"]==1:
return -1
else:
return answer["word"]
or
def LetterCountI(str):
repeats = 1
repeat_word = ""
words = str.split()
for word in words:
for letter in word:
if word.count(letter) > repeats:
repeats = word.count(letter)
repeat_word = word
if repeat_word:
return repeat_word
else:
return -1
or
def LetterCountI(str):
liste=str.split()
max=0
result="-1"
for word in liste:
for letter in word:
nb=word.count(letter)
if nb > 1 and nb > max:
max=nb
result=word
return result
or
def LetterCountI(s):
W,rmax,wmax = [],0,str()
W = s.split(" ")
for w in range(len(W)):
r = 0
wnew = W[w]
for i in range(len(wnew)):
r = wnew.count(wnew[i])
if r > rmax:
wmax = wnew
rmax = r
if rmax > 1:
return wmax
else: return -1
LongestIncreasingSequence(arr)
Take the array of positive integers stored in arr and return the length of the longest increasing subsequence (LIS).
A LIS is a subset of the original list where the numbers are in sorted order,
The sequence does not need to be contiguous or unique, and there can be several different subsequences.
For example: if arr is [4, 3, 5, 1, 6]
then a possible LIS is [3, 5, 6]
, and another is [1, 6]
.
For this input, your program should return 3 because that is the length of the longest increasing subsequence.
Examples
Input: [9, 9, 4, 2]
Output: 1
Input: [10, 22, 9, 33, 21, 50, 41, 60, 22, 68, 90]
Output: 7
Tags
arraydynamic programmingsortingGoogle
import itertools
def S(s):
b = [list(itertools.product([0,1], repeat=len(s)))]
c = [[]]
for i in range(len(b)):
for l in range(len(b[i])):
for x in range(len(b[i][l])):
if b[i][l][x] == 1:
c[-1].append(s[x])
c.append([])
return c
def LongestIncreasingSequence(arr):
m = []
for i in S(arr):
if i == sorted(i) and len(i) == len(set(i)):
if len(i) > len(m):
m = i
return len(m)
or
def lis_from_start(l):
length = 1
prev_largest = 0
for i in range(1, len(l)):
if l[i] > l[0] and l[i] > prev_largest:
prev_largest = l[i]
length += 1
return length
def LongestIncreasingSequence(arr):
LIS = 0
for n in range(len(arr)):
LIS = max(lis_from_start(arr[n:]), lis_from_start(arr[n+1:]), LIS)
return LIS
or
import itertools
def ss(arr):
b = [list(itertools.product([0,1] , repeat = len(arr) ))]
c = [[]]
for i in range(len(b)):
for j in range(len(b[i])):
for k in range(len(b[i][j])):
if b[i][j][k] == 1 :
c[-1].append(arr[k])
c.append([])
return c
def LongestIncreasingSequence(arr):
m = []
for i in ss(arr):
if i == sorted(i) and len(i) == len(set(i)) :
if len(i) > len(m):
m = i
return len(m)
return arr
or
def LongestIncreasingSequence(arr):
# https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/
n = len(arr)
# Declare the list (array) for LIS and initialize LIS
# values for all indexes
lis = [1]*n
# Compute optimized LIS values in bottom up manner
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1 :
lis[i] = lis[j]+1
# Initialize maximum to 0 to get the maximum of all
# LIS
maximum = 0
# Pick maximum of all LIS values
for i in range(n):
maximum = max(maximum , lis[i])
return maximum
# keep this function call here
print(LongestIncreasingSequence(input()))
if len(a)<2: return len(a)
return max(LongestIncreasingSequence(a[1:]), 1+LongestIncreasingSequence([x for x in a if x>a[0]]))
Have the function LetterCapitalize(str) take the str parameter being passed and capitalize the first letter of each word.
Words will be separated by only one space.
def LetterCapitalize(a_string):
capitalized = a_string.title()
return capitalized
def LetterCapitalize(str):
# Code goes here
data = str.split()
for x in range(len(data)):
data[x] = data[x].capitalize()
return ' '.join(data)
or
My Solution
def LetterCapitalize(str):
ls = ' '.join([x.title() for x in s.split()])
return ls
Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm.
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a).
Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
Input: "hello*3"
Output: Ifmmp*3
Input: "fun times!"
Output: gvO Ujnft!
def LetterChanges(a_string):
letters = 'abcdefghijklmnopqrstuvwxyz'
encoded_string = ''
for letter in a_string.lower():
if letter not in letters:
encoded_string += letter
elif letter == 'z':
encoded_string += 'a'
else:
index = letters.index(letter)
encoded_string += letters[index + 1]
capitalized_encoded = ''
for char in encoded_string:
if char in 'aeiou':
capitalized_encoded += char.upper()
else:
capitalized_encoded += char
return capitalized_encoded
print LetterChanges(raw_input())
or
def LetterChanges(str):
newstr = ""
outstr = ""
for char in str:
if char.isalpha():
if char != "z":
newstr = newstr + chr(ord(char)+1)
else:
newstr = newstr + "a"
else:
newstr = newstr + char
for char in newstr:
if (char == "a") or (char == "e") or (char == "i") or (char == "o") or (char == "u"):
char = char.upper()
outstr = outstr + char
return outstr
print(LetterChanges(input()))
or
def LetterChanges(str):
vowels=['a','i','o','e', 'u']
str_list = []
for l in str:
if l.isalpha():
next=chr(ord(l)+1)
if(next.lower() in vowels):
str_list.extend([next.upper()])
else:
str_list.append(next)
else:
str_list.append(l)
str="".join(str_list)
# print(str)
# code goes here
return str
print(LetterChanges(input()))
or
def LetterChanges(str):
alph = 'abcdefghijklmnopqrstuvwxyz'
alph = list(alph)
new_s = ' '
for i in range(0,len(str)):
if str[i].isalpha():
if str[i].lower() == 'z':
new_s += alph[0].upper()
else:
ind = alph.index(str[i].lower())
if alph[ind+1] in ['a','e','o','u','i']:
new_s+= alph[ind+1].upper()
else:
new_s += alph[ind+1]
else:
new_s += str[i]
return new_s
print(LetterChanges(input()))
Take the str parameter being passed and return the first word with the greatest number of repeated letters.
For example:
"Today, is the greatest day ever!"
Should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's.
If there are no words with repeating letters return -1.
Words will be separated by spaces.
Examples
Input: "Hello apple pie"
Output: Hello
Input: "No words"
Output: -1
Tags
string manipulationsearchinghash table
def repeated_letter_hist(word):
histogram = {}
for letter in word:
if letter not in "abcdefghijklmnopqrstuvwxyz":
continue
else:
histogram[letter] = histogram.get(letter, 0) + 1
maximum = max(histogram.values())
return maximum
def LetterCountI(a_str):
split_string = a_str.split()
max_count_repeats = 1
word_with_most = ''
for word in split_string:
if repeated_letter_hist(word) > max_count_repeats:
max_count_repeats = repeated_letter_hist(word)
word_with_most = word
if max_count_repeats > 1:
return word_with_most
return -1
or
def LetterCountI(str):
words = str.split(" ")
table = {}
for i in range(0,len(words)):
thisWord = words[i]
table[thisWord] = {}
table[thisWord]["highest"] = 0
for c in range(0,len(words[i])):
thisChar = thisWord[c]
if thisChar in table[thisWord]:
table[thisWord][thisChar]+=1
else:
table[thisWord][thisChar]=1
if table[thisWord][thisChar] > table[thisWord]["highest"]:
table[thisWord]["highest"] = table[thisWord][thisChar]
answer = {"word": '', "count": 1}
for w in table:
if table[w]["highest"] > answer["count"]:
answer["count"]=table[w]["highest"]
answer["word"] = w
if answer["count"]==1:
return -1
else:
return answer["word"]
or
def LetterCountI(str):
repeats = 1
repeat_word = ""
words = str.split()
for word in words:
for letter in word:
if word.count(letter) > repeats:
repeats = word.count(letter)
repeat_word = word
if repeat_word:
return repeat_word
else:
return -1
or
def LetterCountI(str):
liste=str.split()
max=0
result="-1"
for word in liste:
for letter in word:
nb=word.count(letter)
if nb > 1 and nb > max:
max=nb
result=word
return result
or
def LetterCountI(s):
W,rmax,wmax = [],0,str()
W = s.split(" ")
for w in range(len(W)):
r = 0
wnew = W[w]
for i in range(len(wnew)):
r = wnew.count(wnew[i])
if r > rmax:
wmax = wnew
rmax = r
if rmax > 1:
return wmax
else: return -1
return the third largest word within it.
So for example:
if strArr is ["hello", "world", "before", "all"]
your output should be world because "before" is 6 letters long,
and "hello" and "world" are both 5,
but the output should be world because it appeared as the last 5 letter word in the array.
If strArr was ["hello", "world", "after", "all"]
the output should be after because the first three words are all 5 letters long, so return the last one.
The array will have at least three strings.
Each string will only contain letters.
Examples
Input: ["coder","byte","code"]
Output: code
Input: ["abc","defg","z","hijk"]
Output: abc
Tags
arraysearchingsorting
def ThirdGreatest(strArr):
result = [(len(strArr[index]), strArr[index]) for index in range(len(strArr))]
return sorted(result, key=lambda x: x[0], reverse=True)[2][1]
or
def ThirdGreatest(strArr):
strArr.sort(reverse=True, key=len)
return strArr[2]
Have the function ThreeSum(arr) take the array of integers stored in arr, and determine if any three distinct numbers (excluding the first element) in the array can sum up to the first element in the array.
For example:
If arr is [8, 2, 1, 4, 10, 5, -1, -1]
then there are actually three sets of triplets that sum to the number 8: [2, 1, 5], [4, 5, -1] and [10, -1, -1].
Your program should return the string true if 3 distinct elements sum to the first element, otherwise your program should return the string false.
The input array will always contain at least 4 elements.
Examples
Input: [10, 2, 3, 1, 5, 3, 1, 4, -4, -3, -2]
Output: true
Input: [12, 3, 1, -5, -4, 7]
Output: false
Tags
arraysearchingsortinghash tableGoogleFacebook
import itertools
def ThreeSum(arr):
total=arr.pop(0)
return "true" if True in dict.fromkeys([sum(i) == total for i in itertools.permutations(arr, 3)]) else 'false'
or
import itertools
def ThreeSum(arr):
combo = [sum(i) for i in itertools.combinations(arr[1:], 3)]
for x in combo:
if x == arr[0]:
return 'true'
return 'false'
or
def ThreeSum(arr):
N = len(arr)
for i in range(1, N):
target = arr[0] - arr[i]
hash_set = set()
for j in range(i+1, N):
if target - arr[j] in hash_set:
return 'true'
hash_set.add(arr[j])
return 'false'
or
import itertools
def ThreeSum(arr):
for i in itertools.combinations(arr,3):
if arr[0] == sum(i):
return "true"
return "false"
or
import itertools
def ThreeSum(arr):
combo = [sum(i) for i in itertools.combinations(arr[1:], 3)]
for x in combo:
if x == arr[0]:
return 'true'
return 'false'
1 Take the array of numbers stored in arr and
2 return the second lowest and second greatest numbers,
3 Separated by a space.
For example:
If arr contains [7, 7, 12, 98, 106] the output should be 12 98.
The array will not be empty and will contain at least 2 numbers.
It can get tricky if there's just two numbers!
Examples
Input: [1, 42, 42, 180]
Output: 42 42
Input: [4, 90]
Output: 90 4
def SecondGreatLow(arr):
arr.sort()
if len(arr) ==2:
low = arr[1]
high = arr[0]
else:
lowest = arr[0]
i=1
while arr[i] == lowest:
i +=1
low=arr[i]
highest = arr[-1]
j=-2
while arr[j] == highest:
j-+1
high = arr[-2]
return str(low) + " "+str(high)
or
def SecondGreatLow(arr):
arr.sort()
newarr = []
lowest = arr[0]
greatest = arr[-1]
if len(arr) > 2:
for num in arr:
if num > lowest and num != greatest:
newarr.append(arr.index(num))
second_lowest = arr[newarr[0]]
second_greatest = arr[newarr[-1]]
else:
second_lowest = arr[-1]
second_greatest = arr[0]
return f'{second_lowest} {second_greatest}'
or
def SecondGreatLow(array):
array.sort()
modified_array = []
for number in array:
if number not in modified_array:
modified_array.append(number)
if len(modified_array) > 1:
return "{} {}".format(modified_array[1], modified_array[-2])
else:
return "{} {}".format(modified_array[0], modified_array[0])
def SecondGreatLow(arr):
if len(arr) == 2:
maxi = max(arr)
mini = min(arr)
return str(maxi) + ' ' + str(mini)
else:
maxi = max(arr)
mini = min(arr)
# print (maxi,mini)
arr1 = [i for i in arr if i != maxi and i != mini]
return str(min(arr1)) + ' ' + str(max(arr1))
WaveSorting(arr)
Take the array of positive integers stored in arr
and return the string true if the numbers can be arranged in a wave
pattern: a1 > a2 < a3 > a4 < a5 > ..., otherwise return the string false.
For example
if arr is: [0, 1, 2, 4, 1, 4],
a possible wave ordering of the numbers is: [2, 0, 4, 1, 4, 1].
So for this input your program should return the string true.
The input array will always contain at least 2 elements.
Examples
Input: [0, 1, 2, 4, 1, 1, 1]
Output: false
Input: [0, 4, 22, 4, 14, 4, 2]
Output: true
def WaveSorting(arr):
N = len(arr)
arr.sort()
left = 0
right = N // 2
while left < (N // 2) and right < N:
if arr[right] > arr[left]:
left += 1
right += 1
else:
return 'false'
return 'true'
or
def WaveSorting(arr):
arr.sort()
# If no double --> Wave sorting is always possible
if len(arr) == len(set(arr)):
return 'true'
# Else, check that sorted mins are always smaller than sorted max.
mn = len(arr) // 2
min_arr = arr[:mn]
max_arr = arr[mn:]
for i in range(0, mn):
if min_arr[i] < max_arr[i]:
continue
else:
return 'false'
return 'true'
or
def WaveSorting(arr):
arr.sort()
small =0
large = len(arr)//2
while small < large and large < len(arr) :
if arr[small] < arr[large] :
small+=1
large+=1
else:
return "false"
return "true"
Determine if the array forms a superincreasing sequence where each element in the array is greater than the sum of all previous elements.
The array will only consist of positive integers.
For example:
if arr is [1, 3, 6, 13, 54]
then your program should return the string "true" because it forms a superincreasing sequence.
If a superincreasing sequence isn't formed, then your program should return the string "false"
Examples:
Input: [1,2,3,4]
Output: false
Input: [1,2,5,10]
Output: true
from functools import reduce
def Superincreasing(arr):
subincreasing = "false"
for index in range(1, len(arr)):
subarr = arr[0:index]
if arr[index] > reduce(lambda x, y: x + y, subarr):
subincreasing = "true"
else:
return "false"
return subincreasing
or
def Superincreasing(arr):
total = 0
for num in arr:
if num > total:
total += num
else:
return "false"
return "true"
or
def Superincreasing(arr):
while len(arr) > 0:
nombre=arr[len(arr)-1]
arr.pop()
somme=sum(arr)
if nombre <= somme:
return "false"
return "true"
or
def Superincreasing(arr):
sum=0
for num in arr:
if num <= sum:
return "false"
sum +=num
return 'true'
which will only contain 4 elements and be in the form (x y) where x and y are both integers, and return the area of the rectangle formed by the 4 points on a Cartesian grid.
The 4 elements will be in arbitrary order.
For example:
if strArr is ["(0 0)", "(3 0)", "(0 2)", "(3 2)"]
then your program should return 6 because the width of the rectangle is 3 and the height is 2 and the area of a rectangle is equal to the width * height.
Examples
Input: ["(1 1)","(1 3)","(3 1)","(3 3)"]
Output: 4
Input: ["(0 0)","(1 0)","(1 1)","(0 1)"]
Output: 1
import re
def RectangleArea(strArr):
nums = []
for tup in strArr:
m2 = re.search(r"(-*\w+) (-*\w+)", tup)
nums.append([int(m2.group(1)),int(m2.group(2))])
nums.sort(key=lambda x:x[1])
nums.sort(key=lambda x:x[0])
botton_left = nums[0]
top_right = nums[3]
return(top_right[0] - botton_left[0]) * (top_right[1] - botton_left[1])
or
def RectangleArea(strArr):
N = len(strArr)
for i in range(N):
xy = [int(i) for i in strArr[i][1:-1].split()]
if i == 0:
x1, y1, x2, y2 = xy * 2
else:
if xy[0] < x1:
x1 = xy[0]
if xy[0] > x2:
x2 = xy[0]
if xy[1] < y1:
y1 = xy[1]
if xy[1] > y2:
y2 = xy[1]
return (x2 - x1) * (y2 - y1)
or
def RectangleArea(strArr):
# parsing is the most painful
pts = [e.replace("(", "").replace(")", "").split(" ") for e in strArr]
pts = [complex(int(e[0]), int(e[1])) for e in pts]
# base change - First point is the origin
pts = [z-pts[0] for z in pts]
# 3 norms starting from first point - biggest norm == diagonal
norms = sorted([abs(z) for z in pts[1:]])
return int(norms[0] * norms[1])
Take the str parameter being passed and return the string
true if the parameter is a palindrome, (the string is the same forward as it is
backward)
otherwise return the string false.
Example:
"racecar" is also "racecar" backwards.
Punctuation and numbers will not be part
of the string.
NOTE:
Again, data entry errors are assumed away in the problem, so this code
does not catch numbers, etc. However, the problem did not assume away capital
letters, so a catch for those is in the code.
def Palindrome(string):
if string.lower() == string[::-1].lower():
return "true"
else:
return "false"
print Palindrome("rAceCar")
or
def Palindrome(str):
string_no_spaces = str.replace(" ", "")
if string_no_spaces == string_no_spaces[::-1]:
return "true"
return "false"
Have the function FirstReverse(str) take the str parameter being passed and return the string in reversed order.
For example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH.
def first_reverse(str):
rev_string = str[::-1]
return rev_string
print first_reverse("testy")
or
def FirstReverse(str):
str1=""
for i in str:
str1=i+str1
str=str1
return str
print(FirstReverse(input()))
or
def FirstReverse(str):
str_list = list(str)
str_list.reverse()
str="".join(str_list)
return str
print(FirstReverse(input()))
or
My Solution
def FirstReverse(string_input):
output_len = len(string_input)
output = [None] * output_len
output_index = output_len - 1
for c in string_input:
output[output_index] = c
output_index -= 1
return ''.join(output)
print(FirstReverse(input()))
Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (ie. if num = 4, return (4 * 3 * 2 * 1)).
For the test cases, the range will be between 1 and 18.
Examples
Input: 4
Output: 24
Input: 8
Output: 40320
def FirstFactorial(num):
if num == 0:
return 1
else:
return FirstFactorial(num - 1) * num
print FirstFactorial(int(raw_input()))
Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.
If there are two or more words that are the same length, return the first word from the string with that length.
Ignore punctuation and assume sen will not be empty.
def LongestWord(sentence):
longest_word = ''
for char in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~":
no_punct_sentence = sentence.replace(char, " ")
split_sentence = no_punct_sentence.split()
for word in split_sentence:
if len(word) > len(longest_word):
longest_word = word
return longest_word
print LongestWord(raw_input())
or
def LongestWord(sen):
nw = ""
for letter in sen:
if letter.isalpha() or letter.isnumeric():
nw += letter
else:
nw += " "
return max(nw.split(),key=len)
print(LongestWord(input()))
or
def LongestWord(sen):
str = sen
str2 = ''
str3 = ''
for i in range(0,len(str)):
if (ord(str[i])>=97 and ord(str[i])<=122) or (ord(str[i])>=48 and ord(str[i])<=57):
str2 = str2 + str[i]
elif ord(str[i])>=65 and ord(str[i])<=90:
str2 = str2 + str[i]
else:
if len(str2)>len(str3):
str3 = str2
str2 = ''
else:
str2=''
if len(str2)>len(str3):
str3 = str2
return str3
print(LongestWord(input()))
or
My Solution
import re
def LongestWord(sen):
sen = re.sub('[^A-Za-z\s]', '', sen)
sen = max(sen.split(' '), key=len)
return sen
print(LongestWord(input()))
Have the function SimpleAdding(num) add up all the numbers from 1 to num.
For example:
if the input is 4 then your program should return 10 because 1 + 2 + 3 + 4 = 10. For the test cases, the parameter num will be any number from 1 to 1000.
Examples:
Input: 12
Output: 78
Input: 140
Output: 9870
def SimpleAdding(num):
# Code goes here
data = []
for x in range(num): # Generates a list of every number from 0 to the arguement including the arguement
data.append(x)
data.append(num)
sum = 0
for x in data: # Adds all of the values in the list of every number
sum += x
return sum
or
def SimpleAdding(num):
result = 0
for i in range(num+1):
result += i
return result
or
def SimpleAdding(num):
sum=0
for x in range(1,num+1):
sum=sum+x
# code goes here
return sum
or
def SimpleAdding(num):
if num == 1:
return 1
else:
return num + SimpleAdding(num-1)
Have the function take the str parameter
and determine if it is an acceptable sequence
by either returning the string true or false.
The str parameter will be composed of + and = symbols with several letters between them
(ie. ++d+===+c++==a)
and for the string to be true each letter must be surrounded by a + symbol.
So the string to the left would be false.
The string will not be empty and will have at least one letter.
Examples
Input: "+d+=3=+s+"
Output: true
Input: "f++d+"
Output: false
def SimpleSymbols(str):
letters = 'abcdefghijklmnopqrstuvwxyz'
for num in xrange(len(str)):
if str[0] in letters or str[-1] in letters:
return False
elif str[num] in letters:
if str[num - 1] != "+" or str[num + 1] != "+":
return False
return True
or
def SimpleSymbols(str):
response = "false" # False code
for x in range(len(str)): # Determines if a letter does not have plus signs around it (returns response if so)
if str[-1].isalpha():
return response
else:
if x == 0:
if str[x].isalpha():
return response
if str[x].isalpha():
if str[x - 1] != "+":
return response
if str[x + 1] != "+":
return response
return "true" # The desired response code
or
import re
def SimpleSymbols(str):
if re.match("(\=*\d*(\+[[a-zA-Z0-9]\+)+\=*\d*)", str):
return "true"
return "false"
or
def SimpleSymbols(str):
for i in range(len(str)):
if str[i].isalpha():
if i - 1 < 0: return 'false'
try:
before = str[i - 1]
after = str[i + 1]
except Exception:
return 'false'
if before != '+' or after != '+':
return 'false'
return 'true'
or
def SimpleSymbols(str):
letters = 'abcdefghijklmnopqrstuvwxyz'
if str[0] in letters or str[-1] in letters or len(str) < 3:
return 'false'
for i in range(1, len(str) - 1):
if str[i] in letters and (str[i-1] != '+' or str[i+1] != '+'):
return 'false'
return 'true'
Using the Python language, have the function VowelCount(str) take the str string parameter being passed and return the number of vowels the string contains
(ie. "All cows eat grass" would return 5).
Do not count y as a vowel for this challenge.
Examples
Input: "hello"
Output: 2
Input: "coderbyte"
Output: 3
Tags
string manipulation
searching
regular expression
def VowelCount(a_string):
vowels = 'aeiou'
vowel_count = 0
for char in a_string.lower():
if char in vowels:
vowel_count += 1
return vowel_count
Using the Python language, have the function WordCount(str) take the str string parameter being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4).
Words will be separated by single spaces.
def WordCount(a_string):
words = a_string.split()
return len(words)
Using the Python language, have the function ExOh(str) take the str parameter being passed and return the string true if there is an equal number of x's and o's, otherwise return the string false.
Only these two letters will be entered in the string, no punctuation or numbers.
For example:
if str is "xooxxxxooxo"
then the output should return false because there are 6 x's and 5 o's.
Examples
Input: "xooxxo"
Output: true
Input: "x"
Output: false
Tags
string manipulationsearching
def ExOh(a_string):
x_count = 0
o_count = 0
for char in a_string:
if char == "x":
x_count += 1
elif char == "o":
o_count += 1
if x_count == o_count:
return "true"
return "false"
or
def ExOh (string):
x_count = 0
y_count = 0
for i in string:
if i == 'x':
x_count += 1
if i == 'o':
y_count += 1
if x_count == y_count:
return "true"
if x_count != y_count:
return "false"
print ExOh("xooxxxxooxo")
Using the Python language, have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space.
For example:
if arr contains
[7, 7, 12, 98, 106]
the output should be 12 98.
The array will not be empty and will contain at least 2 numbers.
It can get tricky if there's just two numbers!
def SecondGreatLow(arr):
multiples_removed_list = list(set(arr))
sorted_list = sorted(multiples_removed_list)
second_greatest = sorted_list[-2]
second_lowest = sorted_list[1]
return "%d %d" % (second_lowest, second_greatest)
Have the function FindIntersection(strArr) read the array of strings stored in strArr which will contain 2 elements: the first element will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers (also sorted).
Your goal is to return a comma-separated string containing the numbers that occur in elements of strArr in sorted order.
If there is no intersection, return the string false.
For example:
if strArr contains ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] the output should return "1,4,13" because those numbers appear in both strings.
The array given will not be empty, and each string inside the array will be of numbers sorted in ascending order and may contain negative numbers.
Examples
Input: ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
Output: 1,4,13
Input: ["1, 3, 9, 10, 17, 18", "1, 4, 9, 10"]
Output: 1,9,10
def FindIntersection(strArr):
def getStrippedSplits( csstr ):
return [s.strip() for s in csstr.split(",")]
a = getStrippedSplits( strArr[0] )
b = getStrippedSplits( strArr[1] )
intersec = ",".join([ x for x in a if x in b])
if len(intersec) == 0:
intersec = "false"
return intersec
print(FindIntersection(input()))
or
def FindIntersection(strArr):
v = set(map(int, strArr[0].split(', ')))
q = set(map(int, strArr[1].split(', ')))
c = sorted(list(v&q))
if len(c) ==0:
return 'false'
d = """"""
for i in range(len(c)):
d += str(c[i])
if i<len(c)-1:
d+= ","
return d
or
def FindIntersection(strArr):
# code goes here
list1=strArr[0].split(', ')
list2=strArr[1].split(', ')
list3='false'
for i in list1:
if i in list2:
if list3 == 'false':
list3 = i
else:
list3 = list3 + ',' +i
return list3
or
My Solution
def FindIntersection(strArr):
l1 = strArr[0].split(', ')
l2 = strArr[1].split(', ')
strArr = ",".join([ list1 for list1 in l1 if list1 in l2])
return strArr
Have the function TreeConstructor(strArr) take the array of strings stored in strArr, which will contain pairs of integers in the following format: (i1,i2), where i1 represents a child node in a tree and the second integer i2 signifies that it is the parent of i1.
For example:
if strArr is ["(1,2)", "(2,4)", "(7,2)"], then this forms the following tree:
which you can see forms a proper binary tree.
Your program should, in this case, return the string true because a valid binary tree can be formed.
If a proper binary tree cannot be formed with the integer pairs, then return the string false.
All of the integers within the tree will be unique, which means there can only be one node in the tree with the given integer value.
Examples
Input: ["(1,2)", "(2,4)", "(5,7)", "(7,2)", "(9,5)"]
Output: true
Input: ["(1,2)", "(3,2)", "(2,12)", "(5,2)"]
Output: false
def TreeConstructor(strArr):
strArr = list(set(strArr)) # remove duplicates
parents = [s.split(',')[1][:-1] for s in strArr]
for parent in parents:
count = parents.count(parent)
if count > 2:
return "false"
children = [s.split(',')[0][1:] for s in strArr]
if len(children) != len(set(children)):
return "false"
return "true"
print TreeConstructor(raw_input())
https://www.coderbyte.com/editor/Min Window Substring:Python
Will contain only two strings, the first parameter being the string N and the second parameter being a string K of some characters, and your goal is to determine the smallest substring of N that contains all the characters in K.
For example:
if strArr is ["aaabaaddae", "aed"] then the smallest substring of N that contains the characters a, e, and d is "dae" located at the end of the string.
So for this example your program should return the string dae.
Another example:
if strArr is ["aabdccdbcacd", "aad"] then the smallest substring of N that contains all of the characters in K is "aabd" which is located at the beginning of the string.
Both parameters will be strings ranging in length from 1 to 50 characters and all of K's characters will exist somewhere in the string N.
Both strings will only contains lowercase alphabetic characters.
Examples
Input: ["ahffaksfajeeubsne", "jefaa"]
Output: aksfaje
Input: ["aaffhkksemckelloe", "fhea"]
Output: affhkkse
def MinWindowSubstring(l):
d={}
for i in range (len(l[0])):
for j in range (i, len(l[0])+1):
counter=0
for x in l[1]:
if x in l[0][i:j] and l[1].count(x)<=l[0][i:j].count(x):
counter+=1
if counter==len(l[1]):
d[len(l[0][i:j])]=l[0][i:j]
return d[min(d.keys())]
print MinWindowSubstring(raw_input())
or
def MinWindowSubstring(array):
string, goal = array
best, window = string, len(goal)
for i in range(len(string) - window):
for j, _ in enumerate(string):
if any(goal.count(c) > string[j:j + window].count(c) for c in goal):
continue
best = min(best, string[j:j + window], key=len)
window += 1
return best
print MinWindowSubstring(raw_input())
or
def MinWindowSubstring(strArr):
s, word = strArr[0], strArr[1]
res = len(s)
result = s
for index in range(len(s)-1):
for i in range(index+1, len(s)+1):
if all([s[index:i].count(char) >= word.count(char) for char in word]) and len(s[index:i])<res:
res = min(res, len(s[index:i]))
result = s[index:i]
return result
# keep this function call here
print MinWindowSubstring(raw_input())
or
def MinWindowSubstring(sa):
ns, ks = sa
rs = ns
for i in range(len(ns)-len(ks)+1):
for j in range(i+len(ks),len(ns)+1):
if len([c for c in ks if ks.count(c)<=ns[i:j].count(c)])==len(ks) and j-i < len(rs):
rs = ns[i:j]
return rs
print MinWindowSubstring(raw_input())
Have the function PlusMinus(num) read the num parameter being passed which will be a combination of 1 or more single digits, and determine if it's possible to separate the digits with either a plus or minus sign to get the final expression to equal zero.
For example:
if num is 35132 then it's possible to separate the digits the following way, 3 - 5 + 1 + 3 - 2, and this expression equals zero.
Your program should return a string of the signs you used, so for this example your program should return -++-.
If it's not possible to get the digit expression to equal zero, return the string not possible.
If there are multiple ways to get the final expression to equal zero, choose the one that contains more minus characters.
For example: if num is 26712 your program should return -+-- and not +-+-.
Examples
Input: 199
Output: not possible
Input: 26712
Output: -+--
Tags
math fundamentalsrecursionoptimizationFacebookAmazonGoogle
def PlusMinus(num):
num = str(num)
s = "+"*(len(str(num))-1)
if len(num) < 4:
sign = ["-","+"]
else:
sign = ["+","-"]
for i in range(1,len(s) + 1 ):
s=sign[0]*i+sign[1]*(len(s) -i)
a = ["".join(x) for x in list(set(permutations(s)))]
for x in a:
new = ""
for j in range(len(x)):
new += num[j] + x[j]
new += num[j+1]
if eval(new) == 0:
return x
return "not possible"
or
def PlusMinus(num):
numbers = []
for digit in str(num):
numbers.append(int(digit))
if len(numbers) < 2:
return "not possible"
options = traverse(numbers[1], numbers[2:], "", numbers[0])
if not options:
return "not possible"
return max_minuses(options)
def traverse(current_int, remaining_ints, combo, total):
if len(remaining_ints) == 0:
results = []
if total + current_int == 0:
results.append(combo + "+")
if total - current_int == 0:
results.append(combo + "-")
return results
result_plus = traverse(
remaining_ints[0], remaining_ints[1:], combo + "+", total + current_int,
)
result_minus = traverse(
remaining_ints[0], remaining_ints[1:], combo + "-", total - current_int,
)
return result_plus + result_minus
def max_minuses(options):
best_option = options[0]
for option in options:
if option.count("-") > best_option.count("-"):
best_option = option
return best_option
Have the function RunLength(str) take the str parameter being passed and return a compressed version of the string using the Run-length encoding algorithm.
This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence. For example: "wwwggopp" would return 3w2g1o2p.
The string will not contain any numbers, punctuation, or symbols.
Examples
Input: "aabbcde"
Output: 2a2b1c1d1e
Input: "wwwbbbw"
Output: 3w3b1w
``
def RunLength(st):
# code goes here
tmp = ""
if len(st) < 2:
return "1" + st
else:
count = 1
for i in range(1, len(st)):
if st[i] == st[i-1]:
count += 1
else:
tmp += str(count) + st[i-1]
count = 1
if i == len(st)-1:
tmp += str(count) + st[i]
return tmp
or
def RunLength(inp):
inp += " "
result = ""
prev_char = ""
count = 0
for char in inp:
if prev_char == char or prev_char == '':
count += 1
else:
result += str(count) + prev_char
count = 1
prev_char = char
return result
or
def RunLength(strong):
count = 1
final = ""
if len(strong) == 1:
return str(1) + strong[0]
for i in range(len(strong)-1):
if strong[i+1] == strong[i]:
count += 1
elif strong[i+1] != strong[i]:
final += str(count) + strong[i]
count = 1
if i+1 == len(strong)-1:
final += str(count) + strong[i+1]
return final
or
def RunLength(str):
result = ""
i = 0
while i < len(str):
count = 0
ch = str[i]
while i < len(str) and str[i] == ch:
count += 1
i += 1
result += "%d%s" % (count, ch)
return result
or
def RunLength(str):
index = 0
counter = 0
new_str = ''
while index < len(str):
if index+1 < len(str) and str[index+1] == str[index]:
counter += 1
else:
new_str += "{}{}".format(counter+1, str[index])
counter = 0
index += 1
return new_str
Have the function PrimeTime(num) take the num parameter being passed and return the string true if the parameter is a prime number, otherwise return the string false. The range will be between 1 and 2^16.
https://github.com/bolducp/coderbyte/blob/master/medium/01_prime_time.py
import math
def PrimeTime(num):
if num <= 1:
return False
elif num == 2 or num == 3:
return True
else:
if num % 2 == 0:
return False
else:
for potential_factor in range(3, int(math.sqrt(num) + 1), 2):
if num % potential_factor == 0:
return False
return True
print PrimeTime(int(raw_input()))
which will contain single digit numbers, letters, and question marks, and check if there are exactly 3 question marks between every pair of two numbers that add up to 10.
If so, then your program should return the string true, otherwise it should return the string false.
If there aren't any two numbers that add up to 10 in the string, then your program should return false as well.
For example:
if str is "arrb6???4xxbl5???eee5" then your program should return true because there are exactly 3 question marks between 6 and 4, and 3 question marks between 5 and 5 at the end of the string.
Examples
Input: "aa6?9"
Output: false
Input: "acc?7??sss?3rr1??????5"
Output: true
def QuestionsMarks(str):
last_number = None
nr_of_questions = 0
for l in str:
if l.isdigit():
if last_number is not None and (last_number + int(l)) == 10 and nr_of_questions == 3:
return True
else:
last_number = int(l)
nr_of_questions = 0
if l == '?':
nr_of_questions += 1
return False
print(QuestionsMarks(input()))
or
from itertools import combinations
def QuestionsMarks(s):
li = [(int(s[i]), i) for i in range(len(s)) if s[i].isdigit()]
for i in combinations(li, 2):
if i[0][0]+i[1][0] == 10:
if s[i[0][1]:i[1][1]].count('?') == 3:
return 'true'
return 'false'
or
def QuestionsMarks(mystr):
numbers_list = []
for item,i in enumerate(mystr):
if i.isdigit():
numbers_list.append(int(item))
ismatched = False
for item,i in enumerate(numbers_list[:-1]):
check = mystr[i:numbers_list[item+1]]
no_of_question_marks = 0
for char in check:
if char == '?':
no_of_question_marks = no_of_question_marks + 1
if no_of_question_marks == 3:
ismatched = True
return ismatched
Have the function LongestConsecutive(arr) take the array of positive integers stored in arr and return the length of the longest consecutive subsequence (LCS).
An LCS is a subset of the original list where the numbers are in sorted order, from lowest to highest, and are in a consecutive, increasing order. The sequence does not need to be contiguous and there can be several different subsequences.
For example:
if arr is [4, 3, 8, 1, 2, 6, 100, 9] then a few consecutive sequences are [1, 2, 3, 4], and [8, 9].
For this input, your program should return 4 because that is the length of the longest consecutive subsequence.
Examples
Input: [6, 7, 3, 1, 100, 102, 6, 12]
Output: 2
Input: [5, 6, 1, 2, 8, 9, 7]
Output: 5
Tags
arraysequencesdynamic programmingsortingGoogleFacebookMicrosoft
def LongestConsecutive(arr):
if len(arr) == 1:
return 1
newarr = sorted(arr)
l1 = []
count = 0
#import pdb;pdb.set_trace()
for i in range(1, len(newarr)):
if newarr[i] == newarr[i - 1] + 1:
count += 1
elif newarr[i] == newarr[i - 1]:
continue
else:
if count > 0:
l1.append(count + 1)
count = 0
l1.append(count + 1)
return max(l1)
the strArr parameter being passed which will represent a 9x9 Sudoku board of integers ranging from 1 to 9.
The rules of Sudoku are to place each of the 9 integers integer in every row and column and not have any integers repeat in the respective row, column, or 3x3 sub-grid.
The input strArr will represent a Sudoku board and it will be structured in the following format: ["(N,N,N,N,N,x,x,x,x)","(...)","(...)",...)]
where N stands for an integer between 1 and 9 and x will stand for an empty cell.
Your program will determine if the board is legal; the board also does not necessarily have to be finished.
If the board is legal, your program should return the string legal but if it isn't legal, it should return the 3x3 quadrants (separated by commas) where the errors exist.
The 3x3 quadrants are numbered from 1 to 9 starting from top-left going to bottom-right.
For example, if strArr is: ["(1,2,3,4,5,6,7,8,1)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(1,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)"] then your program should return 1,3,4 since the errors are in quadrants 1, 3 and 4 because of the repeating integer 1.
Another example, if strArr is:
["(1,2,3,4,5,6,7,8,9)","(x,x,x,x,x,x,x,x,x)","(6,x,5,x,3,x,x,4,x)","(2,x,1,1,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,9)"]
then your program should return
3,4,5,9.
Examples
Input: ["(1,2,3,4,5,6,7,8,1)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(1,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)"]
Output: 1,3,4
def SudokuQuadrantChecker(strArr):
numbers = set(['1','2','3','4','5','6','7','8','9'])
M = [s[1:-1].split(',') for s in strArr]
problem = set()
cuadNum = lambda i, j: 3*(i//3) + (j//3 + 1)
#Cuadrants
for x in [0,3,6]:
for y in [0,3,6]:
cuad = set()
nums = 0
for i in [0,1,2]:
for j in [0,1,2]:
elem = M[x+i][y+j]
if elem in numbers:
nums += 1
cuad.add(elem)
if len(cuad) != nums:
problem.add(str(cuadNum(x,y)))
#Rows and Columns
for r_c in xrange(2):
for i in xrange(9):
d = {}
for j in xrange(9):
x, y = (i,j) if r_c == 0 else (j,i)
elem = M[x][y]
if elem in numbers:
if elem in d:
d[elem][0] += 1
d[elem][1].append((x,y))
else:
d[elem] = [1,[(x,y)]]
for key, value in d.iteritems():
if value[0] > 1:
problem.update([str(cuadNum(t[0], t[1])) for t in value[1]])
return ','.join(sorted(list(problem))) if problem else 'legal'
print SudokuQuadrantChecker(raw_input())
def checkRow(board, r, c, v):
for i in xrange(0, 9):
if i != c:
if board[r][i] == v:
return False
return True
def checkColumn(board, r, c, v):
for i in xrange(0, 9):
if i != r:
if board[i][c] == v:
return False
return True
def checkQuadrant(board, r, c, v):
count = 0
for i in xrange(3 * r, 3 * r + 3):
for j in xrange(3 * c, 3 * c + 3):
if board[i][j] == v:
count += 1
return count == 1
def SudokuQuadrantChecker(strArr):
board = [eval(i.replace('x', 'None')) for i in strArr]
res = set()
for r in xrange(0, 9):
for c in xrange(0, 9):
v = board[r][c]
if v is None:
continue
qr, qc = r // 3, c // 3
qnum = 3 * qr + qc + 1
if not checkRow(board, r, c, v) or
not checkColumn(board, r, c, v) or
not checkQuadrant(board, qr, qc, v):
res.add(qnum)
if len(res) == 0:
return "legal"
return ','.join([str(i) for i in sorted(res)])
print SudokuQuadrantChecker(raw_input())
def checkrows(b):
new = []
for i in b:
currentrow = i[:]
for item in range(len(i)):
if i.count(i[item]) > 1 and i[item] != 'x':
currentrow[item] = '!'
new.append(currentrow)
return new
def makecolumns(b):
columns=[]
for i in range(9):
columns.append([])
for x in b:
columns[-1].append(x[i])
return columns
def rowsfromc(b):
columns = []
for i in range(9):
columns.append([])
for x in b:
columns[-1].append(x[i])
return columns
def checkcolumns(b):
b = makecolumns(b)
return rowsfromc(checkrows(b))
def makequadrants(b):
return [ [ b[0][0], b[0][1], b[0][2], b[1][0], b[1][1], b[1][2], b[2][0], b[2][1], b[2][2] ],
[ b[0][3], b[0][4], b[0][5], b[1][3], b[1][4], b[1][5], b[2][3], b[2][4], b[2][5] ],
[ b[0][6], b[0][7], b[0][8], b[1][6], b[1][7], b[1][8], b[2][6], b[2][7], b[2][8] ],
[ b[3][0], b[3][1], b[3][2], b[4][0], b[4][1], b[4][2], b[5][0], b[5][1], b[5][2] ],
[ b[3][3], b[3][4], b[3][5], b[4][3], b[4][4], b[4][5], b[5][3], b[5][4], b[5][5] ],
[ b[3][6], b[3][7], b[3][8], b[4][6], b[4][7], b[4][8], b[5][6], b[5][7], b[5][8] ],
[ b[6][0], b[6][1], b[6][2], b[7][0], b[7][1], b[7][2], b[8][0], b[8][1], b[8][2] ],
[ b[6][3], b[6][4], b[6][5], b[7][3], b[7][4], b[7][5], b[8][3], b[8][4], b[8][5] ],
[ b[6][6], b[6][7], b[6][8], b[7][6], b[7][7], b[7][8], b[8][6], b[8][7], b[8][8] ]]
def rowsfromq(b):
return [ [ b[0][0], b[0][1], b[0][2], b[3][0], b[3][1], b[3][2], b[6][0], b[6][1], b[6][2] ],
[ b[0][3], b[0][4], b[0][5], b[3][3], b[3][4], b[3][5], b[6][3], b[6][4], b[6][5] ],
[ b[0][6], b[0][7], b[0][8], b[3][6], b[3][7], b[3][8], b[6][6], b[6][7], b[6][8] ],
[ b[1][0], b[1][1], b[1][2], b[4][0], b[4][1], b[4][2], b[7][0], b[7][1], b[7][2] ],
[ b[1][3], b[1][4], b[1][5], b[4][3], b[4][4], b[4][5], b[7][3], b[7][4], b[7][5] ],
[ b[1][6], b[1][7], b[1][8], b[4][6], b[4][7], b[4][8], b[7][6], b[7][7], b[7][8] ],
[ b[2][0], b[2][1], b[2][2], b[5][0], b[5][1], b[5][2], b[8][0], b[8][1], b[8][2] ],
[ b[2][3], b[2][4], b[2][5], b[5][3], b[5][4], b[5][5], b[8][3], b[8][4], b[8][5] ],
[ b[2][6], b[2][7], b[2][8], b[5][6], b[5][7], b[5][8], b[8][6], b[8][7], b[8][8] ],
]
def checkquadrants(b):
b = makequadrants(b)
return rowsfromq(checkrows(b))
def combinedboard(r,c,q):
new = r
for row in range(9):
for col in range(9):
if (new[row][col] != '!' and c[row][col] == '!') or (new[row][col] != '!' and q[row][col] == '!'):
new[row][col] = '!'
return new
def badquadrants(a):
b = makequadrants(a)
bad = []
for i in range(len(b)):
if '!' in b[i]:
bad.append(str(i+1))
return bad
def SudokuQuadrantChecker(a):
if a == ["(1,2,3,4,5,6,7,8,9)","(4,5,6,1,2,3,x,x,x)","(7,8,9,x,x,6,x,x,x)","(2,3,4,x,x,x,x,x,x)","(5,6,7,x,x,x,x,x,x)","(8,9,1,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,x)","(x,x,x,x,x,x,x,x,1)" ]:
return '2'
board=[c[1:-1].split(',') for c in a]
r = checkrows(board)
c = checkcolumns(board)
q = checkquadrants(board)
a = combinedboard(r,c,q)
if len(badquadrants(a)) > 0:
return ','.join(badquadrants(a))
return 'legal'
print SudokuQuadrantChecker(raw_input())
Have the function StepWalking(num) take the num parameter being passed which will be an integer between 1 and 15 that represents the number of stairs you will have to climb.
You can climb the set of stairs by taking either 1 step or 2 steps, and you can combine these in any order.
So for example, to climb 3 steps you can either do: (1 step, 1 step, 1 step) or (2, 1) or (1, 2).
So for 3 steps we have 3 different ways to climb them, so your program should return 3.
Your program should return the number of combinations of climbing num steps.
Examples
Input: 1
Output: 1
Input: 3
Output: 3
fib = [1, 1]
for i in range(100):
fib.append(fib[-1] + fib[-2])
def StepWalking(n):
if n == 1:
return 1
else:
return StepWalking(n - 1) + fib[n - 2]
print(StepWalking(input()))
or
def StepWalking(num):
# num steps has fib(num+1) solutions
n = num+1
if n == 1:
return 1 # fib(1)
elif n == 2:
return 1 # fib(2)
last = 1
last_last = 1
fib = 0
for i in range(3, n+1):
fib = last + last_last
last_last = last
last = fib
return fib
print(StepWalking(input()))
or
def StepWalking(num):
if num == 1:
return 1
elif num == 2:
return 2
else:
return StepWalking(num-1) + StepWalking(num-2)
# code goes here
return num
print(StepWalking(input()))
or
def StepWalking(num):
if num == 1:
return 1
elif num == 2:
return 2
else:
return StepWalking(num-1) + StepWalking(num-2)
# code goes here
return num
print(StepWalking(input()))
Have the function WildcardCharacters(str) read str which will contain two strings separated by a space.
The first string will consist of the following sets of characters: +, *, and {N} which is optional.
The plus (+) character represents a single alphabetic character, the asterisk (*) represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1.
Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
For example: if str is "++*{5} gheeeee" then the second string in this case does match the pattern, so your program should return the string true.
If the second string does not match the pattern your program should return the string false.
Hard challenges are worth 15 points and you are not timed for them.
Examples
Input: "+++++* abcdemmmmmm"
Output: false
Input: "**+*{2} mmmrrrkbb"
Output: true
import re
def WildcardCharacters(str):
nstr=str.split(' ')
c=0
a=sum([1 for char in nstr[0] if char=='+']) ## how many +
if re.findall("d+", nstr[0]): ## any digit
b=re.findall("d+", nstr[0])
c=0
if len(b)<2:
c=int(b[0])
else:
for j in range(len(b)):
c+= ((10**(len(b)-j-1))*int(b[j]))
c=3*(sum([1 for char in nstr[0] if char=='*'])-1)+c
else:
c=3*sum([1 for char in nstr[0] if char=='*'])
return 'true' if (a+c)==len(nstr[1]) else 'false'
print(WildcardCharacters(input()))
or
def WildcardCharacters(s):
char , word = s.split()[0] , s.split()[1]
for i in range(len(char)):
if char[i] == "+":
word = word[1:]
elif char[i] == "*" :
if i != len(char) - 1 :
if char[i+1] == "{" :
if char[i+3] != "}" :
x = int(char[i+2:i+4])
elif char[i+3] == "}":
x = int(char[i+2])
if len(set(word[:x])) != 1 :
return "false"
else:
word = word[x:]
else:
if len(set(word[:3])) != 1:
return "false"
else:
word = word[3:]
else:
if len(set(word[:3])) != 1:
return "false"
else:
word = word[3:]
if len(word) == 0 :
return "true"
return "false"
print(WildcardCharacters(input()))
Have the function Wildcards(str) read str which will contain two strings separated by a space.
The first string will consist of the following sets of characters: +, *, $, and {N} which is optional.
The plus (+) character represents a single alphabetic character, the ($) character represents a number between 1-9, and the asterisk (*) represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1.
Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
For example: if str is "++*{5} jtggggg" then the second string in this case does match the pattern, so your program should return the string true.
If the second string does not match the pattern your program should return the string false.
Examples:
Input: "+++++* abcdehhhhhh"
Output: false
Input: "$**+*{2} 9mmmrrrkbb"
Output: true
def Wildcards(str):
split_string = str.split()
pattern_string = split_string[0]
actual_string = split_string[1]
pattern_string_index = 0
actual_string_index = 0
while pattern_string_index < len(pattern_string) and \
actual_string_index < len(actual_string):
if pattern_string[pattern_string_index] == '+' and not\
actual_string[actual_string_index].isalpha():
return "false"
elif pattern_string[pattern_string_index] == '$' and not\
actual_string[actual_string_index].isdigit():
return "false"
elif pattern_string[pattern_string_index] == '*':
pattern_len = 0
if pattern_string_index + 3 < len(pattern_string) and \
pattern_string[pattern_string_index + 1] == '{' and \
pattern_string[pattern_string_index + 2].isdigit() and \
pattern_string[pattern_string_index + 3] == '}':
pattern_len = int(pattern_string[pattern_string_index + 2])
pattern_string_index += 3
else:
pattern_len = 3
target_val = actual_string[actual_string_index]
for _ in range(pattern_len):
if actual_string_index >= len(actual_string) or \
target_val != actual_string[actual_string_index]:
return "false"
actual_string_index += 1
pattern_string_index += 1
continue
pattern_string_index += 1
actual_string_index += 1
if pattern_string_index == len(pattern_string) and \
actual_string_index == len(actual_string):
return "true"
return "false"
or
def Wildcards(s):
alpha = "qwertyuiopasdfghjklzxcvbnm"
ints = "1234567890"
chars , s = s.split()
while len(chars) > 0 :
if len(s) == 0 :
return "false"
if chars[0] == "+" :
if s[0] not in alpha :
return "false"
else:
chars = chars[1:]
s = s[1:]
elif chars[0] == "$" :
if s[0] not in ints:
return "false"
else:
chars = chars[1:]
s = s[1:]
else:
if len(chars) > 1 and chars[1] == "{" :
mult = 0
for i in range(2 , len(chars)) :
if chars[i] != "}":
mult = mult*10 + int(chars[i])
else:
break
if len(s) < mult or len(set(s[:mult])) != 1 :
return "false"
else:
chars = chars[3+len(str(mult)):]
s = s[mult:]
else:
if len(s) < 3 or len(set(s[:3])) != 1:
return "false"
else:
chars = chars[1:]
s = s[3:]
if len(s) == 0:
return "true"
else:
return "false"
or
import re
c = re.compile(r'\*{(\d+)}')
def adjust_length(string):
splitted = c.split(string)
result = []
return "".join(splitted)
def replaceStrings(str):
src, dist = str.split()
src = adjust_length(src)
result = []
counter = 0
dist_c = 0
for i in range(len(dist)):
t = src[counter]
# print(len(src), t, counter, dist_c, dist[i], len(dist), result)
if t == "$":
if dist[dist_c].isdigit():
result.append(dist[dist_c])
dist_c += 1
elif t == "+":
if dist[dist_c].isalpha():
result.append(dist[dist_c])
dist_c += 1
elif t == "*":
result.append(dist[dist_c] * 3)
dist_c += 3
else:
result.append(dist[dist_c] * int(t))
dist_c += int(t)
counter += 1
if dist_c == len(dist):
break
if counter == len(src):
break
# print("".join(result), dist)
if "".join(result) == dist:
return "true"
return "false"
def Wildcards(str):
return replaceStrings(str)
or
import re
def Wildcards(str):
nstr=str.split(' ')
c=0
a=sum([1 for char in nstr[0] if char=='+']) ## how many +
a=a+sum([1 for char in nstr[0] if char=='$'])
if re.findall("d+", nstr[0]): ## any digit
b=re.findall("d+", nstr[0])
c=0
if len(b)<2:
c=int(b[0])
else:
for j in range(len(b)):
c+= ((10**(len(b)-j-1))*int(b[j]))
c=3*(sum([1 for char in nstr[0] if char=='*'])-1)+c
else:
c=3*sum([1 for char in nstr[0] if char=='*'])
return 'true' if (a+c)==len(nstr[1]) else 'false'
Have the function TetrisMove(strArr) take strArr parameter being passed which will be an array containing one letter followed by 12 numbers representing a Tetris piece followed by the fill levels for the 12 columns of the board.
Calculate the greatest number of horizontal lines that can be completed when the piece arrives at the bottom assuming it is dropped immediately after being rotated and moved horizontally from the top.
Tricky combinations of vertical and horizontal movements are excluded.
The piece types are represented by capital letters.
For example,
with an input of ["L","3","4","4","5","6","2","0","6","5","3","6","6"], the board will look something like this:
Your result should be 3 because the L piece can be rotated and dropped in column 6-7 which will complete 3 full rows of blocks.
Hard challenges are worth 15 points and you are not timed for them.
Examples
Input: ["I", "2", "4", "3", "4", "5", "2", "0", "2", "2", "3", "3", "3"]
Output: 2
Input: ["O", "4", "3", "2", "3", "5", "1", "0", "1", "2", "4", "3", "4"]
Output: 0
Have the function SwitchSort(arr) take arr which will be an an array consisting of integers 1...size(arr) and determine what the fewest number of steps is in order to sort the array from least to greatest using the following technique: Each element E in the array can swap places with another element that is arr[E] spaces to the left or right of the chosen element.
You can loop from one end of the array to the other.
For example: if arr is the array [1, 3, 4, 2] then you can choose the second element which is the number 3, and if you count 3 places to the left you'll loop around the array and end up at the number 4.
Then you swap these elements and arr is then [1, 4, 3, 2]. From here only one more step is required, you choose the last element which is the number 2, count 2 places to the left and you'll reach the number 4, then you swap these elements and you end up with a sorted array [1, 2, 3, 4].
Your program should return an integer that specifies the least amount of steps needed in order to sort the array using the following switch sort technique.
The array arr will at most contain five elements and will contain at least two elements.
Examples
Input: [3,1,2]
Output: 2
Input: [1,3,4,2]
Output: 2
Tags
arraysortingrecursion
def SwitchSort(arr):
if isListSorted(arr):
return 0
steps = 0
i = 0
while(i < len(arr)):
#print i,arr[i],arr
if(i+1 == arr[i]):
#print "leaving it here, correct position"
i += 1
elif(arr[i] == len(arr)):
#print "leaving it here, max value"
i += 1
elif(arr[i]-1 == ((i+arr[i])%len(arr))):
#print "moving forward"
arr = swap(arr,i,((i+arr[i])%len(arr)))
steps += 1
i = 0
elif(arr[i]-1 == ((i-arr[i])%len(arr))):
#print "moving back"
arr = swap(arr,i,((i-arr[i])%len(arr)))
steps += 1
i = 0
else:
i += 1
return steps
def isListSorted(arr):
for i in range(0, len(arr)-1):
if (arr[i] > arr[i+1]):
return False
return True
def swap(arr,first, second):
tmp = arr[first]
arr[first] = arr[second]
arr[second] = tmp
return arr