I have a string and a number. I need to find the first sub-string that contain the same characters with the length of the number - numbers

For example:
number= 3
my_string= "gghhsstttevvv"
The output:
"ttt"
*if the number was 2, the output is: "gg"

The below script will give you the desired output :
number = input("Enter Number")
string = input("Enter String")
count = dict.fromkeys(string,0)
for i in string:
count[i] += 1
#print(count)
occurences = count.values()
#print(occurences)
result = [k for k,v in count.items() if v == int(number)]
if not result:
print("No matching substring of length " +number+ " found")
else:
print(result) # To print all the characters with the given count
print(result[0]) # To print the first character with the given count
output_char = result[0]
frequency = count[output_char]
output_char = output_char*frequency
print(output_char)
Output:
python3 string.py
Enter Number5
Enter Stringgghhsstttevvv
No matching substring of length 5 found
python3 string.py
Enter Number3
Enter Stringgghhsstttevvv
['t', 'v']
t
ttt

Related

I'm having trouble with the code where the budget variable wasn't deducting throughout the loop. It instead do nothing or sometimes add up

enter image description hereI'm making an inventory system code and I'm a bit stuck finding a solution to the substraction problem, when I choose "ADD" and entering the input the formula wasn't getting the accurate outcome. For example, if I input Paper001 then its quantity, the output is fine at first but when input another item, the deduction instead becoming addition or sometimes doesn't do anything.
I tried dividing the values in the dictionary in 3 conditions but it turns out even worse.
while True:
try:
bg = float(input("Enter your budget : "))
print("-----------------------------------------------------------")
print(" Item name Item code Item price(Per set) \n")
print("1.Bond Paper : Paper001 100 PHP\n2.Yellow Paper : Paper002 50 PHP\n3.Intermediate Paper : Paper003 20 PHP\n\n")
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break
a ={"name":[], "quant":[], "price":[]}
# converting dictionary to list for further updation
b = list(a.values())
# variable na value of "name" from dictionary 'a'
na = b[0]
# variable qu value of "quant" from dictionary 'a'
qu = b[1]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed else continue asking options
while True:
try:
print("-----------------------------------------------------------")
ch = int(input("1.ADD\n2.STORAGE LIST\n3.Customer purchase\n4.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given option")
continue
else:
# check the budget is greater than zero and option selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
pn = input("Enter item code : ")
if pn in p_list.keys():
q = int(input("Enter quantity : "))
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
#checks if item name is already in the list
if pn in na:
ind = na.index(pn)
# remove quantity from "quant" index of the product
qu.remove(qu[ind])
# new value will be added to the previous value of user's quantity
qu.insert(ind, q)
tpr = (q+q)*p_list[pn]
print(f" Total product price:",tpr)
s = bg-tpr
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
# as na = b[0] it will append all the value in the
# list eg: "name"🙁"rice"]
qu.append(q)
# after appending new value the sum in price
# as to be calculated
tpr = q*p_list[pn]
print("\nTotal product price:",tpr)
s = bg-tpr
if s==0:
print("No more budget left")
print("\nAmount left :", s)
elif s>0:
print("\nAmount left :", s)
else:
print("Insufficient budget. Cannot buy item.")
print("Please restart and re-enter your budget.")
break
elif ch ==2 :
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
continue
elif ch == 3:
print("-----------------------------------------------------------")
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
co = input("\nEnter customer's order : ")
if co in p_list.keys():
q = int(input("Enter quantity : "))
sl = qu[i]-q
print("Item is sold!")
print("Stocks left :",sl)
if sl <=0:
print("Please add new items!")
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
elif ch==4:
print("")
print("\nThank your for shopping with us!")
break
elif s==0:
print("NO BUDGET LEFT. UNABLE TO ADD ITEMS.")
else:
print("ERROR: Choose only the digits given from the option.")

How to remove a single number from a list with multiples of that number

As I'm a beginner in coding I wanted to try to find the first three repeated numbers in a list. My problem is that in my code when there is a number repeated three, the code breaks.
The usual, remove, pop, and del, don't work as they delete one element in the list.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
final_numbers.append(myList[loop])
else:
myList.pop(loop)
myList.pop (loop-1)
number = 0
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
the expected result should be at the first three repeated numbers.
I added some print statements so you can go through your program and find out where the logic is wrong with your code.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
print( 'inside while loop: loop = {}'.format( loop ))
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
print( 'in -> if myList[loop] == myList[loop-1]' )
final_numbers.append(myList[loop])
print( 'final_numbers: [{}]'.format( ','.join( final_numbers )))
else:
print( 'in first -> else' )
myList.pop(loop)
myList.pop (loop-1)
number = 0
print( 'myList: [{}]'.format( ','.join( myList ) ))
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
print( 'returning final numbers' )
print( final_numbers )
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
print( 'at end of this loop final numbers is: [{}]'.format( ','.join( final_numbers)))
print( 'press any key to continue loop: ')
input()
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
Following is a method to do it taking advantage of pythons defaultdict
https://docs.python.org/2/library/collections.html#collections.defaultdict
#import defaultdict to keep track of number counts
from collections import defaultdict
#changed parameter name since you are passing in a string, not a list
def first_repeat( numbers_string ):
#create a dictionary - defaulddict( int ) is a dictionary with keys
#instantiated to 0 - (instead of throwing a key error)
number_count = defaultdict( int )
#convert your string to a list of integers - look up list iterations
numbers = [ int( s ) for s in list( numbers )]
# to store the repeated numbers
first_three_repeats = []
for number in numbers:
# for each number in the list, increment when it is seen
number_count[number] += 1
#at first occurence of 3 numbers, return the number
if number_count[number] == 2:
first_three_repeats.append( number )
if len( first_three_repeats ) == 3:
return first_three_repeats
#if here - not three occurrences of repeated numbers
return []
for n in range(20):
string = string+str(r(0,9))
print( findFirstThreeNumbers( string ))

find out min and max in python 3

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)

