Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Have an assignment where I must sort a list of names and then display it. Then have the user input one of the names and searches the array and displays the ordered number in the array. I pretty much have everything done but I cannot get that part to work.
If I type in one of the names, it just returns the same name but doesn't give me the ordered number in the index. How can the code be changed so it correctly displays the number of the name that is input into the program?
def main():
SIZE = 10
names = ['Ross Harrison', 'Hannah Beauregard', 'Bob White', 'Ava Fisher', 'Chris Rich', 'Xavier Adams', 'Sasha Ricci', 'Danielle Porter', 'Gordon Pike', 'Matt Hoyle']
searchName = str()
index = int()
selectionSort(names, SIZE)
print('Sorted order:')
for index in range (0, SIZE):
print(names[index])
searchName = input('Enter a name to search for: ')
index = binarySearch(names, searchName, SIZE)
if index != -1:
print('The ordered number of this name is ' + str(names[index]))
else:
print(searchName + 'was not found.')
def selectionSort(array, arraySize):
startScan = int(); minIndex = int(); minValue = int(); index = int()
for startScan in range (0, arraySize - 1):
minIndex = startScan
minValue = array[startScan]
for index in range (startScan + 1, arraySize):
if array[index] < minValue:
minValue = array[index]
minIndex = index
array[minIndex] = array[startScan]
array[startScan] = minValue
def binarySearch(array, value, arraySize):
position = -1
first = 0
last = arraySize - 1
found = False
middle = int()
while not found and first <= last:
middle = int((first + last) / 2)
if array[middle] == value :
found = True
position = middle
elif array[middle] > value:
last = middle - 1
else:
first = middle + 1
return position
main()
I think you have a simple, one-line change.
You get the name instead of the index, because that's exactly what you told it to print. Instead, use this:
print('The index of this name is ', index)
Your original went to the extra trouble to look up the name in that location.
Related
Let's say you have a list which only has two types of values and goes something like ['t','r','r','r','t','t','r','r','t'] and you want to find the length of the smallest sequence number of 'r's which have 't's at both ends.
In this case the smallest sequence of 'r' has a length of 2, because there is first t,r,r,r,t and then t,r,r,t, and the latter has the smallest number of 'r's in a row surrounded by 't' and the number of 'r's is 2.
How would I code for finding that number?
This is from a problem of trying of going to a play with your friend, and you want to sit as close as possible with your friend, so you are trying to find the smallest amount of taken seats in between two free seats at a play. "#" is a taken seat and a "." is a free seat. you are given the amount of seats, and the seating arrangement (free seats and taken seats), and they are all in one line.
An example of an input is:
5
#.##.
where there are two taken seats(##) in between two free seats.
Here is my code which is not working for inputs that I don't know, but working for inputs I throw at it.
import sys
seats = int(input())
configuration = input()
seatsArray = []
betweenSeats = 1
betweenSeatsMin = 1
checked = 0
theArray = []
dotCount = 0
for i in configuration:
seatsArray.append(i)
for i in range(len(seatsArray)):
if i == len(seatsArray) - 1:
break
if seatsArray[i] == "." and seatsArray[i+1] == ".":
print(0)
sys.exit()
for i in range(0,len(seatsArray)):
if i > 0:
if checked == seats:
break
checked += 1
if seatsArray[i] == "#":
if i > 0:
if seatsArray[i-1] == "#":
betweenSeats += 1
if seatsArray[i] == ".":
dotCount += 1
if dotCount > 1:
theArray.append(betweenSeats)
betweenSeats = 1
theArray = sorted(theArray)
if theArray.count(1) > 0:
theArray.remove(1)
theArray = list(dict.fromkeys(theArray))
print(theArray[0])
This is a noob and a !optimal approach to your problem using a counter for the minimum and maximum sequence where ew compare both and return the minimum.
''' create a funciton that
will find min sequence
of target char
in a list'''
def finder(a, target):
max_counter = 0
min_counter = 0
''' iterate through our list
and if the element is the target
increase our max counter by 1
'''
for i in x:
if i == target:
max_counter += 1
'''min here is 0
so it will always be less
so we overwrite it's value
with the value of max_counter'''
if min_counter < max_counter:
min_counter = max_counter
'''at last iteration max counter will be less than min counter
so we overwrite it'''
if max_counter < min_counter:
min_counter = max_counter
else:
max_counter = 0
return min_counter
x = ['t','r','r','r','t','t','r','r','t','t','t','r','t']
y = 'r'
print(finder(x,y))
Create a string from list and then search for pattern required and then count r in the found matches and then take min of it
Code:
import re
lst = ['t','r','r','r','t','t','r','r','t']
text = ''.join(lst)
pattern = '(?<=t)r+(?=t)'
smallest_r_seq = min(match.group().count('r') for match in re.finditer(pattern, text))
print(smallest_r_seq)
Output:
2
I am trying to generate combination of ID's
Input: cid = SPARK
oupout: list of all the comibnations as below, position of each element should be constant. I am a beginner in python any help here is much appreciated.
'S****'
'S***K'
'S**R*'
'S**RK'
'S*A**'
'S*A*K'
'S*AR*'
'S*ARK'
'SP***'
'SP**K'
'SP*R*'
'SP*RK'
'SPA**'
'SPA*K'
'SPAR*'
'SPARK'
I tried below, I need a dynamic code:
cid = 'SPARK'
# print(cid.replace(cid[1],'*'))
# cu_len = lenth of cid [SPARK] here which is 5
# com_stars = how many stars i.e '*' or '**'
def cubiod_combo_gen(cu_len, com_stars, j_ite, i_ite):
cubiodList = []
crange = cu_len
i = i_ite #2 #3
j = j_ite #1
# com_stars = ['*','**','***','****']
while( i <= crange):
# print(j,i)
if len(com_stars) == 1:
x = len(com_stars)
n_cid = cid.replace(cid[j:i],com_stars)
i += x
j += x
cubiodList.append(n_cid)
elif len(com_stars) == 2:
x = len(com_stars)
n_cid = cid.replace(cid[j:i],com_stars)
i += x
j += x
cubiodList.append(n_cid)
elif len(com_stars) == 3:
x = len(com_stars)
n_cid = cid.replace(cid[j:i],com_stars)
i += x
j += x
cubiodList.append(n_cid)
return cubiodList
#print(i)
#print(n_cid)
# for item in cubiodList:
# print(item)
print(cubiod_combo_gen(5,'*',1,2))
print(cubiod_combo_gen(5,'**',1,3))
For every character in your given string, you can represent it as a binary string, using a 1 for a character that stays the same and a 0 for a character to replace with an asterisk.
def cubiod_combo_gen(string, count_star):
str_list = [char0 for char0 in string] # a list with the characters of the string
itercount = 2 ** (len(str_list)) # 2 to the power of the length of the input string
results = []
for config in range(itercount):
# return a string of i in binary representation
binary_repr = bin(config)[2:]
while len(binary_repr) < len(str_list):
binary_repr = '0' + binary_repr # add padding
# construct a list with asterisks
i = -1
result_list = str_list.copy() # soft copy, this made me spend like 10 minutes debugging lol
for char in binary_repr:
i += 1
if char == '0':
result_list[i] = '*'
if char == '1':
result_list[i] = str_list[i]
# now we have a possible string value
if result_list.count('*') == count_star:
# convert back to string and add to list of accepted strings
result = ''
for i in result_list:
result = result + i
results.append(result)
return results
# this function returns the value, so you have to use `print(cubiod_combo_gen(args))`
# comment this stuff out if you don't want an interactive user prompt
string = input('Enter a string : ')
count_star = input('Enter number of stars : ')
print(cubiod_combo_gen(string, int(count_star)))
It iterates through 16 characters in about 4 seconds and 18 characters in about 17 seconds. Also you made a typo on "cuboid" but I left the original spelling
Enter a string : DPSCT
Enter number of stars : 2
['**SCT', '*P*CT', '*PS*T', '*PSC*', 'D**CT', 'D*S*T', 'D*SC*', 'DP**T', 'DP*C*', 'DPS**']
As a side effect of this binary counting, the list is ordered by the asterisks, where the earliest asterisk takes precedence, with next earliest asterisks breaking ties.
If you want a cumulative count like 1, 4, 5, and 6 asterisks from for example "ABCDEFG", you can use something like
star_counts = (1, 4, 5, 6)
string = 'ABCDEFG'
for i in star_counts:
print(cubiod_combo_gen(string, star_counts))
If you want the nice formatting you have in your answer, try adding this block at the end of your code:
def formatted_cuboid(string, count_star):
values = cubiod_combo_gen(string, count_star)
for i in values:
print(values[i])
I honestly do not know what your j_ite and i_ite are, but it seems like they have no use so this should work. If you still want to pass these arguments, change the first line to def cubiod_combo_gen(string, count_star, *args, **kwargs):
I am not sure what com_stars does, but to produce your sample output, the following code does.
def cuboid_combo(cid):
fill_len = len(cid)-1
items = []
for i in range(2 ** fill_len):
binary = f'{i:0{fill_len}b}'
#print(binary, 'binary', 'num', i)
s = cid[0]
for idx, bit in enumerate(binary,start=1):
if bit == '0':
s += '*'
else: # 'bit' == 1
s += cid[idx]
items.append(s)
return items
#cid = 'ABCDEFGHI'
cid = 'DPSCT'
result = cuboid_combo(cid)
for item in result:
print(item)
Prints:
D****
D***T
D**C*
D**CT
D*S**
D*S*T
D*SC*
D*SCT
DP***
DP**T
DP*C*
DP*CT
DPS**
DPS*T
DPSC*
DPSCT
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is for the Third Problem on Google's Codejam Qualification Round 2020
The Judging System says this solution gives a wrong answer, but I could not figure out why. Any insights would be much appreciated.
num_test_cases = int(input())
def notOverlap(activity, arr):
# returns true if we have no overlapping activity in arr
for act in arr:
if not (act[0] >= activity[1] or act[1] <= activity[0]):
return False
return True
def decide(act, num_act):
C, J = [], []
result = [None]*num_act
for i in range(num_act):
if notOverlap(act[i], C):
C.append(act[i])
result[i] = "C"
elif notOverlap(act[i], J):
J.append(act[i])
result[i] = "J"
else:
return "IMPOSSIBLE"
return "".join(result)
for i in range(num_test_cases):
num_act = int(input())
act = []
for _ in range(num_act):
act.append(list(map(int, input().split())))
print("Case #" + str(i+1) + ": " + decide(act, num_act))
You implemented a brute force way to solve it. Your code runs slow, Time complexity O(N^2), but you can do it in O(N*log(N))
Instead of check with notOverlap(activity, arr), sort the array and check with the last ending time activity of C or J. ( Greedy Way to solve it )
You have to store the index of activity before sorting the array.
Here is my solution, but before reading the solution try to implement it yourself
for testcasei in range(1, 1 + int(input())):
n = int(input())
acts = []
for index in range(n):
start, end = map(int, input().split())
acts.append((start, end, index)) # store also the index
acts.sort(reverse=True) # sort by starting time reversed
# so the first activity go to the last
d = ['']*n # construct the array for the answer
cnow = jnow = 0 # next time C or J are available
impossible = False # not impossible for now
while acts: # while there is an activity
start_time, end_time, index = acts.pop()
if cnow <= start_time: # C is available to do the activity
cnow = end_time
d[index] = 'C'
elif jnow <= start_time:
jnow = end_time
d[index] = 'J'
else: # both are'nt available
impossible = True
break
if impossible:
d = 'IMPOSSIBLE'
else:
d = ''.join(d) # convert the array to string
print("Case #%d: %s" % (testcasei, d))
I hope you find this informative and helped you to understand, and keep the hard work.
Here is the prompt:
On the first line display the first, last and middle element of the list separated by the , character.
I have been trying to get this figured out for a few hours now, but do not know the correct process to return the middle of the array. Here is my code so far:
primary = []
length = 0
i = ("MORE")
while i != "NOMORE":
i = str(input("?"))
print(i)
if i == "NOMORE":
break
primary.append(i)
length = length + 1
mid = (length/2)
print(primary[0]," , ", primary[-1]," , ",primary.pop([mid]))
The code works to get the correct inputs from the program, but as the lists will be variable lengths I assume some form of a loop will be used. The primary.pop([mid]) was my poor attempt at getting the median printed. I know that the mid will not be printed as it is the wrong variable type, but how would I replace this?
Any help is appreciated.
You're unnecessarily calling the pop() method on primary with [mid] when you should simply be indexing primary with mid. You should also use the // operator instead of / to obtain an integer value for the index. Since the index is 0-based, the mid point should be (length - 1) // 2 instead:
primary = []
length = 0
i = ("MORE")
while i != "NOMORE":
i = str(input("?"))
print(i)
if i == "NOMORE":
break
primary.append(i)
length = length + 1
mid = (length - 1) // 2
print(primary[0]," , ", primary[-1]," , ",primary[mid])
There is a question.
How do i print a pattern like this
stackoverflow
stackoverflo
tackoverflo
tackoverfl
ackoverfl
ackoverf
ckoverf
ckover
kover
kove
ove
ov
v
I have tried to use for loops but failed...
str = "stackoverflow"
k = len(str)
print(str)
print(str[:(k-1)])
And I don't know how to use for loops to finish it
Are there any ways without using for loops to address this problem?
Thanks...
Another possible solution is
s = "stackoverflow"
toggle = True # If true, remove first char. Else, cut last char.
left = 0 # number of spaces to prepend
right = 0 # number of spaces to append
while s: # while s is not empty
print(' '*left + s + ' '*right)
if toggle:
s = s[1:] # remove first char
left += 1
else:
s = s[:-1] # remove last char
right += 1
toggle = not toggle
which gives output
stackoverflow
tackoverflow
tackoverflo
ackoverflo
ackoverfl
ckoverfl
ckoverf
koverf
kover
over
ove
ve
v
I suggest using a for loop. They're pretty easy to use once you get used to them. Here's a solution that uses a for loop:
def show(s):
n = len(s)
for i in range(n):
n1 = i // 2
n2 = i - n1
print(" " * n1 + s[n1:n-n2])
s = "stackoverflow"
show(s)
The output is:
stackoverflow
stackoverflo
tackoverflo
tackoverfl
ackoverfl
ackoverf
ckoverf
ckover
kover
kove
ove
ov
v
If you really don't want to use a for loop, you can replace it with a while loop as follows:
i = 0
while i < n:
...
i += 1
Keep track of two index l and r that represent the slice of string to print. Then shorten that slice on each iteration.
s = 'stackoverflow'
l, r = 0, len(s) # range of string to print
remove_left = True # which side of the string to remove
space = 0 # how much space to print to the left
while l < r:
print('%s%s' % (' ' * int(space/2), s[l:r]))
if remove_left:
r-= 1
else:
l+= 1
remove_left = not remove_left
space += 1
Output:
stackoverflow
stackoverflo
tackoverflo
tackoverfl
ackoverfl
ackoverf
ckoverf
ckover
kover
kove
ove
ov
v
You can use the concept of recursion
def stackoverflow(pattern,alternate=0):
if len(pattern) == 1:
#base condition for recursion
return
elif alternate == 0:
#first time execution
print(pattern)
alternate = alternate + 1
stackoverflow(pattern, alternate)
elif alternate % 2 != 0:
# truncate from right side
pattern = pattern[:-1]
print(pattern)
alternate = alternate + 1
stackoverflow(pattern, alternate)
else:
#truncate from left side
pattern = pattern[1:]
print(pattern)
alternate = alternate + 1
stackoverflow(pattern,alternate)
Well you could use 'some_string'.rjust(width, ' ') where width is an integer value and the second parameter is a string in my example used a blank space. Also you can use 'some_string'.ljust(width, ' '). For more information you should check this site https://www.programiz.com/python-programming/methods/string/rjust
for example:
def word_reduce(word):
n = word.__len__()
for i in range(n):
left = i // 2
right = i - left
result = word[left:n-right]
print((' ').rjust(left + 1) + result)
s = 'stackoverflow'
word_reduce(s)
You could try this with only one counter
string = "stackoverflow"
loop=0
while string.replace(' ','')!='':
print(' '*(loop//2)+string+' '*(loop//2))
if loop%2==0:
string=string[:-1]
else:
string=string[1:]
loop=loop+1
You can use just simple slice operator :
a='stackoverflow'
print(a)
#printing first whole string
for i in range(len(a)):
#loop range of the string
if i%2==0:
#here the logic see the problem you will find a pattern that it removing
#last character when loop number is even and update the string with current
#sliced string
#print(i)
# if you want use this print for understanding track of slicing
print('{:^12s}'.format(a[:-1]))
#Removing last character if loop index is even
a=a[:-1]
#update the string with current sliced string
else:
#print(i)
#use this print for tracking of sliced string
print('{:^14s}'.format(a[1:]))
#remove first character if loop index is not even or loop index is odd.
a=a[1:]
#update the current string with sliced string
output:
stackoverflow
stackoverflo
tackoverflo
tackoverfl
ackoverfl
ackoverf
ckoverf
ckover
kover
kove
ove
ov
v
As OP stated that no loops. Does hardcoding count as valid answer?
print(“stackoverflow”)
print(“stackoverflo”)
print(“ tackoverflo”)
print(“ tackoverfl”)
print(“ ackoverfl”)
print(“ ackoverf”)
print(“ ckoverf”)
print(“ ckover”)
print(“ kover)
print(“ kove”)
print(“ ove”)
print(“ ov”)
print(“ v”)
Here is another way with recursive function printline(). For loop not needed.
# Recursive function
def printline(string, cutleft, padindex):
# Print out the required line
print(string.rjust(padindex+len(string)))
# Last character to print out
if len(string) == 1:
return
# Deciding to trim the left or right part of the string
if cutleft:
printline(string[1:], 0, padindex + 1)
else:
printline(string[:-1], 1, padindex)
# Calling the recursive function with initial value
printline('stackoverflow', 0, 0)
This is the output.
stackoverflow
stackoverflo
tackoverflo
tackoverfl
ackoverfl
ackoverf
ckoverf
ckover
kover
kove
ove
ov
v