text
stringlengths
37
1.41M
number = raw_input("Type a number --> ") print "If you add all the integers between 1 to", number, "you get.."
while True: prompt = raw_input ("Type the word Girls Who Code\n--->") if prompt == "Girls Who Code": print "Good Job!" break if prompt != "Girls Who Code": print "That's not right try something else"
colors = ["red", "yellow", "green", "blue"] i = 0 while i < len(colors): print "When I was %d, my favorite color was %s" % (i, colors[i]) i = i + 1
while True: print "Type in a month's and learn how many days it has." month = raw_input() if month.lower() == "january": print "31" elif month.lower() == "february": print "28" elif month.lower() == "march": print "31" elif month.lower() == "april": print "30" elif month.lower() == "may": print "31" elif month.lower() == "june": print "30" elif month.lower() == "july": print "31" elif month.lower() == "august": print "31" elif month.lower() == "september": print "29" elif month.lower() == "october": print "31" elif month.lower() == "november": print "30" elif month.lower() == "december": print "31!" else: print "Type a month"
"""Func""" def func(): """Call center""" price = int(input()) minutes = int(input()) second = int(input()) if price == 0: print("free") else: if second > 30: minutes += 1 second = 0 if minutes*60 <= 120: print("free") else: if minutes <= 15: print(15 * price) else: print(minutes * price) func()
"""Func""" def checkremoved(removedscore): """Check for real score""" if removedscore < -10: realscore = 0 else: realscore = 10 + removedscore if removedscore == 0: removedscore = "-0" else: removedscore = str(removedscore) return [removedscore, realscore] def func(): """Help teacher check""" teacher = input() student = input() arr1 = [] arr2 = [] removedscore = 0 arrans = "" for i in range(len(teacher)): arr1 += teacher[i] arr2 += student[i] found = False for i in range(len(arr1)): if arr1[i].lower() != arr2[i].lower() and found == False: if arr1[i+1].lower() == arr2[i+1].lower(): arrans += "("+arr2[i]+")" found = False removedscore -= 1 else: arrans += "("+arr2[i] found = True removedscore -= 1 elif arr1[i].lower() != arr2[i].lower() and found == True: if i == len(arr1)-1: if arr1[i].lower() != arr2[i].lower(): arrans += arr2[i]+")" found = False removedscore -= 1 else: if arr1[i+1].lower() == arr2[i+1].lower(): arrans += arr2[i]+")" found = False removedscore -= 1 else: arrans += arr2[i] removedscore -= 1 else: arrans += arr2[i] score = checkremoved(removedscore) print(arrans) print("%d/10 (%s)" %(score[1], score[0])) #ขี้เกียจทำแล้วครับ ขออภัยในความเละ ;) func()
"""Func""" def func(): """Find max""" inp1 = float(input()) inp2 = float(input()) inp3 = float(input()) inp4 = float(input()) inp5 = float(input()) inp6 = float(input()) inp7 = float(input()) inp8 = float(input()) inp9 = float(input()) inp10 = float(input()) def greater(num1, num2): """finding from two arguments""" return ((num1+num2) + abs(num1-num2))/2 def great(num1, num2, num3): """Find a greater number""" arg1 = greater(num1, num2) arg2 = greater(num2, num3) return ((arg1+arg2) + abs(arg1-arg2))/2 pasd = greater(great(inp1, inp2, inp3), great(inp4, inp5, inp6)) pasd2 = greater(greater(inp7, inp8), greater(inp9, inp10)) print("%.2f" %greater(pasd, pasd2)) func()
"""Func""" def checkprime(number): """Check for prime""" if number <= 3: return False if number == 1 else True if number%2 == 0 or number%3 == 0: return False i = 5 while i * i <= number: if number % i == 0 or number % (i + 2) == 0: return False i = i + 6 return True def func(): """Func""" number = int(input()) if checkprime(number): print(number, "is prime number") else: print(number, "is not prime number") func()
"""Func""" def func(): """Pork maker""" mhcount = 0 phcount = 0 shcount = 0 whcount = 0 wrongcount = 0 #err totalcount = 0 while True: ingredient = input().upper() if ingredient == "MH": mhcount += 1 elif ingredient == "PH": phcount += 1 elif ingredient == "SH": shcount += 1 elif ingredient == "WH": whcount += 1 elif ingredient != "END" and ingredient != "GH": #else mhcount = 0 phcount = 0 shcount = 0 whcount = 0 wrongcount += 1 elif ingredient == "GH": if (mhcount-1 >= 0) and (phcount-1 >= 0) and (shcount-1 >= 0) and (whcount-1 >= 0): mhcount = 0 phcount = 0 shcount = 0 whcount = 0 totalcount += 1 elif ingredient == "END": i = 1 while i <= wrongcount: print("ERROR") i += 1 print(totalcount) break func()
"""Func""" def func(): """Icecream""" me_x = int(input()) me_y = int(input()) icea_x = int(input()) icea_y = int(input()) iceb_x = int(input()) iceb_y = int(input()) def distance(ice_x, ice_y): """Find distance""" return (pow(me_x-ice_x, 2) + pow(me_y-ice_y, 2))**0.5 if distance(icea_x, icea_y) > distance(iceb_x, iceb_y): print("B") elif distance(icea_x, icea_y) < distance(iceb_x, iceb_y): print("A") elif distance(icea_x, icea_y) == distance(iceb_x, iceb_y): if icea_y > iceb_y: print("A") elif icea_y < iceb_y: print("B") else: if icea_x < iceb_x: print("A") elif icea_x > iceb_x: print("B") else: print("A") func()
"""Func""" def func(): """Find sum less than 100""" def check(number): """Checker""" if number > 100: return 0 else: return number number1 = check(int(input())) number2 = check(int(input())) number3 = check(int(input())) number4 = check(int(input())) number5 = check(int(input())) number6 = check(int(input())) number7 = check(int(input())) number8 = check(int(input())) number9 = check(int(input())) number10 = check(int(input())) total = number1+number2+number3+number4+number5+number6+number7+number8+number9+number10 if total == 420: print("herb") else: print(total) func()
"""Func""" def func(): """Guess""" wantnumber = int(input()) times = int(input()) i = 0 while i < times: guess = int(input()) if guess == wantnumber: print("Yes! It is %d." %guess) break if i == times-1: print("No more chances. You lose.") break i += 1 func()
"""Func""" def func(): """Calcualte func""" vala = int(input()) valb = int(input()) # != 0 valc = int(input()) # != 0 vald = int(input()) print("%.2f" %(((vala/valc) + vald)/valb)) func()
"""Func""" def func(): """Promotion""" ppamount = int(input()) priceperperson = float(input()) discount = int(input()) def method1(priceperperson, ppamount, discount): """method 1""" if ppamount >= 3: return (priceperperson*ppamount) * ((100-discount)/100) else: return priceperperson * ppamount def method2(ppamt, priceperperson): """method 2""" return (((ppamt // 4)* 3) + ppamt % 4)*priceperperson mth1 = method1(priceperperson, ppamount, discount) mth2 = method2(ppamount, priceperperson) if mth1 < mth2: print("Promotion 1 %.3f Baht\ \nPurchase successfully !\ \nHave a good meal with \"Kanomwhan\"" %mth1) elif mth2 < mth1: print("Promotion 2 %.3f Baht\ \nPurchase successfully !\ \nHave a good meal with \"Kanomwhan\"" %mth2) else: print("Promotion 1 %.3f Baht\ \nPurchase successfully !\ \nHave a good meal with \"Kanomwhan\"" %mth1) func()
"""Func""" def func(): """Dota2 kebab""" price = int(input()) amount = int(input()) feedb = input() if feedb == "This kebab is very good": print("%.2f" %((0.7*price) * amount)) elif feedb == "This is not good not bad": print("%.2f" %((0.95*price) * amount)) elif feedb == "This is not kebab": print("%.2f" %((1.16*price) * amount)) else: print("%.2f" %0) func()
"""Func""" def func(): """Matrix V.3""" rowcol = list(map(int, input().split(" "))) fullmatrix = [] for i in range(rowcol[0]): matrix1 = list(map(int, input().replace("[", "").replace("]", "").split(", "))) fullmatrix.append(matrix1) newmatrix = [] for i in range(rowcol[1]): newrow = [] for j in range(rowcol[0]): newrow.append((i, j)) newmatrix.append(newrow) for row in range(len(fullmatrix)): for column in range(len(fullmatrix[row])): newmatrix[column][row] = fullmatrix[row][column] for row in newmatrix: print(row) func()
"""Func""" def func(): """Time format func""" second = int(input()) day = second//(24*60*60) hour = (second//3600)%24 minute = (second//60)%60 sec = second%60 print("%02d:%02d:%02d:%02d" %(int(day), int(hour), int(minute), int(sec))) func()
"""Func""" def func(): """Wendy""" otheringredient = False buncheck = "" i = 0 while True: ingredient = input() i += 1 if ingredient == "Vegetables": print("We have to cancel your order! Get out!!") break elif ingredient == "Cheese" or ingredient == "Egg" or ingredient == "Ketchup" or \ ingredient == "Mayonnaise" or ingredient == "Beef steak" or\ ingredient == "Chicken steak" or ingredient == "Fish steak" or ingredient == "Bacon" or\ ingredient == "Sausage" or ingredient == "French fries" or ingredient == "Bun": if ingredient == "Bun": buncheck += "Bun%d" %i elif ingredient != "End": otheringredient = True elif ingredient == "End": #n-1 if otheringredient: print("I'm not sure if it is a Windy Burger.") else: lastbun = "Bun%d" %(i-1) if buncheck.find("Bun1") == 0 and (lastbun in buncheck) and len(buncheck) > 4: print("This is your burger, have a good meal.") else: print("I'm not sure if it is a Windy Burger.") break func()
"""Func""" def func(): """X burner""" itemsneed = ["X-gloves", "Leon's tail", "Bullet", "Contact lens", "Ring", "Reborn", "Tsuna"] while True: items = input() if items.lower() == "end": break for item in items.split(","): if item.strip() in itemsneed: itemsneed.remove(item.strip()) if itemsneed: print("NO, I have to run!!!") else: print("X-Burner is ready.") func()
"""Func""" def check1(password): """check 1""" score = 0 if password.isdigit(): # print("isdigit") score += 50 if password.isalpha(): # print("isalphab") score += 30 if password.islower() and password.isalpha(): # print("islower") score += 100 elif password.isupper() and password.isalpha(): # print("isupper") score += 85 # password ตัวอักษรในตำแหน่งแรกมีซ้ำกับตัวอักษรอื่นๆใน # password มากกว่า 3 ตัว โดยไม่นับตัวแรก (หักคะแนนตัวที่เกินตัวละ 15 คะแนน) counterdup = 0 for i in range(1, len(password)): if password[0] == password[i]: counterdup += 1 if counterdup > 3: score -= 15 # ความยาวของ password ที่เกินจาก 10 ตัวอักษร (ตัวละ 10 คะแนน) for i in range(len(password) - 10): score += 10 score += ord(password[-1]) return score def scorecheck(score): """Score check""" if score >= 300: secure = "secure" elif 300 > score >= 150: secure = "acceptable" elif score < 150: secure = "poor" return secure def passwordcheck(password): """Password checker""" score = 0 hasalphab, hasnumber = False, False lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",\ "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] score += check1(password) # password ประกอบไปด้วยตัวเลข และ ตัวอักษร (75 คะแนน) for alphab in lowercase: if alphab in password.lower(): hasalphab = True break for number in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: if number in password: hasnumber = True break if hasalphab and hasnumber: score += 75 # password ประกอบไปด้วยตัวอักษรพิมพ์ใหญ่ และ พิมพ์เล็กเท่านั้น (175 คะแนน) hasupper = False haslower = False if not hasnumber: for alphab in lowercase: if alphab in password: haslower = True if alphab.upper() in password: hasupper = True if hasupper and haslower: score += 175 secure = scorecheck(score) print("Password :", "*"*len(password)) print("Security score :", score) print("Security level :", secure) def func(): """Strong password""" password1 = input() if len(password1) < 6: print("try again") password2 = input() if len(password2) < 6: print("process terminated") else: passwordcheck(password2) else: passwordcheck(password1) func()
def do_plus(x,y): if (type (x)== type(1)) and (type (y)== type(1)): print(type (x)) print(type (y)) return x+y else: return str(x)+str(y)
# https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting import re import codewars_test as Test def highlight(code): ret = code ret = re.sub(r"(F+)", '<span style="color: pink">\\1</span>', ret) ret = re.sub(r"(L+)", '<span style="color: red">\\1</span>', ret) ret = re.sub(r"(R+)", '<span style="color: green">\\1</span>', ret) ret = re.sub(r"([0-9]+)", '<span style="color: orange">\\1</span>', ret) return ret if __name__ == "__main__": Test.describe("Your Syntax Highlighter") Test.it("should work for the examples provided in the description") print("Code without syntax highlighting: F3RF5LF7") print("Your code with syntax highlighting: " + highlight("F3RF5LF7")) print( 'Expected syntax highlighting: <span style="color: pink">F</span><span style="color: orange">3</span><span style="color: green">R</span><span style="color: pink">F</span><span style="color: orange">5</span><span style="color: red">L</span><span style="color: pink">F</span><span style="color: orange">7</span>' ) Test.assert_equals( highlight("F3RF5LF7"), '<span style="color: pink">F</span><span style="color: orange">3</span><span style="color: green">R</span><span style="color: pink">F</span><span style="color: orange">5</span><span style="color: red">L</span><span style="color: pink">F</span><span style="color: orange">7</span>', ) print("Code without syntax highlighting: FFFR345F2LL") print("Your code with syntax highlighting: " + highlight("FFFR345F2LL")) print( 'Expected syntax highlighting: <span style="color: pink">FFF</span><span style="color: green">R</span><span style="color: orange">345</span><span style="color: pink">F</span><span style="color: orange">2</span><span style="color: red">LL</span>' ) Test.assert_equals( highlight("FFFR345F2LL"), '<span style="color: pink">FFF</span><span style="color: green">R</span><span style="color: orange">345</span><span style="color: pink">F</span><span style="color: orange">2</span><span style="color: red">LL</span>', )
# defining a list my_list = ('2', '5', [1,2]) print(my_list) #te dice que methods pueden usarse dentro de la variable print(dir(my_list)) # index, comienza de 0 a contar print(my_list[1]) #index una lista dentro de otra lista print(my_list[2][1]) #para ver la longitud de la lista print(len(my_list)) #print(my_list[len(my_list)-1] #linea 11 si me funciona la linea 12 no **NO ME SALIO** # Sumar Lista numeros_list = [1,2,3,4,5] print(sum(numeros_list)) #sorterar listas shuffled_list = [1,0,4,6,2] shuffled_list.sort() print(shuffled_list) # Modifying lists in place #append agrega cosas a tu lista, agregó el 6 numeros_list.append([10,99]) print(numeros_list) #extend combina dos listas numeros_list.extend([7,8,9]) print(numeros_list) #replace elementwise with indexing numeros_list[2] = 55 print(numeros_list) # usando pop te regresa lo que habías quedado / remueve algo print(numeros_list.pop(2)) print(numeros_list) #si no le especificas al final el index a quitar te quita el último index, te modifica la lista print(numeros_list.pop()) print(numeros_list) # remove numeros_list.append(3) print(numeros_list) numeros_list.remove(3) print(numeros_list) print(numeros_list.pop(4)) print(numeros_list) print(numeros_list.append((5,55,67))) print(numeros_list) # Converting Between List and Strings / SPLIT my_str = 'La casa fantastica' splt_str = my_str.split() print(splt_str) #puedes poner dentro del paréntesis el caracter que quieras usar como seprardor # Join es para concatenar una lista my_join = 'Los pájaros verdes' splt_join = my_join.split() print(splt_join) print(' '.join(splt_join)) print(splt_join) print(my_join) print(splt_join) print('xxxxx'.join(splt_join)) #mostrar lo que esta dentro de la lista print(list(my_str)) #slicing de una lista, sacar elementos de una lista print(numeros_list) print(numeros_list[0:3]) print(numeros_list[4]) print(numeros_list[:3])
class Persona: def __init__(self,nombre,apellidos,edad,ocupacion,turno,sexo): self.nombre = nombre self. apellidos = apellidos self.edad = edad self.ocupacion = ocupacion self.turno = turno self.sexo = sexo class Alumno(Persona): def __init__(self,nombre,apellidos,edad,ocupacion,turno,sexo,semestre, carrera): super().__init__(nombre,apellidos,edad,ocupacion,turno,sexo) self.semestre= semestre self.carrera = carrera class Profesor(Persona): def __init__(self,nombre,apellidos,edad,ocupacion,turno,sexo,especialidad, salario): super().__init__(nombre,apellidos,edad,ocupacion,turno,sexo) self.especialidad = especialidad self.salario = salario def __str__(self): return "\n----Datos del Profesor-----\nNombre> {}\nApellidos> {} \nEdad> {}\nOcupacion> {}\nTurno> {}\nSexo> {}\nEspecialidad> {}\nSalario> {}".format( self.nombre,self.apellidos,self.edad,self.ocupacion,self.turno,self.sexo,self.especialidad,self.salario)
#Wilfred Githuka #Githuka.com #Saturday 16 December 2017 #Udacity Self Driving Car Nanodegree #Project1-Finding Lane Lines on The Road #Color Selection Code Example import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np image = mpimg.imread ('test.jpg') print ('This image is : ',type(image), 'with dimensions:', image.shape) ysize = image.shape[0] xsize = image.shape[1] color_select = np.copy(image) red_threshold = 200 green_threshold = 200 blue_threshold = 200 rgb_threshold = [red_threshold, green_threshold, blue_threshold] thresholds = (image[:,:,0] < rgb_threshold[0]) \ | (image[:,:,1] < rgb_threshold[1]) \ | (image[:,:, 2] < rgb_threshold[2]) color_select[thresholds] = [0,0,0] plt.imshow(color_select) plt.show()
# How many passwords are valid according to their policies? def read_input(file_loc): with open(file_loc, "r") as f: values = f.read().split('\n') values = [i.split(': ') for i in values] return values # for part 1 def pw_is_valid(rule_min, rule_max, rule_char, pw): count = pw.count(rule_char) if rule_min <= count <= rule_max: return True return False # for part 2 def pw_is_valid_2(pos_1, pos_2, rule_char, pw): if (pw[pos_1 - 1] == rule_char) ^ (pw[pos_2 - 1] == rule_char): return True return False values = read_input("../Inputs/day2.txt") valid_pws = 0 valid_pws_2 = 0 for [rule, pw] in values: [rule_min_max, rule_char] = rule.split(" ") [rule_min, rule_max] = rule_min_max.split("-") if pw_is_valid(int(rule_min), int(rule_max), rule_char, pw): valid_pws = valid_pws + 1 if pw_is_valid_2(int(rule_min), int(rule_max), rule_char, pw): valid_pws_2 = valid_pws_2 + 1 print(f'Part 1:\nNumber of valid passwords: {valid_pws}') print(f'Part 2:\nNumber of valid passwords: {valid_pws_2}')
# What is the ID of the earliest bus you can take to the airport # multiplied by the number of minutes you'll need to wait for that bus? import math def read_input(file_loc): with open(file_loc, "r") as f: return f.read().split("\n") notes = read_input("../Inputs/day13.txt") earliest_time = int(notes[0]) busses = [int(i) for i in notes[1].split(",") if i != "x"] schedule = {} for bus in busses: next_time = (math.floor(earliest_time / bus) + 1) * bus schedule[next_time] = bus min_waiting = min(schedule) - earliest_time earliest_bus = schedule.get(min(schedule)) print(f"Part 1:\n ID x minutes waiting: {min_waiting * earliest_bus}") # Part 2 def lcm(a, b): return int(abs(a * b) / math.gcd(a, b)) t = 0 multiplier = 1 for offset, bus in enumerate(notes[1].split(',')): if bus == 'x': continue bus = int(bus) while (t + offset) % bus != 0: t = t + multiplier multiplier = lcm(bus, multiplier) print(f"Part 2:\n Earliest Time: {t}")
"""Utility functions.""" from matplotlib import pyplot as plt import numpy as np def share_fig_ax(fig=None, ax=None, numax=1, sharex=False, sharey=False): """Reurns the given figure and/or axis if given one. If they are None, creates a new fig/ax. Parameters ---------- fig : `matplotlib.figure.Figure` figure ax : `matplotlib.axes.Axis` axis or array of axes numax : `int` number of axes in the desired figure, 1 for most plots, 3 for plot_fourier_chain sharex : `bool`, optional whether to share the x axis sharey : `bool`, optional whether to share the y axis Returns ------- `matplotlib.figure.Figure` A figure object `matplotlib.axes.Axis` An axis object """ if fig is None and ax is None: fig, ax = plt.subplots(nrows=1, ncols=numax, sharex=sharex, sharey=sharey) elif ax is None: ax = fig.gca() return fig, ax def smooth(x, window_len=3, window='flat'): """Smooth data. Parameters ---------- x : `iterable` the input signal window_len the dimension of the smoothing window; should be an odd integer window : {'flat', 'hanning', 'hamming', 'bartlett', 'blackman'} the type of window to use Returns ------- `numpy.ndarray` smoothed data Notes ----- length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y. adapted from scipy signal smoothing cookbook, http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. Raises ------ ValueError invalid window provided """ x = np.asarray(x) if window_len == 1: # short circuit and return original array if window length is unity return x if x.ndim != 1: raise ValueError('Data must be 1D.') if x.size < window_len: raise ValueError('Data must be larger than window.') if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise ValueError('Window must be one of flat, hanning, hamming, bartlett, blackman') s = np.r_[x[window_len - 1:0: - 1], x, x[-2:-window_len - 1:-1]] if window.lower() == 'flat': # moving average w = np.ones(window_len, 'd') else: w = eval('np.' + window + '(window_len)') y = np.convolve(w / w.sum(), s, mode='valid') return y[(int(np.floor(window_len / 2)) - 1):-(int(np.ceil(window_len / 2)))]
""" Implements a simple Python iteration dillema """ import numpy as np def iterator(size, mult): arr = np.ndarray((size, size), dtype=np.float64) x = 0 it = 0 for ix in np.nditer(arr, op_flags=['readwrite']): ix[...] = x x += it * mult it += 1 return arr #myarr = iterator(1000, 4) # if __name__ == '__main__': # import timeit # print(timeit.timeit("iterator(1000, 4)", # setup="from __main__ import iterator"))
from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a # Person object by birth year. @classmethod def fromBirthYear(cls, name2, year): return cls(name2, date.today().year - year) # a static method to check if a # Person is adult or not. @staticmethod def isAdult(age): return age > 18 person1 = Person('anjan', 21) person2 = Person.fromBirthYear('kumar', 1996) print (person1.age) print (person1.name) print (person2.age) print (person2.name)
File = open("Information.txt", "r") #print(File.read()) #print(File.readline()) data = File.readlines() for i in data: print(i)
#How to remove duplicate delecation from list ? a = ['ab', 'cd', 'ef', 'gh', 'ab', 'cd', 'ef', 'gh'] list = [] for i in a: if not i in list: list.append(i) print list
#Odd numbers for i in range(0,30): if i%2 == 1: print i for j in range(0,100): if j%2 == 1: print j print [k for k in range(0,20) if k%2 == 1]
def my_gen(n, m): yield n yield m print(m) n += 1 yield n n += 1 yield n n += 10 yield n b = iter(my_gen(1, 20)) print(next(b)) print(next(b)) print(next(b)) # Using for loop # for item in my_gen(1, 20): # print(item)
a = ["bangalore", "chennai", "pune"] for i in a: if i == 'chennai': continue else: if i == 'bangalore' or i == 'pune': print(i)
file = open('nums.txt', 'r') file_list = file.read().split(':') file.close() num_list = [] for i in file_list: num_list.append(int(i)) print('Have this list: \n' + str(num_list) + '\nStart sorting...') def quick_sort(l: list): if len(l) <= 1: return l bp = len(l) - 1 # l[bp], l[-1] = l[-1], l[bp] # print(f'Swap last and "{bp}" elements\n{l}') # bp = -1 lp = 0 rp = bp - 1 print('b_point: ' + str(bp) + '\nl_point: ' + str(lp) + '\nr_point: ' + str(rp)) while 1: while l[lp] < l[bp] and lp < len(l) - 1: lp += 1 while l[rp] >= l[bp] and rp > lp: rp -= 1 if rp == lp or lp == bp: sorted_pointer = lp print('s_point ' + str(sorted_pointer)) l[bp], l[lp] = l[lp], l[bp] break # print('changing r_point and l_point') l[rp], l[lp] = l[lp], l[rp] l1 = l[:sorted_pointer] l2 = l[sorted_pointer + 1:] tmp_list = quick_sort(l1) tmp_list.append(l[sorted_pointer]) return tmp_list + quick_sort(l2) def sort_test(original_list: list, sorted_list: list): print('===' * 30 + "\nTesting...\n" + '===' * 30) list1 = list(original_list) list1.sort() if list1 == sorted_list: return 1 else: return 0 print("Test success!" if sort_test(num_list, quick_sort(num_list)) else "Test Failed!")
num=int(input("enter a number:")) n=1 for i in range(0,num): for j in range(0,num-2): print(end=" ") for j in range(0,i+1): print(n,end=" ") n=n+1 print()
# getallenraden-SeanBooij # Input vragen voor het getal aan de gamemaster te_raden_getal = input("Welk getal wil je gebruiken?\n") # De loop om te vragen aan de nieuweling welk getal het is, met het maximaal aantal beurten. In dit geval 7. for i in range(0,7): ingevoerd_getal = input("Welk getal denk je dat het is?\n") if ingevoerd_getal > te_raden_getal: print("Getal is te hoog") if ingevoerd_getal < te_raden_getal: print("Getal is te laag") if te_raden_getal == ingevoerd_getal: print("je hebt het getal goed geraden good job") break # Maximum aantal beurten if i == 6: print("je hebt geen beurten meer helaas")
''' 输入一个链表,反转链表后,输出新链表的表头。 ''' # -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 头插法 19ms,5624k # 返回ListNode def ReverseList(self, pHead): # write code here if pHead == None: return None p=ListNode(pHead.val) pHead=pHead.next while pHead!=None: tmp=ListNode(pHead.val) tmp.next=p p=tmp pHead=pHead.next return p a1=ListNode(1) a2=ListNode(3) a1.next=a2 a3=ListNode(5) a2.next=a3 a4=ListNode(8) a3.next=a4 s=Solution() l=s.ReverseList(a1) print(l.val) print(l.next.val) print(l.next.next.val) print(l.next.next.next.val)
''' 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。 保证base和exponent不同时为0 ''' # -*- coding:utf-8 -*- class Solution: # 20ms,5692k def Power(self, base, exponent): # write code here return pow(base, exponent) # -*- coding:utf-8 -*- class Solution2:#22ms,5720k def Power(self, base, exponent): # write code here if exponent > 0: tmp = base for i in range(exponent): base *= tmp return base elif exponent < 0: x = 1 / base tmp = x for i in range(-exponent): x *= tmp return x else: return 1 s = Solution2() print(s.Power(2, 3))
''' 一个整型数组里除了两个数字之外,其他的数字都出现了两次。 请写程序找出这两个只出现一次的数字。 ''' # -*- coding:utf-8 -*- class Solution: # 28ms,5644k # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here count = 0 result = [] while len(array) > 0: a = array.pop() # 对元素进行出栈操作 if a in array: array.remove(a) # 若出栈的元素在列表里,说明这个数是出现了两次的,直接去掉。 else: result.append(a) # 否则就是答案 count += 1 if count == 2: return result # -*- coding:utf-8 -*- class Solution2: # remove操作比较费时间,所以可以换成用字典存储下出现的字,这样可以用空间换时间。21ms,5732k # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here count = 0 result = [] number_dict = {} while len(array) > 0: a = array.pop() # 对元素进行出栈操作 if a not in number_dict: number_dict[a] = 1 if a in array: number_dict[a] += 1 # 若出栈的元素在列表里,说明这个数是出现了两次的,直接去掉。 elif number_dict[a] == 1: result.append(a) # 否则就是答案 count += 1 if count == 2: return result
'''给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2];)''' # -*- coding:utf-8 -*- class Solution: def multiply(self, A): # write code here B = [] Alen = len(A) for i in range(Alen): tmp = 1 for j in range(Alen): if j != i: tmp *= A[j] B.append(tmp) return B class Solution2: def multiply(self, A): B = [1] for i in range(1, len(A)): B.append(B[i - 1] * A[i - 1]) tmp = 1 for j in range(len(A) - 2, -1, -1): tmp *= A[j+1] B[j] *= tmp return B p = Solution2() e = p.multiply([1, 2, 3, 4, 5]) print(e)
''' 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老, 自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m, 让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物, 并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演, 并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢? (注:小朋友的编号是从0到n-1) 如果没有小朋友,请返回-1 ''' # -*- coding:utf-8 -*- class Solution: #运行时间23ms,占用内存5708k def LastRemaining_Solution(self, n, m): # write code here if n == 0: return -1 if n == 1: return 0 P = [] begain = 0 for i in range(n): P.append(i) while n > 1: P.pop((begain+m - 1) % n) begain = (begain+m - 1) % n n = n - 1 return P[0] s = Solution() print(s.LastRemaining_Solution(5, 14))
def get_num(name: str) -> int: num = name.split('-')[1].lstrip('0') num = 0 if len(num) == 0 else int(num) return num def get_pod(name: str, k: int) -> int: num = name.split('-')[1].lstrip('0') num = 0 if len(num) == 0 else int(num) if name.startswith('h-'): pod = int(num / (k * k / 4.)) elif name.startswith('agg-') or name.startswith('tor-'): pod = int(num / (k / 2.)) else: raise KeyError("Node {} does not belong to a pod.".format(name)) return pod
s = input("Enter the String 1 : ") k = input("Enter the String 2 : ") k = k.lower() s = s.lower() count = 0 for i in s: if i not in k: count = 1 break else: count = 0 if count == 1: print("No") elif count == 0: print("Yes")
import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 6.0, 0.01) ################################################ def function(r): theta = 4 * np.pi * r return theta ################################################### ax = plt.subplot(111, polar=True) ax.plot(function(r), r, color='r', linewidth=2) ax.set_rmax(2.0) ax.grid(True) ax.set_title("A line plot on a polar axis", va='bottom') plt.show()
def isPrime(num): return False if num > 1: for i in range(2,num): if (num % i) == 0: return False else: return True return False
while True: try: print('Enter number:') #this prints a command for people to enter a number (works) number = int(input()) #this asks people to enter a number (works) except ValueError: print('please enter a numeric value.') else: break def collatz(): #define collatz function (works) global number if number % 2 == 0: number = number // 2 print(number) elif number % 2 == 1: number = number * 3 + 1 print(number) while number != 1: #ensures program keeps working until it evaluates to "1" collatz() continue
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sortedArrayToBST(self, nums): """ Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Args: nums(List[int]): the name of the ascending order sorted array Returns: the root node of the converted balanced BST(TreeNode) """ if len(nums)==0: return None elif len(nums)==1: return TreeNode(nums[0]) elif len(nums)==2: root=TreeNode(nums[1]) root.left=TreeNode(nums[0]) return root else: mid=int(len(nums)/2) root=TreeNode(nums[mid]) root.left=self.sortedArrayToBST(nums[:mid]) root.right=self.sortedArrayToBST(nums[mid+1:]) return root
class Solution: def isHappy(self, n): """ Write an algorithm to determine if a number is "happy". Args: n(int): the given integer number Returns: A bool value(bool) """ history = [] while True: n = sum([int(d)**2 for d in str(n)]) if n == 1: return True if n not in history: history.append(n) elif n in history and n != 1: return False
# import all libraries from IPython.display import display, Image import numpy as np from keras.models import Sequential # initialize NN as a Sequence from keras.layers import Convolution2D # to deal with images from keras.layers import MaxPool2D # this will add pooling layers from keras.layers import Flatten # this will flatten pooling layers from keras.layers import Dense # create NN from keras.preprocessing.image import ImageDataGenerator class CNN: def __init__(self): pass classifier = Sequential() # create convolutional layer def addConvolutionalLayer(self): self.classifier.add(Convolution2D(32, 3, 3, input_shape=(64, 64, 3), activation='relu')) # feature detectors , filter 3 by 3 , # input shape - format of pictures that are inputed , depends if there are coloured images or black and white # number of channels - 3 # 64 , 64 - parameters of pictures # activation function - rectify def maxPooling(self): self.classifier.add(MaxPool2D(pool_size=(2, 2))) # we take a size 2,2 of stride def flattening(self): self.classifier.add(Flatten()) def fullConnection(self): self.classifier.add(Dense(output_dim=128, activation='relu')) self.classifier.add( Dense(output_dim=1, activation='sigmoid')) # sigmoid function becouse there is a binary outcome # output_dim - how many nodes will be def compile(self): self.classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics={"named_accuracy" : 'accuracy'}) # stochastic discent - adam # loss - binary cross entropy , becouse it is a classification problem # metrics - accuracy # using image augmentation to prevent overfitting def trainTest(self): train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory( 'data/training_set', target_size=(64, 64), batch_size=32, # number of images that will go threw and weights will be updated class_mode='binary') test_set = test_datagen.flow_from_directory( 'data/test_set', target_size=(64, 64), batch_size=32, class_mode='binary') self.classifier.fit_generator( train_generator, steps_per_epoch=200, epochs=5, validation_data=test_set, validation_steps=2000)
from collections import defaultdict class Furniture: '''An inventory item with a name, description, and price.''' def __init__(self, name, description, price): self.name = name self.description = description self.price = price def __str__(self): return self.name + '.' + '\n' + self.description class ShoppingCart: '''A container to track and add up a customer's purchases.''' sales_tax = 0.088 def __init__(self, customer_id=""): self.customer_id = customer_id self.contents = defaultdict(int) self.total = 0 self.taxes = 0 def add_item(self, item, quantity = 1): self.contents[item] += quantity def remove_item(self, item, quantity = 1): self.contents[item] -= quantity if self.contents[item] <= 0: del self.contents[item] def _update_total(self): for item, quantity in self.contents.items(): self.total += item.price * quantity self.taxes += item.price * quantity * self.sales_tax def __str__(self): result = "" for item, quantity in self.contents.items(): result += str(item) + '\n' + f'Price: ${item.price;.2f}, Quantity: {quantity}'+ \ '\n\n' return result def print_receipt(self): self._update_total() print(self.customer_id, "Items:\n") print(self, end="") print(self.customer_id, "Total:") print(f"${self.total + self.taxes:.2f}") if __name__ == '__main__': lovely_loveseat = Furniture("Lovely Loveseat", "Tufted polyester blend on wood. 32 inches high x 40 inches wide \ x 30 inches deep. Red or white.", 254.00) stylish_settee = Furniture("Stylish Settee", "Faux leather on birch. 29.50 inches high x 54.75 inches wide \ x 28 inches deep. Black.", 180.50) luxurious_lamp = Furniture("Luxurious Lamp", "Glass and iron. 36 inches tall. Brown with cream shade.", 52.15) inventory = {"Lovely Loveseat" : lovely_loveseat, "Stylish Settee" : stylish_settee, "Luxurious Lamp" : luxurious_lamp, } customer_one = ShoppingCart("Customer One") customer_one.add_item(inventory["Lovely Loveseat"]) customer_one.add_item(inventory["Luxurious Lamp"], 2) customer_one.remove_item(inventory["Lovely Loveseat"]) print(customer_one.contents) customer_one.print_receipt()
# Xander Eagle # January 6, 2020 # this program draws a target and adds up the total points based on where the user clicks import pygame class Target: def __init__(self, main_surface): self.main_surface = main_surface self.score = 0 def draw_target(self): # this functions draws the target and adds the color x = int(self.main_surface.get_width()/2) y = int(self.main_surface.get_height()/2) pygame.draw.circle(self.main_surface, (0, 0, 0), (x, y), 350, 1) pygame.draw.circle(self.main_surface, (0, 0, 0), (x, y), 280, 0) pygame.draw.circle(self.main_surface, (0, 0, 255), (x, y), 210, 0) pygame.draw.circle(self.main_surface, (255, 0, 0), (x, y), 150, 0) pygame.draw.circle(self.main_surface, (255, 255, 0), (x, y), 80, 0) def print_mouse_coordinates(self, position): # this function gives each color a value and adds it to the total... # ...every click target_color = self.main_surface.get_at(position) if target_color == (255, 255, 0, 255): self.score += 9 if target_color == (255, 0, 0, 255): self.score += 7 if target_color == (0, 0, 255, 255): self.score += 5 if target_color == (0, 0, 0, 255): self.score += 3 if target_color == (255, 255, 255, 255): self.score += 1 self.main_surface.fill((255, 255, 255)) self.draw_target() mouse_font = pygame.font.SysFont("Helvetica", 32) mouse_label = mouse_font.render(str(self.score), 1, (0, 255, 255)) self.main_surface.blit(mouse_label, (30, 30)) pygame.display.update()
#!/usr/bin/env python3 """ File: static_save.py Purpose: A decorator function to initialize a list of static variables to a None. Usage: In the python file, add the following line above the function definition which is to be decorated. @static_vars([<variable_list]) def target_function(): where, <variable_list> = List of static variables within the function "target_function" """ from delphi.translators.for2py.arrays import * from dataclasses import dataclass def static_vars(var_list): # This code is part of the runtime system def decorate(func): for var in var_list: setattr(func, var["name"], var["call"]) return func return decorate
""" This module implements several arithmetic and logical operations such that it maintains single-precision across variables and operations. It overloads double-precision floating variables into single-precision using numpy's float32 method, forcing them to stay in single-precision type. This avoids a possible butterfly effect in numerical operations involving large floating point calculations. Usage: To convert a float variable into Float32 type, do the following target = Float32(float_variable) OR target = Float32(5.0) where <target> is now a Float32 object. Now, any arithmetic/logical operation involving <float_variable> will involve single-point calculations. Example Usage: eps = Float32(1.0) while eps + 1.0 > 1.0: ____eps /= 2.0 eps *= 2.0 Authors: Saumya Debray Pratik Bhandari """ from numbers import Real, Number import math from numpy import float32 class Float32(Real): """ This class converts float variables into float32 type for single-precision calculation and overloads the default arithmetic and logical operations. All methods below follow a similar input/output type. Input: Either a Float32 variable or a variable of a supported type. Output: A Float32 object of the result of the operation. """ def __init__(self, val): """ This constructor converts the float variable 'val' into numpy's float32 type. """ self._val = float32(val) def __add__(self, other): """ Addition """ return Float32(self._val+self.__value(other)) def __radd__(self, other): """ Reverse Addition """ return Float32(self._val+self.__value(other)) def __truediv__(self, other): """ True Division """ return Float32(self._val/self.__value(other)) def __rtruediv__(self, other): """ Reverse True Division """ return Float32(self.__value(other)/self._val) def __floordiv__(self, other): """ Floor Division """ return self._val//self.__value(other) def __rfloordiv__(self, other): """ Reverse Floor Division """ return self.__value(other)//self._val def __mul__(self, other): """ Multiplication """ return Float32(self._val*self.__value(other)) def __rmul__(self, other): """ Reverse sMultiplication """ return Float32(self._val*self.__value(other)) def __sub__(self, other): """ Subtraction """ return Float32(self._val-self.__value(other)) def __rsub__(self, other): """ Reverse Subtraction """ return Float32(self.__value(other)-self._val) def __eq__(self, other): """ Logical Equality """ return self._val == self.__value(other) def __gt__(self, other): """ Logical greater than """ return self._val > self.__value(other) def __ge__(self, other): """ Logical greater than or equals to """ return self._val >= self.__value(other) def __lt__(self, other): """ Logical less than """ return self._val < self.__value(other) def __le__(self, other): """ Logical less than or equals to """ return self._val <= self.__value(other) def __ne__(self, other): """ Logical not equal to """ return self._val != self.__value(other) def __str__(self): """ Float-to-string conversion """ return str(self._val) def __abs__(self): """ Absolute value conversion """ return abs(self._val) def __neg__(self): """ Value negation """ return -self._val def __mod__(self, other): """ Modulo operation """ return Float32(self._val % self.__value(other)) def __rmod__(self, other): """ Reverse Modulo operation """ return Float32(self.__value(other) % self._val) def __and__(self, other): """ Bitwise 'and' of two variables """ return Float32(self._val and self.__value(other)) def __or__(self, other): """ Bitwise 'or' of two variables """ return Float32(self._val or self.__value(other)) def __pos__(self): """ Return positive value """ return +self._val def __pow__(self, other): """ Power operation """ return Float32(self._val ** self.__value(other)) def __rpow__(self, other): """ Reverse Power operation """ return Float32(self.__value(other) ** self._val) # ========================================================================== # Added by Paul to extend the Real class def __float__(self): return float(self._val) def __round__(self, ndigits=None): return round(self._val, ndigits=ndigits) def __ceil__(self): return Float32(math.ceil(self._val)) def __floor__(self): return Float32(math.floor(self._val)) def __trunc__(self): return int(self._val) # ========================================================================== def __value(self, other): """ This method checks whether the variable is a Float32 type or not and returns it's value likewise. """ if isinstance(other, Float32): return other._val elif isinstance(other, Number): return other else: raise TypeError(f"Unusable type ({type(other)}) with Float32")
from itertools import permutations from itertools import combinations class Service(object): def sorted_key(self, word): chars = [c for c in word] chars.sort() return "".join(chars) def possiblepermutations(self,text): return [''.join(p) for p in permutations(text)] def subWordSort(self,word): listWord = list(word) word_keys = [] for i in range(3,len(word)+1): temp=(["".join(c)for c in permutations(word,i)]) for c in temp: word_keys.append(c) return word_keys
a=int(input('Enter first number: ')) b=int(input('Enter second number: ')) if(a==b): print('Two numbers are equal') else: print('Two numbers are not equal')
import sys def appEnd(flag): if flag==1: file.close() sys.exit() path = "testfile.text" #input("path (e.x. testfile.text): ") #'testfile.text' procType = "symbols" #input("Select process method (words, sentences, symbols): ") minSymb = 20#int(input("Min count symbols: ")) maxSymb = 50#int(input("Max count symbols: ")) wordsNumb = 2#nt(input("Number of words: ")) #print(wordsNumb) sentNumb = 4#int(input("Number of sentences: ")) file = open(path, encoding="utf8") # 'r' winsows... # print(file.read()) str1 = file.read() # print(str1) # wordsObj = str1.split(' ') # concString = ""; # sordsNumb = 200 # for x in range(0, sordsNumb): # concString += wordsObj[x] + ' ' # print(concString) concString = "" wordsObj = str1.split(' ') # split to words sentObj = str1.split('.') # add &, ! if procType == "symbols": #print("symbols") if (len(concString) < maxSymb): #and len(concString) > minSymb print(concString) elif(len(concString) > maxSymb): print(concString[0 : maxSymb]) elif procType == "words": # wordsObj = str1.split(' ') for x in range(0, wordsNumb): concString += wordsObj[x] + ' ' # print(len(concString.split(' '))) # words ammount if (len(concString) < maxSymb): #and len(concString) > minSymb print(concString) elif(len(concString) > maxSymb): print(concString[0 : maxSymb]) # elif < min #print(concString) # print("words") elif procType == "sentences": print("sentences") # sentObj = str1.split('.') # add &, ! concString = "" for x in range(0, sentNumb): concString += sentObj[x] + '.' #print(len(concString.split(' '))) # words ammount if (len(concString.split(' ')) > wordsNumb): for x in range(0, wordsNumb): concString += wordsObj[x] + ' ' # print(concString) # print("< words") # elif(len(concString.split(' ')) > wordsNumb): # wordsObj = str1.split(' ') # for x in range(0, wordsNumb): # concString += wordsObj[x] + ' ' if(len(concString) < maxSymb and len(concString) > minSymb): # size = 0 print(concString) print("< symbols") elif(len(concString) > maxSymb): print(concString[0 : maxSymb]) # elif < min # if (len(concString.split(' ')) < maxSymb and len(concString.split(' ')) > minSymb): # print(concString) # elif(len(concString.split(' ')) > minSymb): # print(concString[0 : minSymb]) else: print("Please, read man, you sun of the bitch :)") appEnd(0) #appEnd(1)
# --- Define your functions below! --- from random import * def intro(): name = input("Hello! What's your name? ") print("Nice to meet you,", name) def is_valid_input(): while True: answer = input("What would you like to do? You can CHAT or PLAY rock, paper, scissors: ") valid_responses = ["chat", "play"] if answer in valid_responses: process_input(answer) elif answer == "bye": return answer def rock_paper_scissors(): gameOver = False while gameOver == False: objects = ["rock", "paper", "scissors"] objIdx = randint(0, len(objects) - 1) choice = input("Choose rock, paper, or scissors: ") move = objects[objIdx] if choice == move: print("Your choice: %s. My choice: %s." %(choice, move)) print("Draw! Try again.") elif (choice == "rock" and move == "paper") or (choice == "paper" and move == "scissors") or (choice == "scissors" and move == "rock"): print("Your choice: %s. My choice: %s." %(choice, move)) print("You lose!") gameOver = True elif (choice == "paper" and move == "rock") or (choice == "scissors" and move == "paper") or (choice == "rock" and move == "scissors"): print("Your choice: %s. My choice: %s." %(choice, move)) print("You win!") gameOver = True elif choice == "bye": gameOver = True return choice else: print("That's not an option") def process_input(answer): valid_greeting = ["hi", "hello", "hey", "hey there", "Hi", "Hey", "Hello", "Hey there"] if answer == "play": rock_paper_scissors() elif answer == "chat": while True: answer = input("What would you like to talk about? ") if answer in valid_greeting: print("Hello!") elif answer == "bye": return answer else: print("That's cool!") elif answer == "bye": return answer else: answer = input("What would you like to do? You can CHAT or PLAY rock, paper, scissors: ") # --- Put your main program below! --- def main(): intro() is_valid_input() # DON'T TOUCH! Setup code that runs your main() function. if __name__ == "__main__": main()
idade = int(input("Coloque sua idade: ")) if idade >= 18: print ("Maior") else: print ("Menor")
import requests def by_city(): city = input('Enter your city : ') url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid= your api key here &units=metric'.format(city) res = requests.get(url) data = res.json() show_data(data) def by_location(): res = requests.get('https://ipinfo.io/') data = res.json() location = data['loc'].split(',') latitude = location[0] longitude = location[1] url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid= your api key here &units=metric'.format(latitude, longitude) res = requests.get(url) data = res.json() show_data(data) def show_data(data): temp = data['main']['temp'] wind_speed = data['wind']['speed'] latitude = data['coord']['lat'] longitude = data['coord']['lon'] description = data['weather'][0]['description'] print() print('Temperature : {} degree celcius'.format(temp)) print('Wind Speed : {} m/s'.format(wind_speed)) print('Latitude : {}'.format(latitude)) print('Longitude : {}'.format(longitude)) print('Description : {}'.format(description)) def main(): print('1. Get data By city') print('2. Get data By location') choice = input('Enter your choice : ') if choice == '1': by_city() else: by_location() if __name__ == '__main__': main()
from pynput.keyboard import Key, Controller import time import keyboard Keyboard = Controller() print(""" ██╗███╗ ██╗██████╗ ██╗ ██╗████████╗ ███████╗██████╗ █████╗ ███╗ ███╗███╗ ███╗███████╗██████╗ ██║████╗ ██║██╔══██╗██║ ██║╚══██╔══╝ ██╔════╝██╔══██╗██╔══██╗████╗ ████║████╗ ████║██╔════╝██╔══██╗ ██║██╔██╗ ██║██████╔╝██║ ██║ ██║ ███████╗██████╔╝███████║██╔████╔██║██╔████╔██║█████╗ ██████╔╝ ██║██║╚██╗██║██╔═══╝ ██║ ██║ ██║ ╚════██║██╔═══╝ ██╔══██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██╔══██╗ ██║██║ ╚████║██║ ╚██████╔╝ ██║ ███████║██║ ██║ ██║██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ██║ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ """) print("Enter Esc key to start spamming...\n---------------------------------\n") while True: try: spamNum = input("How many messages do you want to send?: ") spamNum = int(spamNum) break except: print("Error: try again.. (Enter a Number)") message = input("Enter the message to spam: ") while True: if keyboard.is_pressed('!'): # if key 'q' is pressed for i in range(1, spamNum + 1): print(str(i) + " Messages Sent.") for letter in str(message): Keyboard.press(letter) Keyboard.release(letter) Keyboard.press(Key.enter) Keyboard.release(Key.enter) time.sleep(0.1) break
import pygame from pygame.locals import * class Control: def __init__(self): self.game_Play = True self.direction_controller = 'RIGHT' self.game_start = False self.pause = True self.game_start_counter = True #Простой контролер персонажа, в зависимости от нажатой кнопки двигается def snake_control(self): for event in pygame.event.get(): if event.type == QUIT: self.game_Play = False elif event.type == KEYDOWN: if event.key == K_RIGHT and self.direction_controller != 'LEFT': self.direction_controller = 'RIGHT' elif event.key == K_LEFT and self.direction_controller != 'RIGHT': self.direction_controller = 'LEFT' elif event.key == K_UP and self.direction_controller != 'DOWN': self.direction_controller = 'UP' elif event.key == K_DOWN and self.direction_controller != 'UP': self.direction_controller = 'DOWN' elif event.key == K_ESCAPE: self.game_Play = False elif event.key == K_SPACE: if self.pause == True: self.pause = False self.game_start_counter = False else: self.pause = True
#!/usr/bin/env python # Suggest a sexy Halloween costume idea import json import requests url = "http://whatthefuckshouldibeforhalloween.com/api.com?count=1" response = requests.get(url) json_data = json.loads(response.text) suggestion = json_data[0] print "%s %s" % (suggestion['prompt'], suggestion['costume'].upper())
#Problème d'importation liée à un problème d'encodage, réglé par ces lignes #!/usr/bin/env python #-*- coding: utf-8 -*- #Fichier définissant la classe histoire from pickle import * #Module permettant la sauvegarde class Histoire: """Classe d'objet contenant la totalite d'une histoire: un attribut pour les paragraphes un attribut pour les liens un attribut pour les choix """ def __init__(self): self.paragraphes=[] self.liens=[] self.choix=[] #Méthode d'ajout des différents objets def ajout_p(self,p): #Normalement ce test n'a pas à être faux, mais on ne sait jamais if p not in self.paragraphes: self.paragraphes.append(p) def ajout_l(self,l): if l not in self.liens: self.liens.append(l) def ajout_c(self,c): if c not in self.choix: self.choix.append(c) def sauvegarde(self,nom): """Permet de sauvegarder l'objet dans un fichier""" #La méthode with permet d'ouvrir un fichier et d'exécuter des actions dans le fichier. Si jamais une erreur interrompt le #programme, le fichier sera quand même fermé with open(nom,"wb") as fichier: pick=Pickler(fichier) #Le module pickle a une classe d'objet nommé Pickler, qui est associé à la variable contenant le fichier pick.dump(self) #La méthode dump de cette objet permet d'enregistrer n'importe quelle information dans un fichier, ici #on enregistre l'objet histoire directement def charger(self,nom): """Permet de charger un objet de type histoire contenu dans un fichier. Attention, l'objet doit être VIDE sinon l'objet garde ses anciennes caractéristiques. Mettre le résultat de la fonction dans une var, self ne marche pas Exemple: Si h doit recevoir le fichier chargé écrire: h=Histoire() h=h.charger()""" try: with open(nom,"rb") as fichier: unpick=Unpickler(fichier) #Le module pickle contient également une classe d'objet nommé Unpickler, qui est associé #à la variable contenant le fichier. Il permet, cette fois ci, de récupérer chaque objet histoire=unpick.load() #enregistré dans un fichier. Ici, notre objet histoire return histoire except: pass def verif(self): """Vérif de la validité de chacun des éléments. Non complet, évalue juste si les attributs sont non vides (pas d'info si toujours d'actualité)""" for p in self.paragraphes: if p.verif() !=True: #Méthode à créer return "Error" for l in self.liens: if l.verif() !=True: return "Error" for c in self.choix: if c.verif() !=True: #Méthode à créer return "Error" #A l'avenir, il faudra créer des fonctions pour chaque erreur, afin d'indiquer à l'utilisateur l'erreur qu'il a commise #Fonction de mise à jour des différents attributs de l'objet, qui sont tous des listes def del_l(self,lien): """Permet de supprimer l'objet lien de la liste correspondante de l'objet""" self.liens.remove(lien) def del_p(self, paragraphe): """Permet de supprimer l'objet paragraphe de la liste correspondante de l'objet""" self.paragraphes.remove(paragraphe) def del_c(self,choix): """Permet de supprimer l'objet choix de la liste correspondante de l'objet""" self.choix.remove(choix)
#!/usr/bin/env python3 class Ferry: def __init__(self, instructions, waypoint=False): self.x = 0 self.y = 0 self.facing = 0 self.waypoint_x = 10 self.waypoint_y = 1 for instruction in instructions: if not waypoint: self.move(instruction) else: self.move_with_waypoint(instruction) def move(self, instruction): command = instruction[0] amount = int(instruction[1:]) if command == "F": if self.facing == 0: command = "E" elif self.facing == 90: command = "N" elif self.facing == 180: command = "W" elif self.facing == 270: command = "S" else: print(f"Unexpected facing: {self.facing}") if command == "N": self.y += amount elif command == "S": self.y -= amount elif command == "E": self.x += amount elif command == "W": self.x -= amount elif command == "L": self.facing = (self.facing + amount) % 360 elif command == "R": self.facing = (36000 + self.facing - amount) % 360 else: print(f"Unexpected command: {command}") def move_with_waypoint(self, instruction): command = instruction[0] amount = int(instruction[1:]) if command == "F": self.x += self.waypoint_x * amount self.y += self.waypoint_y * amount elif command == "N": self.waypoint_y += amount elif command == "S": self.waypoint_y -= amount elif command == "E": self.waypoint_x += amount elif command == "W": self.waypoint_x -= amount elif command == "L": turns = amount // 90 for _ in range(turns): self.waypoint_x, self.waypoint_y = self.waypoint_y * -1, self.waypoint_x elif command == "R": turns = amount // 90 for _ in range(turns): self.waypoint_x, self.waypoint_y = self.waypoint_y, self.waypoint_x * -1 else: print(f"Unexpected command: {command}") def distance_from_origin(self): return abs(self.x) + abs(self.y) def load_input(filename): with open(filename) as f: return [line.strip() for line in f.readlines()] if __name__ == "__main__": instructions = load_input("day12_input.txt") ferry = Ferry(instructions) print(f"Part 1: {ferry.distance_from_origin()}") ferry = Ferry(instructions, waypoint=True) print(f"Part 2: {ferry.distance_from_origin()}") # ~~~ Tests ~~~ # def test_distance(): instructions = ["F10", "N3", "F7", "R90", "F11"] ferry = Ferry(instructions) assert ferry.distance_from_origin() == 25 def test_distance_with_waypoint(): instructions = ["F10", "N3", "F7", "R90", "F11"] ferry = Ferry(instructions, waypoint=True) assert ferry.distance_from_origin() == 286
from collections import deque def materials_or_magics(m): if m: print("Materials left:", end=" ") print(*materials, sep=", ") materials = deque(int(n) for n in input().split() if int(n) != 0) magics = deque(int(n) for n in input().split() if int(n) != 0) gifts = { 150: ["Doll", 0], 250: ["Wooden train", 0], 300: ["Teddy bear", 0], 400: ["Bicycle", 0] } while magics and materials: material = materials.pop() magic = magics.popleft() total = magic * material if total not in gifts: if total < 0: material += magic else: material += 15 if not material == 0: materials.append(material) continue gifts[total][1] += 1 materials = deque(reversed(materials)) if gifts[150][1] > 0 and gifts[250][1] > 0 or gifts[400][1] > 0 and gifts[300][1] > 0: print("The presents are crafted! Merry Christmas!") materials_or_magics(materials) materials_or_magics(magics) for key, value in dict(sorted(gifts.items(), key=lambda el: el[1][0])).items(): if value[1] > 0: print(f"{value[0]}: {value[1]}") else: print("No presents this Christmas!") materials_or_magics(materials) materials_or_magics(magics)
def get_matrix(matrix, n): position = [] for index in range(n): row = input() for col in range(n): if not row[col] == "-": matrix[index][col] = row[col] if row[col] == "P": position = [index, col] return matrix, position def next_cells_move(position, move): x = position[0] + move[0] y = position[1] + move[1] return x, y def is_valid(matrix, coordinate): x, y = coordinate return 0 <= x < len(matrix) and 0 <= y < len(matrix) initial_string = input() n = int(input()) matrix = [["-"]*n for row in range(n)] commands = { 'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1), } matrix, current_position = get_matrix(matrix, n) for _ in range(int(input())): command = input() move_coordinate = commands[command] next_cell = next_cells_move(current_position, move_coordinate) if is_valid(matrix, next_cell): pos_x, pos_y = current_position x, y = next_cell if not matrix[x][y] == "-": initial_string += matrix[x][y] current_position = next_cell matrix[pos_x][pos_y] = "-" matrix[x][y] = "P" else: initial_string = initial_string[:-1] print(initial_string) print(*["".join(m) for m in matrix], sep="\n")
# function declaration def print_matrix(matrix): for row in range(0,len(matrix)): print(matrix[row]) def swap_row(matrix,row1,row2): for i in range(0,len(matrix)+1): temp=matrix[row1][i] matrix[row1][i]=matrix[row2][i] matrix[row2][i]=temp def scale_row(matrix,row,factor): for i in range(0,len(matrix)+1): matrix[row][i]=float(matrix[row][i])*float(factor) def add_to_row(matrix,rowTarget,rowSource,factor): for i in range(0,len(matrix)+1): matrix[rowTarget][i]=float(matrix[rowTarget][i])+float(matrix[rowSource][i])*float(factor) size=float(input("Enter the size of the matrix: ")) #initializing list with rows and columns: extra column for constant term matrix=[[] *(int(size)+1) for i in range(int(size))] for row in range(0,int(size)): for column in range(0,int(size)+1): matrix[int(row)].append(input("Enter row "+str(row+1)+" column "+str(int(column)+1)+": ")) print("The size of the matrix is :",len(matrix)) print("The original matrix is:\t") print_matrix(matrix) # matrix reducing loop for row in range(0,len(matrix)): # while the first element is 0, swap until it is not if float(matrix[row][row])==0: swap=0 while matrix[swap][swap]==0: swap+=1 swap_row(matrix,row,swap) # now the row we're on is not 0 in the diagonal scale_row(matrix,row,1.0/float(matrix[row][row])) for i in range(0,len(matrix)): if i!=row: add_to_row(matrix,int(i),int(row),-float(matrix[i][row])) # making the numbers nice for row in range(0,int(size)): for column in range(0,int(size)+1): matrix[row][column]=round(float(matrix[row][column]),4) if float(matrix[row][column])==0: matrix[row][column]=float(0) # final print print("\nThe RREF form is:") print_matrix(matrix)
import threading import datetime from time import sleep class myThread(threading.Thread): def __init__(self, name): super().__init__() self.name = name def run(self): print (f"Starting {self.name}") threadLock.acquire(blocking=False, timeout=-1) print_date(self.name) if threadLock.locked(): threadLock.release() print (f"Finishing {self.name}") def print_date(thread_name): today = datetime.date.today() if thread_name == "Thread 1": sleep(2) print(f"{thread_name}: {today}") threadLock = threading.Lock() threads = [] thread1 = myThread("Thread 1") thread2 = myThread("Thread 2") thread1.start() thread2.start() threads.append(thread1) threads.append(thread2) for t in threads: t.join() print("Threads are dead")
temperatura = int (print (input ("Digite uma temperatura: "))) print ("A temperatua em Fahrenheit é: " temperatura = (5/9) * (temperatura – 32))
'''Trabalho feito por david, gabriel rech e gabriel sgorla''' nota100 = 6 nota50 = 6 nota20 = 6 nota10 = 6 notas = 0 while True: saque = int(input("Digite quanto sacar: ")) if saque // 100 >= 1 and nota100 > 0: notas = saque // 100 saque = saque % 100 nota100 -= notas print("A quantidade de notas de 100: ", notas) if saque // 50 >= 1 and nota50 > 0: notas = saque // 50 saque = saque % 50 nota50 -= notas print("A quantidade de notas de 50: ", notas) if saque // 20 >= 1 and nota20 > 0: notas = saque // 20 saque = saque % 20 nota20 -= notas print("A quantidade de notas de 20: ", notas) if saque // 10 >= 1 and nota10 > 0: notas = saque // 10 saque = saque % 10 nota10 -= notas print("A quantidade de notas de 10: ", notas) if nota100 == 0 and nota50 == 0 and nota20 == 0 and nota10 == 0: print("Saque nao disponivel!") break print("Fim do programa")
# Trabalhando com strings: # multstring: seja uma string s e um inteiro positivo n retorna uma # string com n cópias da string original multstring('Hi', 2) -> 'HiHi' print('Hi' * 2) #string_splosion: string_splosion('Code') -> 'CCoCodCode', # string_splosion('abc') -> 'aababc', string_splosion('ab') -> 'aab' palavra = str(input('Digite uma palvra: ')) auxiliar = "" for i in len(palavra): print() # array_count9: conta quantas vezes aparece o 9 numa lista nums # array_front9: verifica se pelo menos um dos quatro primeiros é nove, # array_front9([1, 2, 9, 3, 4]) -> True array_front9([1, 2, 3, 4, 9]) -> False, # array_front9([1, 2, 3, 4, 5]) -> False # hello_name: seja uma string name hello_name('Bob') -> 'Hello Bob!' # make_tags: make_tags('i', 'Yay'), 'Yay', make_tags('i', 'Hello'), 'Hello' # I. sem_pontas - seja uma string s de pelo menos dois caracteres # retorna uma string sem o primeiro e último caracter - without_end('Hello') -> 'ell'
# Leia um número e imprima seu dobro​. num = int(input('Digite um número: ')) print('O dobro do número {} é {}.'.format(num, num * 2))
# Caixa Eletrônico # Desenvolva um programa que simule a entrega de notas quando um cliente # efetuar um saque em um caixa eletrônico. Os requisitos básicos são os seguintes:​ # - Entregar o menor número de notas;​ # - É possível sacar o valor solicitado com as notas disponíveis;​ # - Saldo do cliente infinito;​ # - Quantidade de notas infinito (pode-se colocar um valor finito de # cédulas para aumentar a dificuldade do problema);​ # - Notas disponíveis de R$ 100,00; R$ 50,00; R$ 20,00 e R$ 10,00​ ## Exemplos:​ # - Valor do Saque: R$ 30,00 – Resultado Esperado: # Entregar 1 nota de R$20,00 e 1 nota de R$ 10,00.​ # - Valor do Saque: R$ 80,00 – Resultado Esperado: # Entregar 1 nota de R$50,00 1 nota de R$ 20,00 e 1 nota de R$ 10,00. ​​ # Obs: Dsenvolvido por Jaqueline e Pedro notas = [100, 50, 20, 10] restoSaque, notasCem, notas50, notas20, notas10 = 0, 0, 0, 0, 0 while True: saque = int(input('Digite valor do saque: ')) notasCem = saque // 100 restoSaque = saque % 100 notas50 = restoSaque // 50 restoSaque = restoSaque % 50 notas20 = restoSaque // 20 restoSaque = restoSaque % 20 notas10 = restoSaque // 10 if notasCem > 0: print('Notas de 100 = {}'.format(notasCem)) if notas50 > 0: print('Notas de 50 = {}'.format(notas50)) if notas20 > 0: print('Notas de 20 = {}'.format(notas20)) if notas10 > 0: print('Notas de 10 = {}'.format(notas10)) if saque == 0: print('Saque indisponível') break
'''exercicio feito por David, Gabriel Rech e Gabriel Sgorla''' import random lista1 = random.sample(range(0,20),5) lista2 = random.sample(range(0,20),10) lista3 = [] print(lista1) print("----------------------------------------------------------") print(lista2) print("----------------------------------------------------------") '''for i in lista1: if i in lista2: lista3.append(i) print(lista3)''' print([i for i in lista1 if i in lista2])
"""Faça um programa para a leitura de duas notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e apresentar: A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; A mensagem "Reprovado", se a média for menor do que sete; A mensagem "Aprovado com Distinção", se a média for igual a dez.""" nota1 = float(input("Digite nota 1: ")) nota2 = float(input("Digite nota 2: ")) soma = nota1 + nota2 media = soma /2 if media>=7 and media<10: print("Aprovado,Media = ",media) elif media<7: print("Reprovado,Media = ",media) elif media ==10: print("Aprovado com Distincao,Media = ",media)
numero = int(input("Digite um numero para saber o dobro: ")) print("o dobro e: ", numero * 2)
val1 = int(input(print("Digite o primeiro valor: "))) val2 = int(input(print("Digite o segundo valor: "))) aux = 0 aux = val1 val1 = val2 val2 = aux print("Valor 1: ",val1," e valor 2: ",val2)
num = int (print (input ("Digite um número: "))) print ("O dobro do número é: "num*2)
# expresiones regulares (search, findall, split, sub) texto = "Hola, mi nombre es camila" import re resultado = re.search("camila$", texto) # devuelve match si encuentra camila$ busca si hay una frase que acabe en camila resultado = re.search("^Hola", texto) #^empieza con esa palaba en este caso hola (es sensible a mayus y min) resultado = re.search("mi.*es", texto) # ente el mi y el es hay mas caractes if(resultado): print("Coincidencia") else: print("No hubo coincidencia") # findall texto = """ el coche de luis es rojo, el coche de antonio es blanco y el coche de maria es rojo """ resultado2 = re.findall("coche.*rojo", texto) if(resultado2): print("Hay coincidencia en resultado2") else: print("No hubo coincidencia") # split => divide una cadena a partir de un patron texto = "la silla es blanca y vale 80" print(re.split("\s", texto)) # el caracter de corte es un caracter en blanco # devuelve: ['la', 'silla', 'es', 'blanca', 'y', 'vale', '80'] # sub= => sustituir coincidencias en una cadena print(re.sub("blanca", "rosa", texto)) # la silla es rosa y vale 80
class Node(): def __init__(self, data, next=None): self.data = data self.next = next class Stack(): def __init__(self, head=None): self.head = head def isEmpty(self): if self.head == None: return True else: return False def push(self, data): if self.head == None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.isEmpty(): return None else: pop_node = self.head self.head = self.head.next pop_node.next = None return pop_node.data def peek(self): if self.isEmpty(): return None else: return self.head.data def print_stack(self): print_val = self.head while print_val is not None: print(print_val.data) print_val = print_val.next def find_value(target, s): temp = Stack() target_found = False while not s.isEmpty(): if s.peek() == target: target_found = True break temp.push(s.pop()) while not temp.isEmpty(): s.push(temp.pop()) return target_found s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) s.push(5) s.print_stack() print(find_value(6, s))
def reverse_array(arr): if len(arr) == 0: return start = 0 end = len(arr)-1 while start <= end: swap(arr, start, end) start += 1 end -= 1 return arr def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr print(reverse_array([1,2,3,4,5,6]))
def find_min(arr): low = 0 high = len(arr)-1 right_pivot = arr[len(arr)-1] while low<=high: mid = low+(high-low)//2 if (arr[mid]<=right_pivot) and (mid==0 or arr[mid-1] > arr[mid]): return mid elif arr[mid] > right_pivot: low = mid+1 else: high = mid-1 return -1 print(find_min([7,8,1,2,3,4,5,6]))
def sort_subarray(arr): minimum = 0 maximum = float("inf") if len(arr) == 0: return 0 #Find Dip for start in range(0, len(arr)): if arr[start+1] > arr[start]: break if start == len(arr)-1: return #Find rise for end in range(len(arr)-1, 0, -1): if arr[end-1] > arr[end]: break for k in range(start, end+1): if arr[k] > maximum: maximum = arr[k] if arr[k] < minimum: minimum = arr[k] while start > 0 and arr[start-1] > minimum: start -= 1 while end < len(arr)-1 and arr[end+1] < maximum: end += 1 return start, end print(sort_subarray([1,2,4,5,3,5,6,7]))
mnemonics_dict = { 0:[], 1:[], 2:["a","b","c"], 3:["d","e","f"], 4:["g","h","i"], 5:["j","k","l"], 6:["m","n","o"], 7:["p","q","r","s"], 8:["t","u","v"], 9:["w","x","y","z"], } def mnemonics(arr, buff, next_index, buff_index): #termination case if buff_index==len(buff) or next_index==len(arr): print(buff[:buff_index]) return letter = mnemonics_dict[arr[next_index]] #check if the list is empty if len(letter)==0: mnemonics(arr, buff, next_index+1, buff_index) #find the candidate to place in buffer for l in letter: buff[buff_index] = l mnemonics(arr, buff, next_index+1, buff_index+1) mnemonics([0,2,3],[0,0,0],0,0) print("=====new_set====") mnemonics([4,5,7],[0,0,0], 0, 0)
def print_combination(a, buff, start_index, buff_index): #terminatio case if buff_index==len(buff): print(buff) return if start_index==len(a): return for i in range(start_index, len(a)): buff[buff_index] = a[i] print_combination(a, buff, i+1, buff_index+1) print_combination([1,2,3,4,5,6], [0,0,0], 0, 0)
def reverse_array(arr): if len(arr) == 0 or arr==None: return -1 start=0 end = len(arr)-1 while start<=end: swap(arr, start, end) start += 1 end -= 1 return arr def swap(arr, start, end): temp = arr[start] arr[start] = arr[end] arr[end] = temp return arr print(reverse_array([1,2,3,4,5]))
def min_path_sum(arr): m = len(arr) n = len(arr[0]) for i in range(1, m): arr[i][0] += arr[i-1][0] for j in range(1, n): arr[0][j] += arr[0][j-1] for i in range(1, m): for j in range(1, n): arr[i][j] += min(arr[i-1][j] , arr[i][j-1]) return arr[-1][-1] print(min_path_sum([[1,3,1],[1,5,1],[4,2,1]])) print(min_path_sum([[1,2,3],[4,5,6]]))
def hascycle(l): slow = l.head fast = l.head while fast is not None: fast = fast.get_next() if fast==slow: return True if fast is not None: fast = fast.get_next() if fast==slow: return True slow = slow.get_next() return False class Node: def __init__(self, data, next=None): self.data = data self.next = next def set_data(self, item): self.data = item def get_data(self): return self.data def set_next(self, node): self.next = node def get_next(self): return self.next class LinkedList: def __init__(self, head=None, tail=None): self.head = head self.tail = tail def get_head(self): return self.head def set_head(self, head): self.head = head def get_tail(self): return self.tail def set_tail(self, tail): self.tail = tail def append(self, append_node): if self.head == None: self.head = append_node else: self.tail = self.tail.set_next(append_node) self.tail = append_node def delete_node(self, toDelete, prev): if toDelete is None: return if self.head == toDelete: self.head = toDelete.get_next() if self.tail == toDelete: self.tail = prev if prev is not None: prev.next = toDelete.next def delete_without_prev(self, toDelete): next = toDelete.get_next() if next is None: return toDelete.set_data(next.get_data()) self.delete_node(next, toDelete) node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6) node7 = Node(7) list_data = LinkedList() list_data.head = node1 node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node3 print(hascycle(list_data))
def countigous_subarray_sort(arr): if len(arr)==0 or arr==None: return -1 for start in range(0, len(arr)): if arr[start]>arr[start+1]: break if start == len(arr): return -1 for end in range(len(arr)-1, -1, -1): if arr[end-1] < arr[end]: break min_val = float("inf") max_val = float("-inf") for k in range(start, end+1): if arr[k] < min_val: min_val = arr[k] if arr[k] > max_val: max_val = arr[k] while start > 0 and arr[start-1] > min_val: start -= 1 while end < len(arr)-1 and arr[end+1] < max_val: end += 1 return start,end print(countigous_subarray_sort([1,3,5,2,6,4,7,8,9]))
def binary_search_cyclic(a): low = 0 high = len(a)-1 right = a[len(a)-1] while(low <=high): mid = low+(high-low)//2 if (a[mid] <= right) and (mid==0 or a[mid-1]>a[mid]): return mid elif a[mid] > right: low = mid+1 else: high = mid-1 return -1 print(binary_search_cyclic([4,5,6,1,2,3]))
def print_permutation(arr, k): if len(arr)==0 or arr==None or k==None: return isinBuffer = [False]*len(arr) buff = [0]*k print_permutation_helper(arr, buff, 0, isinBuffer) def print_permutation_helper(arr, buff, buffer_index, isinBuffer): #termination case if buffer_index == len(buff): print(buff[:buffer_index]) return #find candidates for i in range(0, len(arr)): if not isinBuffer[i]: buff[buffer_index] = arr[i] isinBuffer[i] = True print_permutation_helper(arr, buff, buffer_index+1, isinBuffer) isinBuffer[i] = False print_permutation([1,2,3,4,5,6],3)
class StackAsQueue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def flushtos2(self): while not self.s1.isEmpty(): self.s2.push(self.s1.pop()) def enqueue(self, a): self.s1.push(a) def dequeue(self): if self.s2.isEmpty(): self.flushtos2() if self.s2.isEmpty(): raise("s2 is empty") return self.s2.pop() class Node: def __init__(self, data, next=None): self.data = data self.next = next class Stack: def __init__(self, head=None): self.head =head def isEmpty(self): if self.head == None: return True else: return False def push(self, item): if self.head == None: self.head = Node(item) else: new_node = Node(item) new_node.next = self.head self.head = new_node def pop(self): if self.isEmpty(): return pop_node = self.head self.head = self.head.next pop_node.next = None return pop_node.data def peek(self): if self.isEmpty(): return return self.head.data def print_stack(self): print_val = self.head while print_val is not None: print(print_val.data) print_val = print_val.next q = StackAsQueue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.dequeue()
def longest_palindrome(s): if len(s)%2==0: val = check_even_palindrome(s) else: val = check_odd_palindrome(s) return val def check_odd_palindrome(s): longest = 1 for i in range(len(s)): offset = 0 while isvalid(s[i], i-1-offset) and isvalid(s[i], i+1+offset) and (s[i-1-offset]==s[i+1+offset]): offset += 1 longestati = offset*2+1 if longest<longestati: longest = longestati r return (i-1-offset,i+1+offset) def check_even_palindrome(s): longest = 1 for i in range(len(s)): offset = 0 while isvalid(s[i], i-offset) and isvalid(s[i], i+1+offset) and (s[i-offset]==s[i+1+offset]): offset += 1 longestati = offset*2 if longest<longestati: longest = longestati return (i-offset,i+1+offset) def isvalid(s, i): return i>=0 and i<len(s) print(longest_palindrome("ab​babab​aab"))
class Node: def __init__(self, data, next=None): self.data = data self.next = next def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next def set_next(self, node): self.next = node class LinkedList(): def __init__(self, head=None, tail=None): self.head = head self.tail = tail def get_head(self): return self.head def set_head(self, head): self.head = head def get_tail(self): return self.tail def set_tail(self, tail): self.tail = tail def append(self, append_value): if self.head is None: self.head = append_value else: self.tail = self.tail.set_next(append_value) self.tail = append_value def delete_node(self, toDelete, prev): if toDelete is None: return if toDelete == self.head: self.head = toDelete.get_next() if toDelete == self.tail: self.tail = prev if toDelete is not None: prev.next = toDelete.next def delete_without_prev(self, toDelete): next = toDelete.get_next() if next is None: return toDelete.set_data(next.get_data()) self.delete_node(next, toDelete) def get_median(self): slow = self.head fast = self.head while fast.get_next() is not None: fast = fast.get_next() if fast.get_next() is None: break fast = fast.get_next() slow = slow.get_next() return slow def reverse_link_list(self, head): prev = None curr = self.head while curr is not None: next = curr.get_next() curr.set_next(prev) prev = curr curr = next return prev def isPalindrome(self): median = self.get_median() last = self.reverse_link_list(median) start = self.head end = last while start is not None and end is not None: if start.get_data() != end.get_data(): return False start = start.get_next() end = end.get_next() return True node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("B") node5 = Node("C") list_data = LinkedList() list_data.head = node1 node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 print(list_data.isPalindrome())
def isBalanced(root): if root==None: return 0 rightH = isBalanced(root.right) leftH = isBalanced(root.left) if rightH==-1 and leftH==-1: return -1 if abs(rightH)-abs(leftH) > 1: return -1 return 1+max(rightH, leftH) def is
def square_root(num): low = 0 high = num//2 while low<=high: mid = low + (high-low)//2 if mid*mid > num: high = mid-1 elif mid*mid < num: if (mid+1)*(mid+1) > num: return mid low = mid + 1 else: return mid return -1 print(square_root(36))
def prime_num(n): l1=[2] for i in range(3,10,2): l1.append(i) for i in l1: if n%i==0: return False return True def main(): n=eval(input("Enter the number:")) result=prime_num(n) print (result) main()
''' PROBLEM MAKING_ANAGRAMS Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not. Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number? ''' import math import os import random import re import sys from collections import Counter # Complete the makeAnagram function below. def makeAnagram(a, b): count = 0 count_a = Counter((a)) count_b = Counter((b)) l = [] for i in count_a.keys(): count += abs(count_a[i]-count_b[i]) l.append(i) for j in count_b.keys(): if j not in l: count += abs(count_b[j]-count_a[j]) return count a = input("Enter String 1 \n") b = input("Enter String 2 \n") res = makeAnagram(a, b) print("The number of deletions required is", res, '\n')