Difficulty getting readLine() to work as desired on HackerRank

I'm attempting to submit the HackerRank Day 6 Challenge for 30 Days of Code.
I'm able to complete the task without issue in an Xcode Playground, however HackerRank's site says there is no output from my method. I encountered an issue yesterday due to browser flakiness, but cleaning caches, switching from Safari to Chrome, etc. don't seem to resolve the issue I'm encountering here. I think my problem lies in inputString.
Task
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).
Input Format
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String, .
Constraints
1 <= T <= 10
2 <= length of S < 10,000
Output Format
For each String (where 0 <= j <= T-1), print S's even-indexed characters, followed by a space, followed by S's odd-indexed characters.
This is the code I'm submitting:
import Foundation
let inputString = readLine()!
func tweakString(string: String) {
// split string into an array of lines based on char set
var lineArray = string.components(separatedBy: .newlines)
// extract the number of test cases
let testCases = Int(lineArray[0])
// remove the first line containing the number of unit tests
lineArray.remove(at: 0)
/*
Satisfy constraints specified in the task
*/
guard lineArray.count >= 1 && lineArray.count <= 10 && testCases == lineArray.count else { return }
for line in lineArray {
switch line.characters.count {
// to match constraint specified in the task
case 2...10000:
let characterArray = Array(line.characters)
let evenCharacters = characterArray.enumerated().filter({$0.0 % 2 == 0}).map({$0.1})
let oddCharacters = characterArray.enumerated().filter({$0.0 % 2 == 1}).map({$0.1})
print(String(evenCharacters) + " " + String(oddCharacters))
default:
break
}
}
}
tweakString(string: inputString)
I think my issue lies the inputString. I'm taking it "as-is" and formatting it within my method. I've found solutions for Day 6, but I can't seem to find any current ones in Swift.
Thank you for reading. I welcome thoughts on how to get this thing to pass.
readLine() reads a single line from standard input, which
means that your inputString contains only the first line from
the input data. You have to call readLine() in a loop to get
the remaining input data.
So your program could look like this:
func tweakString(string: String) -> String {
// For a single input string, compute the output string according to the challenge rules ...
return result
}
let N = Int(readLine()!)! // Number of test cases
// For each test case:
for _ in 1...N {
let input = readLine()!
let output = tweakString(string: input)
print(output)
}
(The forced unwraps are acceptable here because the format of
the input data is documented in the challenge description.)
Hi Adrian you should call readLine()! every row . Here an example answer for that challenge;
import Foundation
func letsReview(str:String){
var evenCharacters = ""
var oddCharacters = ""
var index = 0
for char in str.characters{
if index % 2 == 0 {
evenCharacters += String(char)
}
else{
oddCharacters += String(char)
}
index += 1
}
print (evenCharacters + " " + oddCharacters)
}
let rowCount = Int(readLine()!)!
for _ in 0..<rowCount {
letsReview(str:String(readLine()!)!)
}

Add spacing between digits and non digits

Hi guys I have a probelm that I needed to solve. Here are the examples:
input is ABCD12345 will output ABCD 12345
input is A12345BCDE will output A 12345 BCDE
imput is ABC 12345 will output ABC 12345 (excess spacing removed)
As shown above a single spacing shall be added when there are no spacing but if there is, it will check if there are double spaces, then it will make it into single spacing.
To accomplish what you ask you can do something like this:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var res = ""
var lastDigit = false
for char in [input].unicodeScalars {
if letters.longCharacterIsMember(char.value) && lastDigit {
res += " "
lastDigit = false
} else if digits.longCharacterIsMember(char.value) && !lastDigit {
res += " "
lastDigit = true
}
if String(char) != " " {
res += String(char)
}
}
print(res)
In the code above you should replace the [input] placeholder with the input that you want to deal and the result string will be in res variable.