blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c528ece8650c68ce80f1141af1f1903ef7e1ed70
ccrain78990s/Python-Exercise
/0317 資料定義及字典/0317-2-list資料定義.py
2,076
4.34375
4
#0317 CH7 資料定義 print("===append===") list1=[3,1,2] print(list1) list1.append(100) #<----添加資料到陣列最後面 print(list1) list1.append(2197) print(list1) print("===extend===") list2=[2,1,3] print(list2) list2.extend([10]) #<----添加 " 矩陣 " 資料到陣列最後面 print(list2) list2.extend([21,97]) print(list2) print("===insert===") list3=[3,1,2] print(list3) list3.insert(2,3) #<----添加資料到指定位置 insert(指定位置,資料) print(list3) list3.insert(1,5) #try 寫出 [3,5,1,3,2] print(list3) #[3,1,2,5,1,3,2] 同時加入1,2 # 方法1: list3.insert(1,1) list3.insert(2,2) print(list3) # 方法2: # for x in [2,1]: # list3.insert(1,2) # or # y=[1,2] # for x in y.reverse(): # list3.insert(1,x) print("===remove===") list4=[3,1,2] print(list4) list4.remove(2) #<----移除指定資料 print(list4) list4.remove(1) print(list4) # 延伸: 移除所有的1 list5=[3,1,2,1] len(list5) x=0 while x<len(list5): list5.remove(1) x=x+1 print(list5) print("===pop===") list6=[3,1,2,1] print(list6) x=list6.pop() #<----取得和刪除最後的資料 print(x) print(list6) list6.pop() #<----再做一次會怎樣呢????思考看看 print(list6) print("===clear===") list7=[3,1,2,1] print(list7) list7.clear() #<----刪除所有的資料 print(list7) print("===index===") list8=[3,1,2,1] print(list8) print(list8.index(1)) #<----找第一個符合資料的位置 print(list8.index(2)) print(list8.index(3)) print("===count===") list9=[3,1,2,1] print(list9) x=list9.count(1) #<----查詢某項資料出現的次數 print(x) print("===sort===") list10=[3,1,2,1] print(list10) list10.sort() #<----順序排列資料 print(list10) print("===reverse===") list11=[1,2,3,4] print(list11) list11.reverse() #<----反轉資料 print(list11) print("===copy===") list12=[1,2,3] print(list12) list13=list12.copy() # copy 複製 *注意 print(list13)
false
716d36f828edf84625bcaceec67f7a5d0d024815
jwhitenews/computers-mn
/tk/Snowmobiles.py
1,761
4.15625
4
import sqlite3 from tkinter import * def create_table(): #connect to db conn = sqlite3.connect("lite.db") #create cursor object cur = conn.cursor() #write an SQL query cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER , price REAL )") #commit changes conn.commit() #close connection to db conn.close() def insert(item, quantity, price): #connect to db conn = sqlite3.connect("lite.db") #create cursor object cur = conn.cursor() #write an SQL query cur.execute("INSERT INTO store VALUES (?,?,?)", (item,quantity,price)) #commit changes conn.commit() #close connection to db conn.close() def view(): # connect to db conn = sqlite3.connect("lite.db") # create cursor object cur = conn.cursor() # write an SQL query cur.execute("SELECT * FROM store") #fetch data rows = cur.fetchall() # close connection to db conn.close() #return what was fetched return rows def delete(item): # connect to db conn = sqlite3.connect("lite.db") # create cursor object cur = conn.cursor() # write an SQL query cur.execute("DELETE FROM store WHERE item=?", (item,)) # commit changes conn.commit() # close connection to db conn.close() #return what was fetched return rows def update(quantity,price,item): # connect to db conn = sqlite3.connect("lite.db") # create cursor object cur = conn.cursor() # write an SQL query cur.execute("UPDATE store SET quantity=?, price=? WHERE item=?",(quantity,price,item)) # commit changes conn.commit() # close connection to db conn.close() update(11,6,"Water Glass") print(view())
true
884ee0304f568e8137f23722bba533df504703d3
DsDoctor/Basic-python-program
/Offer/q3_duplicate_nums.py
2,027
4.125
4
""" 在一个长度为n的数组里的所有数字都在0~n-1范围内。数组中某些数字是重复的, 但不知道有个数字重复了,也不知道每个数字冲了了几次。 请找出数组中任意一个重复的数字。 例如输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是重复的数字2或者3。 """ import doctest def q3_1(lis): """ >>> q3_1([2,3,1,0,2,5,3]) 2 >>> q3_1([]) Empty List! >>> q3_1([2, 2, 2, 2, 2]) 2 >>> q3_1([3, 2, 3]) Length Error! >>> q3_1(['a']) Invalid Input! >>> q3_1([0, 1, 2, 3]) no duplicate nums """ if not len(lis): print(f'Empty List!') return None hash_list = [-1] * len(lis) for i in lis: try: if hash_list[i] == -1: hash_list[i] = i else: return i except IndexError: print(f'Length Error!') return None except TypeError: print(f'Invalid Input!') return None print(f'no duplicate nums') return None def q3_2(lis): """ >>> q3_2([2,3,5,4,3,2,6,7]) 2 >>> q3_2([]) Empty List! >>> q3_2([2, 2, 2, 2, 2]) 2 >>> q3_2([3, 2, 3]) Length Error! >>> q3_2(['a']) Invalid Input! >>> q3_2([0, 1, 2, 3]) no duplicate nums """ if not len(lis): print(f'Empty List!') return None try: for i in range(len(lis)): while lis[i] != i: if lis[i] == lis[lis[i]]: return lis[i] x = lis[i] y = lis[x] lis[i] = y lis[x] = x i = lis.index(y) print(f'no duplicate nums') return None except IndexError: print(f'Length Error!') return None except TypeError: print(f'Invalid Input!') return None if __name__ == '__main__': if not doctest.testmod().failed: print(f'Well Done!')
false
5ff39f24214038947d4da34accd9dcc9b6db1ba8
Worros/2p2-Euler-Project
/problem-1/Sorrow/solution.py
473
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Problem 1 # # If we list all the natural numbers below 10 that are multiples of 3 or 5, we # get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. i = 3 MAX = 1000 max_count = MAX - 1 trees = set() fives = set() while i <= max_count: if i%3 == 0: trees.add(i) if i%5 == 0: fives.add(i) i += 1 both = trees | fives print sum(both)
true
91071429cfce206297f39f3a2d7f485d6f5bcf65
brenddesigns/learning-python
/_ 11. Dictionaries/dictionaries.py
858
4.28125
4
# Project Name: Dictionaries # Version: 1.0 # Author: Brendan Langenhoff (brend-designs) # Description: Using the Dictionary data type which is similar to arrays, but works with keys and values instead of indexes. # Define an empty Dictionary phonebook = {} # Storing values using specific keys, so we may retrieve them later using these keys phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 # Print all keys and values of defined Dictionary print(phonebook) # Iterating over Dictionaries for name, number in phonebook.items(): print("Phone number of %s is %d" % (name, number)) # Removing a value from a Dictionary del phonebook["John"] # Remove the value which has the key "John" # Removing a value can also be done via the .pop function: # phonebook.pop("John") print(phonebook) # Re-print after removing a value
true
6f4ecce8aeddcb4bbfe6c115eeb52022d85741f2
sarohan/project_euler
/3-largest-prime-factor.py
371
4.125
4
def prime_factors(n): i = 2 factors = [] while i*i <= n: if n % i : i = i+1 else: n = n // i factors.append(i) if n > 1: factors.append(n) return factors def accept(): num = int(input("Enter number to find prime factor : ")) print("Prime factor is : ", prime_factors(num)) accept()
false
cfb0ed3a10794d7c2fa82e2669523b595e49d3ab
ugwls/PRACTICAL_FILE
/5.py
1,010
4.21875
4
# Count and display the number of vowels, # consonants, uppercase, lowercase characters in string def countCharacterType(s): vowels = 0 consonant = 0 lowercase = 0 uppercase = 0 for i in range(0, len(s)): ch = s[i] if ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')): if ch.islower(): lowercase += 1 if ch.isupper(): uppercase += 1 ch = ch.lower() if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): vowels += 1 else: consonant += 1 print("Vowels:", vowels) print("Consonant:", consonant) print("LowerCase:", lowercase) print("UpperCase:", uppercase) k = True while k == True: s = input('Enter a string: ') countCharacterType(s) option = input('Do you want to try again.(y/n): ').lower() if option == 'y': continue else: k = False
true
25baca22cd8baab76c4511dc09e631f0ecd4b662
ugwls/PRACTICAL_FILE
/21.py
415
4.3125
4
# WAP to input employee number and name for ‘N’ # employees and display all information in ascending # order of their employee number n = int(input("Enter number of Employee: ")) emp = {} for i in range(n): print("Enter Details of Employee No.", i+1) Empno = int(input("Employee No: ")) name = input("Name: ") emp[Empno] = name ascending = list((emp.items())) ascending.sort() print(ascending)
true
21a79559ef6a4ec719b68c5d690eddc9e5e83160
ugwls/PRACTICAL_FILE
/35.py
2,083
4.1875
4
# Write a menu driven program to add and manipulate data # from customer.csv file. Give function to do the following: # 1.Add Customer Details, 2.Search Customer Details # 3.Remove Customer Details # 4.Display all the Customer Details, 5.Exit import csv def add(): with open('customer.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(["Cus_no", "C_name"]) n = int(input('Enter how many Customer you want to insert: ')) for _ in range(0, n): cus_no = int(input('Enter Customer ID: ')) cus_name = input('Enter Customer Name: ') info = [cus_no, cus_name] writer.writerow(info) def display(): with open('customer.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) def search(): data = [] with open('customer.csv', 'r') as f: reader = csv.reader(f) for row in reader: data.append(row) id = input('Enter customer ID to search info: ') for i in data: if i[0] == id: print(f'Customer no. {i[0]} and Name is {i[1]}') def remove(): data = [] new_data = [] with open('customer.csv', 'r') as f: reader = csv.reader(f) for row in reader: data.append(row) print(data) name = input('Enter customer name to delete info: ') with open('customer.csv', 'w', newline='') as f: f.truncate(0) for i in data: if i[1] != name: new_data.append(i) writer = csv.writer(f) writer.writerows(new_data) k = True while k == True: print(''' 1.Add Customer Details 2.Search Customer Details 3.Remove Customer Details 4.Display all the Customer Details 5.Exit ''') option = int(input('Enter your option(1/5): ')) if option == 1: add() elif option == 2: search() elif option == 3: remove() elif option == 4: display() elif option == 5: k = False else: print("Invalid Option!") continue
true
8196c34bf0cf65826cbd5af81f712f2980577a92
ugwls/PRACTICAL_FILE
/4.py
523
4.125
4
# Compute the greatest common divisor and least # common multiple of two integers. def gcd(x, y): while y > 0: x, y = y, x % y return x def lcm(x, y): lcm = (x*y)//gcd(x, y) return lcm k = True while k == True: x = int(input('Enter a number: ')) y = int(input('Enter a number: ')) print(f'The GCD is {gcd(x, y)}') print(f'The LCM is {lcm(x, y)}') option = input('Do you want to try again.(y/n): ').lower() if option == 'y': continue else: k = False
true
6fb0b3831d5b56eb05d39b30df7b4634a091eb8a
maxxymuch/gbpy20
/les01/hw03.py
1,076
4.3125
4
# Урок 1. Введение в алгоритмизацию и реализация простых алгоритмов на Python # 3. По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки. while (1): first_point = input('Введите через запятую координаты x,y первой точки : ') second_point = input('Введите через запятую координаты x,y второй точки: ') first_point = first_point.split(',') second_point = second_point.split(',') try: x1 = float(first_point[0]) x2 = float(second_point[0]) y1 = float(first_point[1]) y2 = float(second_point[1]) print(f'Уранение прямой вида y=kx+b: y = {(y2 - y1) / (x2 - x1)}x + {(x2 * y1 - x1 * y2) / (x2 - x1)}') break except: print('Неверный ввод или значения') continue
false
faa07e9618a4d07bc4ad932f63d0f6ea9989d167
maxxymuch/gbpy20
/les01/hw01.py
2,503
4.3125
4
# Урок 1. Введение в алгоритмизацию и реализация простых алгоритмов на Python # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. ################################## Вариант 1 ######################################### while (1): try: user_input = int(input('Введите трехзначное число: ')) user_input = str(user_input) if len(user_input) == 3: break else: print('Вы ввели отличное число символов от 3') except: print('Ошибка формата ввода') print(f'Суммм цифр числа {user_input}: {int(user_input[0]) + int(user_input[1]) + int(user_input[2])}') print(f'Произведение цифр {user_input}: {int(user_input[0]) * int(user_input[1]) * int(user_input[2])}') print(f'\n') ################################## Вариант 2 ######################################### while (1): try: x = int(input('Введите трехзначное число: ')) num1 = x % 10 x = x // 10 num2 = x % 10 num3 = x // 10 num4 = num3 % 10 if (num1 != 0 and num2 != 0 and num3 != 0 and num4 == num3): break else: print('Вы ввели отличное число символов от 3') except: print('Ошибка формата ввода') print(f'Сумма: {num1 + num2 + num3}, ' f'\nПроизведение: {num1 * num2 * num3}') print(f'\n') ################################## Вариант 3 ######################################### while (1): try: user_input = int(input('Введите трехзначное число: ')) user_input = str(user_input) if len(user_input) == 3: break else: print('Вы ввели отличное число символов от 3. Лишние символы отбрасываются') user_input = (user_input[0:3]) break except: print('Ошибка формата ввода') print(f'Суммм цифр числа {user_input}: {int(user_input[0]) + int(user_input[1]) + int(user_input[2])}') print(f'Произведение цифр {user_input}: {int(user_input[0]) * int(user_input[1]) * int(user_input[2])}')
false
0da6d8a6bb0c7b06615a622583759ca646112f7f
motoko2045/python_masterclass
/f_strings.py
447
4.1875
4
# you cannot concatenate a string and a number # in comes f strings (you don't have to use the format function) greeting = "oy!" age = 23 name = "charlie" print(age) print(type(greeting)) print(type(age)) age_in_words = "2 years" print(name + f" is {age} years old") print(type(age)) print(f"Pi is approximately {22 / 7:12.50f}") # extra formatting # no variable name, we just used an expression pi = 22 / 7 print(f"Pi is approximately {pi}")
true
c93e5d825a3e7a5d94dca656b4c9e22dacf7bba0
motoko2045/python_masterclass
/s3_lecture2.py
1,328
4.40625
4
# escape character portion of lecture splitString = "this string has been\nsplit over\nseveral\nlines" print(splitString) # note the \n for new line between words tabbedStr = "1\t2\t3\t4\t5" print(tabbedStr) # using the escape to use only one type of quote print('the pet shop owner said "no, no, he\'s uh, ... he\'s resting".') print("the pet shop owner said \"no, no, he's uh, ... he's resting\".") print("""the pet shop owner said "no, no, he's uh, ... he's resting". """) # python knows that everything is a string inside of the triple quotes # using triple quotes is also how to make one string span multiple lines. print("""this string has been split over several lines """) # you can use the back slash to escape the end of the line when using triple quotes print("""this string has been \ split over \ several \ lines """) # print("C:\Users\\noname\\notes.txt") # you have to escape the backslash # so that it doesnt' think the N in noname isn't a new line age = 24 print(age) name= 'charlie' # you can have multiple arguments for the function print print('hello ' + name) print('hello ',name, age) # you cannot concatenate strings and numbers! # think of values having a type, not a variable because you can reassign # a variable to a different value of a different type. print(type(name)) print(type(age))
true
4d17f656c66cda50889096e334b0887a4f1cd21c
glingden/Machine-Learning
/Regression_line_fit.py
2,844
4.21875
4
"""" Authur: Ganga Lingden This is a simple demonstration for finding the best regression line on the given data points. This code provides 2d interative regression line plot. Given equation: y = ax + b. After solving the derivatives of the loss function- MES w.r.t 'a' and 'b', the value of 'a' and 'b' are found as follows: a = ∑𝑖=1-𝑁(x𝑖y𝑖−x𝑖y¯)/∑𝑖=1-𝑁(x𝑖2−x𝑖x¯) and, b =y¯− ax¯ """ # import necessary libraries import numpy as np import matplotlib.pyplot as plt # function to calculate 'a' and 'b' in y = ax + b def my_linearfit(x, y): """ :param x(ndarray): x-values/feature vectors :param y(ndarray): y-values/prediton values :return a and b: weight/slope and bias/intercept respectively """ sum_xy = (x * y).sum() sum_x = x.sum() mean_y = y.mean() sum_xx = (x ** 2).sum() mean_x = x.mean() # a and b after derivatives a = (sum_xy - (sum_x * mean_y)) / (sum_xx - (sum_x * mean_x)) b = mean_y - a * mean_x return a, b # mouse click event function def onclick(event): """This function requires at least two data points to find the best fit regression line""" global count # right button click if str(event.button) == 'MouseButton.RIGHT': # Incase first click is 'right button' if count < 2: print('Click left mouse button to plot data points') else: fig.canvas.mpl_disconnect(cid) # Disconnect callback id 'cid' a, b = my_linearfit(np.array(x_coordinates), np.array(y_coordinates))# call my_linearfit function print('Best fit line: a = {}, and b = {} '.format(a,b)) # print a and b plt.plot(np.array(x_coordinates), a*np.array(x_coordinates)+b, '-r')# plot regression line fig.canvas.draw() # show in figure # left button click if str(event.button) == 'MouseButton.LEFT': count += 1 x_coordinates.append(event.xdata)# append x-value y_coordinates.append(event.ydata)# append y-value plt.plot(event.xdata, event.ydata, '*') # mark '*' in fig fig.canvas.draw() # show fig if __name__ == "__main__": x_coordinates = [] # store x-coordiantes y_coordinates = [] # store y-coordiantes count = 0 #count clicks # setup figure fig = plt.figure() ax = fig.add_subplot() # sub-plot ax.set_xlim([0, 15]) # set x-limit of the current axes ax.set_ylim([0, 15]) # set x-limit of the current axes plt.xlabel('x-values') # set xlabel plt.ylabel('y-values') # set ylabel plt.title('Regression Line Fit: Click on figure\n(left click = data plot, and right click = regression line)') # set title # connect mouse click event and return connection id cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() #show figure
true
df62030a1249a201a21335ab9f94006bfac6463f
Sarefx/Dates-and-Times-in-Python
/Let's Build a Timed Quiz App/time_machine.py
1,424
4.25
4
# my solution to the Simple Time Machine challenge/exercise in Let's Build a Timed Quiz App # the challenge: Write a function named delorean that takes an integer. Return a datetime that is that many hours ahead from starter. import datetime starter = datetime.datetime(2015, 10, 21, 16, 29) def delorean(integer): future_time = starter + datetime.timedelta(hours=integer) return future_time # the challenge is solved # the challenge: Write a function named time_machine that takes an integer and a string of "minutes", "hours", "days", or "years"... # ... This describes a timedelta. Return a datetime that is the timedelta's duration from the starter datetime. import datetime starter = datetime.datetime(2015, 10, 21, 16, 29) # Remember, you can't set "years" on a timedelta! # Consider a year to be 365 days. ## Example # time_machine(5, "minutes") => datetime(2015, 10, 21, 16, 34) def time_machine(integer, string): if string == "minutes": new_starter = starter + datetime.timedelta(minutes=integer) pass elif string == "hours": new_starter = starter + datetime.timedelta(hours=integer) pass elif string == "days": new_starter = starter + datetime.timedelta(days=integer) pass elif string == "years": new_starter = starter + datetime.timedelta(days=integer * 365) pass return new_starter # the challenge is solved
true
97d0d2120b76fc91f4dc0124e7608ba070b85076
AdamC66/01---Reinforcing-Exercises-Programming-Fundamentals
/fundamentals.py
1,377
4.40625
4
import random # from random import randrange # Exercise 1 # Create an emotions dict, where the keys are the names of different human emotions and the values are the degree to which the emotion is being felt on a scale from 1 to 3. # Exercise 2 # Write a Person class with the following characteristics: # name (string) # emotions (dict) # Initialize an instance of Person using your emotions dict from exercise 1. # Exercise 3 # Add an instance method to your class that displays a message describing how the person is feeling. Substitute # the words "high", "medium", and "low" for the emotion levels 1, 2, and 3. emotions={ 'happy':[1,2,3], 'sad':[1,2,3], 'angry':[1,2,3], 'elated':[1,2,3], 'malaise':[1,2,3], 'depressed':[1,2,3], 'upset':[1,2,3], 'excited':[1,2,3] } class Person: def __init__(self,name, emotion): self.name = name self.emotion = emotion def message(self): return(f'{self.name} is feeling {self.emotion_level()} {self.rand_emotion()} today') def emotion_level(self): x = random.randrange(3) if x == 0: return "a little" elif x==1: return "somewhat" elif x==2: return "very" def rand_emotion(self): return(random.choice(list(self.emotion.keys()))) adam = Person('Adam', emotions) print(adam.message())
true
fd5a819c0ff4c27e929adcae1dac025d87c45d5c
sunjinshuai/Python
/Code/nested_loop.py
568
4.15625
4
# Python 语言允许在一个循环体里面嵌入另一个循环。 # Python for 循环嵌套语法: # for iterating_var in sequence: # for iterating_var in sequence: # statements(s) # statements(s) # Python while 循环嵌套语法: # while expression: # while expression: # statement(s) # statement(s) # 以下实例使用了嵌套循环输出2~100之间的素数: i = 2 while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j) : print i, " 是素数" i = i + 1 print "Good bye!"
false
d0bbea6d2de955a86244d220f6d2a1ff7c659004
ashish-bisht/must_do_geeks_for_geeks
/stack/python/parentheseis.py
485
4.1875
4
def valid_parentheses(string): stack = [] brackets = {"(": ")", "{": "}", "[": "]"} for ch in string: if ch not in brackets: if not stack: return False cur_bracket = stack.pop() if not brackets[cur_bracket] == ch: return False else: stack.append(ch) return not stack print(valid_parentheses("()[]{}")) print(valid_parentheses("()[]{")) print(valid_parentheses("})"))
true
6a9b1f3952572d73b05af1e42cb948906234a816
karam-s/assignment_1
/Q2.py
460
4.125
4
while 1: decimal_num = int(input("enter a decimal numbe: ")) pout=decimal_num if decimal_num==-1: break binary_num = [] while decimal_num!=0: y= decimal_num %2 binary_num.append(y) decimal_num=decimal_num//2 binary_num.reverse() print ("the binary number of the "+str(pout)+" \ is: "+"".join([str(i) for i in binary_num])) print ("to break the loop enter -1")
false
490c73c4444ccdcbbe02b825d0bbe159264fc9e2
karam-s/assignment_1
/Q1-E.py
345
4.1875
4
L=["Network" , "Math" , "Programming", "Physics" , "Music"] length = [] for i in L: x =len(i) length.append(x) the_longest_item=max(length) the_index_for_the_longest_item=length.index(the_longest_item) print ("the longest item in list is "+str(L[the_index_for_the_longest_item])+"\ And its length "+str(the_longest_item))
true
6ee7ed7a04cfcb5325f58bf60d4ad2fd367f6860
Naganandhinisri/python-beginner
/hacker_rank/palindrome.py
233
4.28125
4
word = "12345" new_word = "54321" sorted_word = sorted(word) new_sorted_word = sorted(new_word) if sorted_word == new_sorted_word: print('the given string is palindrome') else: print('The given string is not palindrome')
true
4920a9b8776f24f142025fcd3d50170a2fd21f65
Naganandhinisri/python-beginner
/test3/sorted_number.py
337
4.125
4
def sort_numbers(): number = "687" sorted_number = ''.join(sorted(number)) rev_sorted_number = ''.join(reversed(number)) if number == sorted_number: return 'Ascending Order' elif sorted_number == rev_sorted_number: return 'descending order' else: return 'neither' print(sort_numbers())
true
7bd1794f73990e131743cf4ea47cd86d51f9b893
Chanchal1603/python-gs-eop
/day-2/create-container.py
752
4.40625
4
""" A professor asked Lisha to list up all the marks in front of her name but she doesn't know how to do it. Help her to use a container that solves this problem. Input Format First line of input contains name Next three lines contains marks of a student in three subjects. Constraints type(marks) = int Output Format Print the container which contains the name and all the marks and can be accessed easily NOTE: Use the variable name to store name and varibale marks to store the marks Sample Input 0 Lisha 98 97 99 Sample Output 0 {'name': 'Lisha', 'marks': [98, 97, 99]} """ # Solution name=input() marks=[] marks.append(int(input())) marks.append(int(input())) marks.append(int(input())) d={} d["name"]=name d["marks"]=marks print(d)
true
e4c2cbd32810a0d7d8720d6d53c27e55e738632c
theburningmonk/IntroductionToAOP
/AopDemo/AopDemo.DynamicLanguage/Demo.py
749
4.28125
4
class Person: """A simple class representing a person""" def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print "Hello, my name is {}, I'm {} years old".format(self.name, self.age) def say_goodbye(self, recipient): print "Good bye, {}".format(recipient) # create a new instance of Person and call the say_hello and say_goodbye methods person = Person("Lorenzo Von Matterhorn", 35) person.say_hello() person.say_goodbye("Ms Goat") old_say_hello = person.say_hello def new_say_hello(): print "Invoking new_say_hello" old_say_hello() print "Invoked new_say_hello" # swap out the original implementation of say_hello person.say_hello = new_say_hello person.say_hello()
false
b7f96b7a47d1b99f5a0e62e7d2979e127a7759d4
rikudo765/algorithms
/lab7/aud/7.1-4.py
1,805
4.28125
4
""" Реалізуйте підпрограми сортування масиву. """ def bubble_sort(array): """ Сортування "Бульбашкою" :param array: Масив (список однотипових елементів) """ n = len(array) for i in range(n - 1, 0, -1): for j in range(i): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] def bubble_sort_optimized(array): """ Модификований алгоритм сортування "Бульбашкою" :param array: Вхідний масив даних, що треба відсортувати. """ n = len(array) for i in range(n - 1, 0, -1): check = True for j in range(i): if array[j] > array[j + 1]: check = False array[j], array[j + 1] = array[j + 1], array[j] if check: break def selection_sort(array): """ Сортування вибором :param array: Масив (список однотипових елементів) :return: None """ n = len(array) for i in range(n - 1, 0, -1): m = 0 for j in range(1, i + 1): if array[m] < array[j]: m = j array[i], array[m] = array[m], array[i] def insertion_sort(array): """ Сортування вставкою :param array: Масив (список однотипових елементів) :return: None """ n = len(array) for i in range(1, n): cur = array[i] pos = i while pos > 0: if array[pos - 1] > cur: array[pos] = array[pos - 1] else: break pos -= 1 array[pos] = cur
false
493f7024a4af67c7cd527dc824aa596beb60f9d4
RinatStar420/programming_training
/lesson/call_twice.py
697
4.34375
4
""" Вам предстоит реализовать функцию call_twice(), которая должна принять функцию и произвольный набор аргументов для неё, вызвать функцию с заданными аргументами дважды, вернуть пару из результатов вызовов (первый, затем второй). call_twice(input, 'Enter value: ') Enter value: foo Enter value: barc ('foo', 'bar') """ def call_twice(function, *args, **kwargs): result1 = function(*args, **kwargs) result2 = function(*args, **kwargs) return result1, result2 print(call_twice(input, 'Enter value: '))
false
398b6bb3187a835deda3719fddc5520eedf6f82b
dinohadzic/python-washu-2014
/hw3/merge_sort.py
801
4.1875
4
def merge_sort(list): if len(list) <= 1: #If the length of the input is 1, simply return that value return list else: mid = len(list)/2 left = list[:mid] right = list[mid:] left = merge_sort(left) right = merge_sort(right) sorted_list = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: #Should the left be smaller than the right, append it to the list sorted_list.append(left[i]) i += 1 else: sorted_list.append(right[j]) #Should the right be smaller than the left, append it to the list j += 1 if i == len(left) or j == len(right): #If the end is reached on the left (or right), extends the list by what's remaining of the right (or left) sorted_list.extend(left[i:] or right[j:]) return sorted_list
true
7e3d9d503c9e92294fdb49f18f03399f12f60412
scottherold/python_refresher_2
/iterators.py
403
4.3125
4
# Create a list of items (you may use either strings or numbers) # then create an iterator using the iter() function. # Use a for loop to loop "n" times, where n is the number of items in # your list. Each time round the loops, use next() on your list to # to print the next item numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] number = iter(numbers) for i in range(0, len(numbers)): print(next(number))
true
9e0925d29868d5406da243e131f388c8331794d4
yanil3500/data-structures
/src/stack.py
1,022
4.25
4
""" implementation of a stack """ from linked_list import LinkedList class Stack(object): def __init__(self, iterable=None): if type(iterable) in [list, tuple, str]: self._container = LinkedList(iterable=iterable) elif iterable is None: self._container = LinkedList() else: raise TypeError('You need to use an iterable or no arguments.') def push(self, value): """ The push method on our stack uses the linked list's push function as the underlying method by which items are added onto our stack. """ self._container.push(value) def pop(self): """ The pop method on our stack uses the linked list's pop function as the underlying method by which items are removed from the stack. """ return self._container.pop() def __len__(self): """ This function definition allows for the built-in len func to be used. """ return self._container.length
true
185d672f79d2297615e67163751c153da825f113
Gloamglozer/PythonScripts
/Sixthproblem.py
1,905
4.125
4
""" LEGENDARY SIXTH PROBLEM https://www.youtube.com/watch?v=Y30VF3cSIYQ This is a quickly made script which visualizes a small grid containing solutions to the equation given in the legendary sixth problem something something vieta jumping """ from math import sqrt import numpy print("Legendary sixth problem\n") space = 2 count = 0 numbers = False grid = True x = int(input("Enter the size you would like to see\n")) if(grid): if(numbers): print(" ".rjust(space),end=" ") for k in range(0,x+1): print(str(k).rjust(space),end=" ") print(" ") for a in range(0,x+1): print(str(a).rjust(space),end=" ") for b in range(0,x+1): clark = (((a*a)+(b*b))/(a*b+1)) if(sqrt(clark).is_integer()): print(("!"+str(clark)).rjust(space),end=" ") count +=1 else: print(str(round(clark,2)).rjust(space),end=" ") print(" ") else: print(" ".rjust(space),end=" ") for k in range(0,x+1): print(str(k).rjust(space),end=" ") print(" ") for a in range(0,x+1): print(str(a).rjust(space),end=" ") for b in range(0,x+1): clark = (((a*a)+(b*b))/(a*b+1)) if(sqrt(clark).is_integer()): print(("!").rjust(space),end=" ") count +=1 else: print("x".rjust(space),end=" ") print(" ") print("\n") print(count-(2*x+1)) else: for a in range(0,x+1): for b in range(a,x+1): clark = (((a*a)+(b*b))/(a*b+1)) if(sqrt(clark).is_integer()&(a!=0)): print(str("({},{})".format(a,b)).rjust(space)) count +=1
true
a76b154bd030a73cf6c509e47f2b3dcdadfbbadf
ryhanlon/legendary-invention
/labs_Fundaments/pig-latin/pig-latin-func.py
845
4.125
4
""" This file was writting by Rebecca Hanlon Changing an English word into Pig Latin. """ def ask_word(): # asking for word word = input("Let's speak some Pig Latin! Input one word. >> ") vowels = "aeiou" # Get first letter. first_letter = word[0] if first_letter in vowels: # Cuts off first letter from word & capitalizes pig_latin_end_v = "yay" pig_latin_word = word + pig_latin_end_v print(f"Word? {word.title()} " + f"\n{word.title()} in Pig Latin is {pig_latin_word}.") elif first_letter not in vowels: # Cuts off first letter from word word_nfl = word[1:] pig_latin_end_c = "ay" pig_latin_word = word_nfl + first_letter + pig_latin_end_c print(f"Word? {word.title() } " + f"\n{word.title()} in Pig Latin is {pig_latin_word}.") ask_word()
false
97f8053fb78f12d76ea006aeb506c97112867ce9
ryhanlon/legendary-invention
/labs_Functional_Iteration/functions_2/functions_2.py
1,291
4.125
4
""" >>> combine(7, 4) 11 >>> combine(42) 42 >>> combine_many(980, 667, 4432, 788, 122, 9, 545, 222) 7765 >>> choose_longest("Greg", "Rooney") 'Rooney' >>> choose_longest("Greg", "Rooney", "Philip", "Maximus", "Gabrielle") 'Gabrielle' >>> choose_longest("Greg", [0, 0, 0, 0, 4]) [0, 0, 0, 0, 4] """ def combine(num_one, num_two=0): """ Used a default value of zero for setting the 2nd arg to optional :param num_one: int :param num_two: int :return: int """ result = num_one + num_two return result def combine_many(*fudge): """ Used *args to pass any number of integers. :param fudge: ints, multiple :return: int """ result = sum(fudge) print(result) def choose_longest(*fudge): result = max(fudge) return result # def choose_longest(*fudge): # """ # Return the longest input argument. # :param fudge: multiple args, *args # :return: strings, int, list # """ # def return_len(word): # return len(word) # # result = max(fudge, key=return_len) # # print(result) def choose_longest(*fudge): """ Return the longest input argument. :param fudge: multiple args, *args :return: strings, int, list """ result = max(fudge, key=len) return result
true
a263ae4127db5b6cccfb196958a8be667938bf86
ryhanlon/legendary-invention
/labs_Functional_Iteration/distance_converter/distance-converter.py
1,666
4.375
4
""" This file is written by Rebecca Y. Hanlon. """ # catch input errors, refactor, add additional units def converter(): input_distance = int(input("Enter distance: ")) input_unit = input("Enter units (m, km, ft, mi): ") target_unit = input("Enter target units (m, km, ft, mi): ") m_to_meters = input_unit == 'meter' or input_unit == 'm' km_to meters = input_unit == 'kilometer' or input_unit == 'km' # convert units to meter if to_meters: distance = input_distance * 1 # m to m print(distance) elif km_to meters: distance = input_distance * 1000 # km to m print(distance) elif input_unit == 'mile' or input_unit == 'mi': distance = input_distance * 1609 # mi to m print(distance) elif input_unit == 'feet' or input_unit == 'ft': distance = input_distance * .3 # ft to m print(distance) # convert input units to target units if target_unit == 'meter' or target_unit == 'm': convert_dist = distance * 1 # m to m print(f"{input_distance} {input_unit} is {convert_dist} m") elif target_unit == 'kilometer' or target_unit == 'km': convert_dist = distance * .001 # m to km print(f"{input_distance} {input_unit} is {convert_dist} km") elif target_unit == 'mile' or target_unit == 'mi': convert_dist = distance * .0006 # m to mi print(f"{input_distance} {input_unit} is {convert_dist} mi") elif target_unit == 'feet' or target_unit == 'ft': convert_dist = distance * 3.3 # m to ft print(f"{input_distance} {input_unit} is {convert_dist} ft") converter()
false
46279bcd5591db4fedaa49e964e950459732ad6e
ryhanlon/legendary-invention
/labs_Fundaments/simple_converter.py
319
4.15625
4
""" This is a file written by Rebecca Hanlon Ask for miles and then convert to feet. """ def question(miles): ''' Ask for # of miles, then converts to feet. ''' result = miles * 5280 print(f"You walk {result} feet everyday.") answer = int(input("How many miles do you walk everyday? ")) question(answer)
true
33cadac1f1ea635e2b0a1595391887ae892421dc
AndersonTorres1993/jogo-da-forca
/Aula31/aula31.py
747
4.15625
4
''' Formatando valores modificados - Aula 5 :s - Texto (strings) :d - Inteiros (int) :f - Números de ponto flutuante ( float) :.(NÚMERO)f - Quantidade de casas decimais ( float) :(CARACTERE)(>ou < ou ^) ( QUANTIDADE)( TIPO - s,d ou f) > - Esquerda < - Direita ^ - Centralizar ''' '''num_1 = 10 num_2 = 3 divisao= num_1/num_2 print(f'{divisao:.5f}') #print('{:.2f}'.format (divisao)) nome= " Anderson Avila" print(f'{nome:s}') # ta convertendo para str ''' '''num_1= 1 print(f'{num_1:0>10}') num_2 = 1122 print(f'{num_2:1f}') ''' nome = "Anderson Avila Torres" nome_formatado = '{}'.format(nome) print(nome_formatado) nome = "Anderson Avila Torres" print(nome.lower()) #tudo minusculo print(nome.upper()) # tudo maiusculo print(nome.title()) #Primeiras Letras Maisculas
false
fa927006a4537ae68cb0c52a9f158bfd05a4f00d
HanChen1988/BookExercise_02
/Chapter_07/Page_100/even_or_odd.py
553
4.28125
4
# -*- coding: utf-8 -*- # @Time : 2020/4/12 3:20 下午 # @Author : hanchen # @File : even_or_odd.py # @Software: PyCharm # ------------------ example01 ------------------ # 判断一个数是奇数还是偶数 number = input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0: # 求模运算符(%),它将两个数相除并返回余数 print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.") # ------------------ example01 ------------------
false
7234c896215dfc924ba7bbea68817de5b7df8fe9
ragavanrajan/Python3-Basics
/breakContinue.py
823
4.21875
4
student_names = ["Mike", "Bisset", "Clark","Ragavan"] # imagine if you have 1000 list in array it will not execute once the match is found for name in student_names: if name == "Bisset": print("Found him! " + name) print("End of Break program") break print("currently testing " + name) # Continue Example # Continue will work if match is found and then execute the rest student_namesnew = ["Mike", "Bisset", "Clark","Ragavan","Milan","Graeme"] # It will iterate for every single element except for Clark. Bcoz using continue keyword to skip executing the rest of the code # to continue iteration directly for namenew in student_namesnew: if namenew == "Clark": continue print("Found him Continue! " + namenew) print("currently testing-using continue " + namenew)
true
ff511ef0763e5e4616a3339185553599a642fa09
begora/apuntespython
/Ej_.varios.py
635
4.1875
4
#numero1=int(input("Introduce un número")) #numero2=int(input("Introduce otro número")) #numero3=int(input("Introduce otro")) # #def devuelveMax(): # if numero1>numero2 & numero2>numero3: # print (numero1) # elif numero2>numero1 & numero1>numero3: # print(numero2) # else: # print(numero3) # #devuelveMax() #Ejercicio 2 #name=input("Nombre") #adress=input("Dirección") #phone=input("Teléfono") # #mylist=(name,adress,phone) # #print("Los datos personales son:"+ str(mylist[:])) n1=int(input("Número 1")) n2=int(input("Número 2")) n3=int(input("Número 3")) middle=(n1+n2+n3)/3 print(middle)
false
870ecf814b003df11af879f0c0456862215060c4
pooja-pichad/dictionary
/saral4.py
800
4.375
4
# Ek program likhiye jo ki nested dictionary me se first key or value ko remove kare. # Example :- Input :- Output :- # output # Dic= { # 1: 'NAVGURUKUL', # 2: 'IN', # 3: # { 'B' : 'To', # 'C' : 'DHARAMSALA' # } # } # people= { # 1: 'NAVGURUKUL', # 2: 'IN', # 3:{ # 'A' : 'WELCOME', # 'B' : 'To', # 'C' : 'DHARAMSALA' # } # } # del people[3]['A'] # print(people) # Do lists lekar ek dictionary banaiye jisme pehli list ke elements keys ho aur dusri list ke elements unn keys ki values ho. Example :- Input :- list1=["one","two","three","four","five"] list2=[1,2,3,4,5,] a={} i=0 while i<len(list1): a[list1[i]]=list2[i] i=i+1 print(a) # i=i+1
false
29fc112780357814e8accdd1364d97e140f44245
delio1314/sort
/bubble-sort/python/bubble-sort.py
422
4.28125
4
#!/usr/bin/python #coding:utf8 def bubbleSort(list): i = 0 ordered = False while i<len(list)-2 and not ordered: ordered = True j = len(list)-1 while j > i: if list[j] < list[j-1]: ordered = False temp = list[j] list[j] = list[j-1] list[j-1] = temp j-=1 i+=1 list = [4, 1, 2, 9, 6, 5, 0, 8, 3, 7] print 'before bubble sort: ', list bubbleSort(list) print 'after bubble sort: ', list
true
36e6d43c0be830348c682e2f051b867e4cf9ace1
raioliva21/Taller-N-1
/ex07.py
1,446
4.1875
4
""" Ejercicio 7 El buen gordito” ofrece hamburguesas sencillas, dobles y triples, las cuales tienen un costo de $2000, $2500 y $3000 respectivamente. La empresa acepta tarjetas de cr ́edito con un cargo de 5 % sobre la compra. Suponiendo que los clientes adquieren solo un tipo de hamburguesa, realice un algoritmo para determinar cu ́anto debe pagar una persona por N hamburguesas. """ #se permite seleccionar unicamente un tipo de hamburguesa print("Ingrese <s> para hamburguesa sencilla ($2000 c/u)") print("Ingrese <d> para hamburguesa doble ($2500 c/u)") tipo_hamburguesa = input("Ingrese <t> para hamburguesa triple ($3000 c/u)\n") if tipo_hamburguesa == "s": costo_hamburguesa = 2000 elif tipo_hamburguesa == "d": costo_hamburguesa = 2500 elif tipo_hamburguesa == "t": costo_hamburguesa = 3000 else: print("ERROR, ingrese caracter valido") cantidad_hamburguesas = int(input("Cantidad de hamburguesas a llevar: ")) costo_total = costo_hamburguesa * cantidad_hamburguesas print("Ingrese forma de pago") print("<1> para pago con efectivo") print("<2> para pago con tarjeta de debito") tipo_pago = int(input("<3> para pago con tarjeta de credito (se adiciona cargo de 5/100 sobre la compra)\n")) #si opcion de pago es igual a 3, entonces se aplica adicion de 5% sobre el costo de pedido if tipo_pago == 3: costo_total = costo_total + (costo_total * 5/100) print("El costo de hamburguesa es de", costo_total,"pesos")
false
6a2c642ee5c77a77dca94e5360300880ce93ec9a
27fariha/Python1903F1
/ListComprehension.py
1,082
4.21875
4
#syntax : [expression(variable) for item in list] #example 1 fruits=["Apple","Banana","Watermelon","Kiwi","Cherry"] for x in fruits: print(x) # with compre new_List=[x for x in fruits] print(new_List) #Example -2 #simple letter=['A','B','C','D','E','F'] letter.append("abc") for x in 'Human': letter.append(x) print(letter) #with compre new_letter=[ a for a in 'HUMAN'] print(new_letter) #even for x in range(21): if x%2 == 0: print(x) #with compre even=[ x for x in range(51) if x%2==0] # 4/2 =0== 0 -yes print(even) #nested compre list1=[y for y in range(51) if y%2==0 if y%5==0] print(list1) #uppercase a=[x.upper() for x in fruits] print(a) #square number 2*2 , a*a d=[i*i for i in range(10)] print(d) #if else abc=[ x if x!="Banana" else "orange" for x in fruits ] print(abc) sentence="this is python language and it is used in ai" #string for i in sentence: print(i) vowel=[i for i in sentence if i in 'aeiou'] print(vowel) matrix=[ [0,0,0] , [1,1,1], [2,2,2] ] flat_matrix=[col for row in matrix for col in row] print(flat_matrix)
false
0a1c54a2598a6a04a890993e959122f053439313
nandhinik13/Sqlite
/select.py
390
4.1875
4
import sqlite3 conn = sqlite3.connect("data_movies") cur = conn.cursor() #selects the record if the actor name is ajith query = "select * from movies where actor='Ajith'" cur.execute(query) #fetchall fetches all the records which satisfies the condition data = cur.fetchall() print("type of data is :",type(data)) print("\n") print(data) cur.close() conn.close()
true
1b449bced7c40519774de41684941e1acbdcc02d
m-junaidaslam/Coding-Notes
/Python/decorators.py
2,160
4.25
4
# decorators.py # Just important attributes of object(function "add" in this case) # add : physical memory address of function # add.__module__: defined in which module # add.__defaults__: what default values it had # add.__code__.co_code: byte code for this add function # add.__code__.co_nlocals: how many local variables the function has # add.__code__.co_name: name of the function # add.__code__.co_varnames: names of the variables # More Interesting questions that can be asked from object # Get function source code # from inspect import getsource # getsource(add) # print(getsource(add)) # Get function file name # from inspect import getfile # getfile(add) from time import time # Wrapper to calculate the time elapsed when the wrapper function is called def timer(func): def f(*args, **kwargs): # *args : arguments without key values # **kwargs : arguments with key values e.g. y=10 instead of just 10 before = time() rv = func(*args, **kwargs) after = time() print('elapsed: ', after - before) return rv return f # @timer is same as "add = timer(sub)", here timer is a wrapper function # which adds to the functionality of add function # Same goes for the subtract function below @timer def add(x, y=10): return x + y @timer def sub(x, y=10): return x - y print('add(10)', add(10)) print('add(20, 30)', add(20, 30)) print('add("a", "b")', add("a", "b")) print('add(10)', sub(10)) print('add(20, 30)', sub(20, 30)) # Now lets say we want a wrapper to run function n times (just an example) def ntimes(n): def inner(f): def wrapper(*args, **kwargs): for _ in range(n): print('running {.__name__}'.format(f)) rv = f(*args, **kwargs) return rv return wrapper return inner @ntimes(4) # where 4 is the number of times we want add1 to run def add1(x, y=10): return x + y print('add1(10)', add1(10))
true
e371094c000056f90580b37925467171a4a70cb6
raj9226/rk
/sesion3a.py
210
4.28125
4
#assignment operator num1=10 #write operation /update operation num1=5 num2=num1 #copy operation/referrence copy #num1=num1+10 num1 += 5 print(num1) # *=,/=,//=,**= num1 **=2 num1 //=2 print(num1)
false
4a88628231baaef87a2cc2c333bde75cc370067b
programiranje3/2020
/python/sets.py
1,176
4.4375
4
"""Demonstrates sets """ def demonstrate_sets(): """Creating and using sets. - create a set with an attempt to duplicate items - demonstrate some of the typical set operators: & (intersection) | (union) - (difference) ^ (disjoint) """ the_beatles = {'John', 'Paul', 'George', 'Ringo'} print(the_beatles) print() # Alternatively the_beatles = ('John', 'Paul', 'George', 'Ringo') # the_beatles = ['John', 'Paul', 'George', 'Ringo'] # this is also OK; any iterable will do the_beatles = set(the_beatles) print(the_beatles) print() the_beatles.add('John') print(the_beatles) the_beatles.remove('John') print(the_beatles) print() the_beatles = {'John', 'Paul'} | {'George', 'Ringo'} print(the_beatles) the_beatles = the_beatles - {'John', 'George'} print(the_beatles) print(sorted(the_beatles)) print("{'John', 'Paul'} & {'George', 'Ringo'}:", {'John', 'Paul'} & {'George', 'Ringo'}) print("{'John', 'Paul'} ^ {'George', 'Ringo'}:", {'John', 'Paul'} ^ {'George', 'Ringo'}) print() if __name__ == '__main__': demonstrate_sets()
true
c02d56bd3bffe56f87326121d368f8a5978f7d1a
accus84/python_bootcamp_28032020
/moje_skrypty/nauka/02_funkcje/007_funkcje.py
1,796
4.15625
4
#lambda x: x.... #lambda umożliwia operacje na samym sobie kolekcja = [(10, "z"), (5, "c"), (15, "a")] #sortowanie po drugim elemencie czyli 5,10,15 def first(x): return x[0] def second(x): return x[1] #sortowanie po pierwszym elemencie czyli 5,10,15 print(first(kolekcja)) #(10, 'z') funkcja zwracająca element 0 listy kolekcja print(second(kolekcja)) #(5, 'c') funkcja zwracająca element 1 listy kolekcja print(sorted([5,7,14,-2])) #[-2, 5, 7, 14] domyślne sortowanie print(sorted(kolekcja)) #[(5, 'c'), (10, 'z'), (15, 'a')] domyślne sortowanie po elemencie 0 #sorted ma parametr key, który jest używany do wywołania jakiejś funkcji print(sorted(kolekcja, key=first)) #[(5, 'c'), (10, 'z'), (15, 'a')] sortowanie listy kolekcja według funkcji first (funkcja first zwraca element 0) print(sorted(kolekcja, key=second)) #sortowanie(co, jak) [(15, 'a'), (5, 'c'), (10, 'z')] - posortowanie po elemencie 1 czyli a c z #to samo, można rozpatrywać jako przetwórz x: tak aby pobrać element 1 x print(sorted(kolekcja, key=lambda x: x[1])) #lambda <agument który wchodzi>: <argument który wychodzi> otrzymamy (5, 'c') #inny przykład suma = lambda x, y: x + y print(suma(1, 2)) #suma 1 i 2 print((lambda x, y: x + y)(1, 2)) #suma 1 i 2 #zadanie lista_osob = ["Jan Nowak", "Anna Zagajska", "Mateusz Pospieszalski", "Piotr Baron"] print(sorted(lista_osob, key = lambda x: x.split()[1])) #split podzielił Jan Nowak itd na 2 części sortowanie po nazwisku czyli: sortowanie(lista_osob, dzielenie samego siebie i branie po uwagę elementu 1) #['Piotr Baron', 'Jan Nowak', 'Mateusz Pospieszalski', 'Anna Zagajska']
false
b9f683c78b4ab99a53b561f8268a0cc95d39776d
alshayefaziz/comp110-21f-workspace
/exercises/ex02/fortune_cookie.py
1,507
4.15625
4
"""Program that outputs one of at least four random, good fortunes.""" __author__ = "730397680" # The randint function is imported from the random library so that # you are able to generate integers at random. # # Documentation: https://docs.python.org/3/library/random.html#random.randint # # For example, consider the function call expression: randint(1, 100) # It will evaluate to an int value >= 1 and <= 100. from random import randint fortune_saying: int = int(randint(1, 4)) fortune_1: str = ("Tomorrow will be the start of a powerful new journey!") fortune_2: str = ("True love is right in front of you, you just have to open your eyes.") fortune_3: str = ("You must love yourself before you are able to love others!") fortune_4: str = ("You already know what the next step required is, you just have to take it!") print("Your fortune cookie says...") if fortune_saying == 1: print(fortune_1) else: if fortune_saying == 2: print(fortune_2) else: if fortune_saying == 3: print(fortune_3) else: print(fortune_4) print("Now, go spread positive vibes!") """At first the point of the "from random import randint" function really confused me but after messing with it for a while I understood how I could assign the randomly assigned number prdouced from a set value to my fortune_saying variable as an integer which then allowed me to immediately follow up with a nested if/else conditional statement which was pretty easy to setup."""
true
2b32a6ef5be1b97a3a5a8fb14df6929c0e1de254
alshayefaziz/comp110-21f-workspace
/lessons/data_utils.py
1,254
4.25
4
"""Some helpful utility functions for working with CSV files.""" from csv import DictReader def read_csv_rows(filename: str) -> list[dict[str, str]]: """Read the rows of a csv into a 'table'.""" result: list[dict[str, str]] = [] # Open ahandle to the data file file_handle = open(filename, "r", encoding="utf8") # Prepare to read the data file as a CSV rather than just strings csv_reader = DictReader(file_handle) # Read each row of the CSV line-by-line for row in csv_reader: result.append(row) # Close the file when we're done, to free its resources. file_handle.close() return result def column_values(table: list[dict[str, str]], column: str) -> list[str]: """Produce a list[str] of all values in a single column.""" result: list[str] = [] for row in table: item: str = row[column] result.append(item) return result def columnar(row_table: list[dict[str, str]]) -> dict[str, list[str]]: """Transform a row-oriented table to a column-oriented table.""" result: dict[str, list[str]] = {} first_row: dict[str, str] = row_table[0] for column in first_row: result[column] = column_values(row_table, column) return result
true
a0b1b9a6082b26cdb54174c9c24fa63687c5ab66
alshayefaziz/comp110-21f-workspace
/exercises/ex05/utils.py
1,614
4.21875
4
"""List utility functions part 2.""" __author__ = "730397680" def only_evens(even: list[int]) -> list[int]: """A function that returns only the even values of a list.""" evens: list[int] = list() if len(even) == 0: return evens i: int = 0 while i < len(even): item: int = even[i] if item % 2 == 0: evens.append(item) i += 1 return evens def sub(sup: list[int], start: int, end_minus_one: int) -> list[int]: """A function that takes a list and produces a subset of the list which contains all items from start index to end index -1.""" sublist: list[int] = list() if start < 0: start = 0 if end_minus_one > len(sup): end_minus_one = len(sup) - 1 else: end_minus_one = end_minus_one - 1 if len(sup) == 0 or start > len(sup) or end_minus_one <= 0: return sublist while start <= end_minus_one: item: int = sup[start] sublist.append(item) start += 1 return sublist def concat(first_list: list[int], second_list: list[int]) -> list[int]: """A function that takes two lists and generates a new list which contains all of the items from the firs tlist followed by all of the items in the second list.""" concatenated: list[int] = list() i: int = 0 if len(first_list) > 0: while i < len(first_list): concatenated.append(first_list[i]) i += 1 i: int = 0 if len(second_list) > 0: while i < len(second_list): concatenated.append(second_list[i]) i += 1 return concatenated
true
d25b2e03c3dbbde0adaf951479bb747130c54a5b
grahamRuttiman/practicals
/exceptions.py
614
4.46875
4
try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") # QUESTIONS: # 1. A ValueError occurs when the value entered is not an integer, or even a number # 2. A ZeroDivisionError occurs when the value of demoninator entered is zero # 3. Before the fraction value is calculated we could use an if statement to print an error message if the demoninator value entered is zero
true
8b0196b9cd8643a516730276f084afc249ce8b8e
dfm066/Programming
/ProjectEuler/Python/latticepath.py
369
4.15625
4
def lattice_path(n): list = [] list.append(1) for i in range(1,n+1): for j in range(1,i): list[j] += list[j-1] list.append(list[-1]*2) return list[-1] def main(): size = int(input("Enter Grid Size : ")) path_count = lattice_path(size) print("Total Possible Paths : {0}".format(path_count)) main()
false
9d7f4a745fb024199bcc0be0bd89542931aea90a
ohiosuperstar/Meow
/meow.py
755
4.15625
4
import string def isCaps(word): for letter in word: if letter in string.ascii_lowercase: return False return True str = input('Give me a string, mortal: ') out = '' str = str.split() for word in str: meowDone = False for symbol in word: if symbol not in string.ascii_letters: out += symbol elif meowDone: pass else: if isCaps(word): out += 'MEOW' meowDone = True else: if word[0] in string.ascii_uppercase: out += 'Meow' meowDone = True else: out += 'meow' meowDone = True out += ' ' print(out)
true
37c535b3f96153785af441fe876b7d0524d69511
PyStyle/LPTHW
/EX20/ex20.py
1,249
4.3125
4
from sys import argv # adding a module to my code script, input_file = argv # create a function to display an entire text file, # "f" is just a variable name for the file def print_all(f): print f.read() # dot operator to use the read function # create a function to go to beginning of a file (i.e. byte 0) def rewind(f): f.seek(0) # create a function to print out one line, where line_count is the # line number we want to read, f is the name of the file (from above), # and readline is a built-in function or method def print_a_line(line_count, f): print line_count, f.readline() # = assignment operator, defines variable and put in the variable object current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" # define current line below, current file in line 24, print 1 line @ a time current_line = 1 print_a_line(current_line, current_file) # move to neaxt line by incrementing the variable current_line, # +1 add another line current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
true
7a598699e2e43fa3ee4f7fb2d0ba971e6c68fdbe
mhdaimi/Python-Selenium
/python_basics/data_type_dictionary.py
457
4.28125
4
# Dictionary stores a key:value pair city_pincode = {"Pune": 411014, "Mumbai": 400001, 100011:"Delhi"} print("Pincode of Pune is {}".format(city_pincode["Pune"])) print("Size of dictionary -> {}".format(len(city_pincode))) #Add new key:value pair city_pincode["Aurangabad"] = 431001 print(city_pincode) #Update value of existing Key city_pincode["Pune"] = 411001 print(city_pincode) #Remove a key:value pair del city_pincode["Pune"] print(city_pincode)
false
6943815ec00b9a7fc6885b1aff1cd3568b86a488
mhdaimi/Python-Selenium
/python_basics/concatenation.py
832
4.34375
4
print("Welcome to " + "Python learning") name = "Python 3.8" print("We are learning " + name) print("We are learning Python", 3.8) name = "Python" version = "3.8" #Version as string print("We are using version " + version + " of " + name ) # Plus(+) operator works only with 2 strings name = "Python" version = 3.8 # Version as a float # The following will give an error as we try to concatenate string with float #print("We are using version " + version + " of " + name ) print("We are using version", version, "of " + name ) print("We are using version %f of %s " %(version, name)) #Best way to concatenate different types of data is to use format method of string print("We are using version {} of {}".format(version, name)) city = "Pune" temperature = 38 print("The temperature of {} is {}".format(city, temperature))
true
93e0dca5501fe5aabf2d2b3c216bc152c02438e1
DeanHe/Practice
/LeetCodePython/MinimumAdditionToMakeIntegerBeautiful.py
1,690
4.3125
4
""" You are given two positive integers n and target. An integer is considered beautiful if the sum of its digits is less than or equal to target. Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful. Example 1: Input: n = 16, target = 6 Output: 4 Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4. Example 2: Input: n = 467, target = 6 Output: 33 Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33. Example 3: Input: n = 1, target = 1 Output: 0 Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target. Constraints: 1 <= n <= 10^12 1 <= target <= 150 The input will be generated such that it is always possible to make n beautiful. hints: 1 Think about each digit independently. 2 Turn the rightmost non-zero digit to zero until the digit sum is greater than target. """ class MinimumAdditionToMakeIntegerBeautiful: def makeIntegerBeautiful(self, n: int, target: int) -> int: def sum_digits(x): digits = 0 while x > 0: digits += x % 10 x //= 10 return digits num, base = n, 1 while sum_digits(n) > target: n = n // 10 + 1 base *= 10 return n * base - num
true
be719ca69d88a89af3bb9f354e1c77021338ccf2
DeanHe/Practice
/LeetCodePython/MaximumXORAfterOperations.py
1,588
4.46875
4
""" You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times. Example 1: Input: nums = [3,2,4,6] Output: 7 Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2. Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7. It can be shown that 7 is the maximum possible bitwise XOR. Note that other operations may be used to achieve a bitwise XOR of 7. Example 2: Input: nums = [1,2,3,9,2] Output: 11 Explanation: Apply the operation zero times. The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11. It can be shown that 11 is the maximum possible bitwise XOR. Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 108 hint: 1 Consider what it means to be able to choose any x for the operation and which integers could be obtained from a given nums[i]. 2 The given operation can unset any bit in nums[i]. 3 The nth bit of the XOR of all the elements is 1 if the nth bit is 1 for an odd number of elements. When can we ensure it is odd? 4 Try to set every bit of the result to 1 if possible. """ from typing import List class MaximumXORAfterOperations: def maximumXOR(self, nums: List[int]) -> int: res = 0 for n in nums: res |= n return res
true
d41b7798d86f4d8806d6fd96ceb97baace6604d0
DeanHe/Practice
/LeetCodePython/ValidParenthesisString.py
1,253
4.25
4
""" Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid. The following rules define a valid string: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "". Example 1: Input: s = "()" Output: true Example 2: Input: s = "(*)" Output: true Example 3: Input: s = "(*))" Output: true Constraints: 1 <= s.length <= 100 s[i] is '(', ')' or '*'. """ class ValidParenthesisString: def checkValidString(self, s: str) -> bool: open_min, open_max = 0, 0 for i in range(0, len(s)): if s[i] == '(': open_min += 1 open_max += 1 elif s[i] == ')': if open_min > 0: open_min -= 1 open_max -= 1 else: # for '*' if open_min > 0: open_min -= 1 open_max += 1 if open_max < 0: return False return open_min == 0
true
0b296ace36871717597aeb6153f07e7f0449ace6
DeanHe/Practice
/LeetCodePython/PalindromePartitioning.py
939
4.15625
4
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. Example 1: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Example 2: Input: s = "a" Output: [["a"]] Constraints: 1 <= s.length <= 16 s contains only lowercase English letters. """ from typing import List class PalindromePartitioning: def partition(self, s: str) -> List[List[str]]: res = [] def dfs(candidates, pos): if pos == len(s): res.append(candidates.copy()) return for i in range(pos + 1, len(s) + 1): sub = s[pos:i] if sub == sub[::-1]: candidates.append(sub) dfs(candidates, i) candidates.pop() dfs([], 0) return res
true
fbaa5c030a51d6dff0dea8f50f15d6c8fb152b13
DeanHe/Practice
/LeetCodePython/OddEvenLinkedList.py
1,259
4.15625
4
""" Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in O(1) extra space complexity and O(n) time complexity. Example 1: Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] Example 2: Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4] Constraints: The number of nodes in the linked list is in the range [0, 10^4]. -106 <= Node.val <= 10^6 """ from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class OddEvenLinkedList: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return head even_start, odd_cur, even_cur = head.next, head, head.next while odd_cur.next and even_cur.next: odd_cur.next = even_cur.next odd_cur = odd_cur.next even_cur.next = odd_cur.next even_cur = even_cur.next odd_cur.next = even_start return head
true
a69d0974b8aaa8cbcb4feec4161756a793b5de90
DeanHe/Practice
/LeetCodePython/LargestRectangleInHistogram.py
1,209
4.1875
4
""" Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Example 1: Input: heights = [2,1,5,6,2,3] Output: 10 Explanation: The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. Example 2: Input: heights = [2,4] Output: 4 Constraints: 1 <= heights.length <= 10^5 0 <= heights[i] <= 10^4 """ from typing import List class LargestRectangleInHistogram: def largestRectangleArea(self, heights: List[int]) -> int: res = h = w = 0 stack = [] for i in range(len(heights)): while stack and heights[i] <= heights[stack[-1]]: h = heights[stack.pop()] if stack: w = i - stack[-1] - 1 else: w = i res = max(res, h * w) stack.append(i) while stack: h = heights[stack.pop()] if stack: w = len(heights) - stack[-1] - 1 else: w = len(heights) res = max(res, h * w) return res
true
e7e281750a240d1fd64d121b218d4d4aa036d833
DeanHe/Practice
/LeetCodePython/ReconstructItinerary.py
1,653
4.40625
4
""" You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi """ import collections from typing import List class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: graph = collections.defaultdict(list) for s, e in sorted(tickets)[::-1]: graph[s].append(e) path = [] def dfs(departure): while graph[departure]: dfs(graph[departure].pop()) path.append(departure) dfs('JFK') return path[::-1]
true
cf15cecb8c0a3143bb30877307a6cf62f7f91a29
DeanHe/Practice
/LeetCodePython/RaceCar.py
1,867
4.25
4
""" Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse): When you get an instruction 'A', your car does the following: position += speed speed *= 2 When you get an instruction 'R', your car does the following: If your speed is positive then speed = -1 otherwise speed = 1 Your position stays the same. For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1. Given a target position target, return the length of the shortest sequence of instructions to get there. Example 1: Input: target = 3 Output: 2 Explanation: The shortest instruction sequence is "AA". Your position goes from 0 --> 1 --> 3. Example 2: Input: target = 6 Output: 5 Explanation: The shortest instruction sequence is "AAARA". Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. Constraints: 1 <= target <= 10^4 """ class RaceCar: def racecar(self, target: int) -> int: dp = [0] * (target + 1) for i in range(1, target + 1): dp[i] = float('inf') cnt_of_A_before_first_R, j = 1, 1 while j < i: cnt_of_A_before_second_R, k = 0, 0 while k < j: dp[i] = min(dp[i], 1 + cnt_of_A_before_first_R + 1 + cnt_of_A_before_second_R + dp[i - (j - k)]) k += 1 << cnt_of_A_before_second_R cnt_of_A_before_second_R += 1 j += 1 << cnt_of_A_before_first_R cnt_of_A_before_first_R += 1 if j == i: dp[i] = min(dp[i], cnt_of_A_before_first_R) else: dp[i] = min(dp[i], cnt_of_A_before_first_R + 1 + dp[j - i]) return dp[target]
true
9f72042b90ed8510e7bb546b43646b17cf4d5cc3
DeanHe/Practice
/LeetCodePython/Largest3SameDigitNumberInString.py
1,110
4.125
4
""" You are given a string num representing a large integer. An integer is good if it meets the following conditions: It is a substring of num with length 3. It consists of only one unique digit. Return the maximum good integer as a string or an empty string "" if no such integer exists. Note: A substring is a contiguous sequence of characters within a string. There may be leading zeroes in num or a good integer. Example 1: Input: num = "6777133339" Output: "777" Explanation: There are two distinct good integers: "777" and "333". "777" is the largest, so we return "777". Example 2: Input: num = "2300019" Output: "000" Explanation: "000" is the only good integer. Example 3: Input: num = "42352338" Output: "" Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers. Constraints: 3 <= num.length <= 1000 num only consists of digits. """ class Largest3SameDigitNumberInString: def largestGoodInteger(self, num: str) -> str: return max(num[i - 2: i + 1] if num[i] == num[i - 1] == num[i - 2] else "" for i in range(2, len(num)))
true
c015380c6afec6e616a443dc036ac4fd9c8f3fe2
DeanHe/Practice
/LeetCodePython/TheNumberOfBeautifulSubsets.py
1,979
4.25
4
""" You are given an array nums of positive integers and a positive integer k. A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k. Return the number of non-empty beautiful subsets of the array nums. A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different. Example 1: Input: nums = [2,4,6], k = 2 Output: 4 Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6]. It can be proved that there are only 4 beautiful subsets in the array [2,4,6]. Example 2: Input: nums = [1], k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1]. Constraints: 1 <= nums.length <= 20 1 <= nums[i], k <= 1000 hints: 1 Sort the array nums and create another array cnt of size nums[i]. 2 Use backtracking to generate all the beautiful subsets. If cnt[nums[i] - k] is positive, then it is impossible to add nums[i] in the subset, and we just move to the next index. Otherwise, it is also possible to add nums[i] in the subset, in this case, increase cnt[nums[i]], and move to the next index. """ from collections import defaultdict from typing import List class TheNumberOfBeautifulSubsets: def beautifulSubsets(self, nums: List[int], k: int) -> int: size = len(nums) nums.sort() pos = defaultdict(int) for i, n in enumerate(nums): pos[n] |= 1 << i mem = {} def dfs(mask, idx): if idx >= size: return 1 if mask > 0 else 0 if mask in mem: return mem[mask] res = dfs(mask, idx + 1) if pos[nums[idx] - k] & mask == 0: res += dfs((1 << idx) | mask, idx + 1) mem[mask] = res return res return dfs(0, 0)
true
77fd864cec47777a25e1ee2d1701c56056cd61d4
DeanHe/Practice
/LeetCodePython/NumberOfWaysToBuyPensAndPencils.py
1,489
4.15625
4
""" You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil. Return the number of distinct ways you can buy some number of pens and pencils. Example 1: Input: total = 20, cost1 = 10, cost2 = 5 Output: 9 Explanation: The price of a pen is 10 and the price of a pencil is 5. - If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils. - If you buy 1 pen, you can buy 0, 1, or 2 pencils. - If you buy 2 pens, you cannot buy any pencils. The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9. Example 2: Input: total = 5, cost1 = 10, cost2 = 10 Output: 1 Explanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils. Constraints: 1 <= total, cost1, cost2 <= 10^6 hint: 1 Fix the number of pencils purchased and calculate the number of ways to buy pens. 2 Sum up the number of ways to buy pens for each amount of pencils purchased to get the answer. """ class NumberOfWaysToBuyPensAndPencils: def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: res, cnt1 = 0, 0 while cnt1 * cost1 <= total: res += (total - cnt1 * cost1) // cost2 + 1 cnt1 += 1 return res
true
e695e23413a87d0581dcdb9b903d222b7450ddac
DeanHe/Practice
/LeetCodePython/PseudoPalindromicPathsInaBinaryTree.py
2,298
4.25
4
""" Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 2: Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome). Example 3: Input: root = [9] Output: 1 Constraints: The number of nodes in the tree is in the range [1, 105]. 1 <= Node.val <= 9 hint: 1 Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). 2 Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity). analysis: TC: O(N) SC: O(height of tree) """ from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class PseudoPalindromicPathsInaBinaryTree: def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int: def dfs(cur, mask): if not cur: return 0 mask ^= 1 << (cur.val - 1) res = dfs(cur.left, mask) + dfs(cur.right, mask) if cur.left is None and cur.right is None: # is leaf if mask & (mask - 1) == 0: # check that at most one digit has an odd frequency res += 1 return res return dfs(root, 0)
true
600fd6d1eeb0d0c8469a8b5cb43241fcfc9e6643
DeanHe/Practice
/LeetCodePython/MinimumSpeedToArriveOnTime.py
2,928
4.40625
4
""" You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. Example 1: Input: dist = [1,3,2], hour = 6 Output: 1 Explanation: At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. Example 2: Input: dist = [1,3,2], hour = 2.7 Output: 3 Explanation: At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. Example 3: Input: dist = [1,3,2], hour = 1.9 Output: -1 Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. Constraints: n == dist.length 1 <= n <= 105 1 <= dist[i] <= 105 1 <= hour <= 109 There will be at most two digits after the decimal point in hour. hint: 1 Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? 2 Is there a cutoff where any speeds larger will always allow you to arrive on time? """ from typing import List class MinimumSpeedToArriveOnTime: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: def canReach(spd): total = 0 for i, d in enumerate(dist): if i == len(dist) - 1: t = d / spd else: t = (d + spd - 1) // spd total += t return total <= hour s, e = 1, 10 ** 7 + 1 while s + 1 < e: mid = s + (e - s) // 2 if canReach(mid): e = mid else: s = mid if canReach(s): return s if canReach(e): return e return -1
true
899f69376cfae31d701cded34e814c3c59230582
DeanHe/Practice
/LeetCodePython/RotateImage.py
1,222
4.375
4
""" You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]] Example 2: Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] Constraints: n == matrix.length == matrix[i].length 1 <= n <= 20 -1000 <= matrix[i][j] <= 1000 """ from typing import List class RotateImage: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ self.transpose(matrix) self.reverse(matrix) def transpose(self, matrix): n = len(matrix) for r in range(n): for c in range(r + 1, n): matrix[c][r], matrix[r][c] = matrix[r][c], matrix[c][r] def reverse(self, matrix): n = len(matrix) for r in range(n): for c in range(n // 2): matrix[r][c], matrix[r][-c-1] = matrix[r][-c-1], matrix[r][c]
true
7a7124640f42f2d1c4acb10b0e66cda54000fc37
DeanHe/Practice
/LeetCodePython/JumpGameII.py
930
4.21875
4
""" Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index. Example 1: Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [2,3,0,1,4] Output: 2 Constraints: 1 <= nums.length <= 10^4 0 <= nums[i] <= 1000 """ from typing import List class JumpGameII: def jump(self, nums: List[int]) -> int: max_reach, end, res = 0, 0, 0 for i in range(len(nums) - 1): max_reach = max(max_reach, i + nums[i]) if i == end: res += 1 end = max_reach return res
true
9a167a3e2e3c0363a88e9f9634961e96dd9b917d
DeanHe/Practice
/LeetCodePython/EvaluateReversePolishNotation.py
1,653
4.28125
4
""" Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression. Note that division between two integers should truncate toward zero. It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation. Example 1: Input: tokens = ["2","1","+","3","*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: tokens = ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 Constraints: 1 <= tokens.length <= 10^4 tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200]. """ from typing import List class EvaluateReversePolishNotation: def evalRPN(self, tokens: List[str]) -> int: stack = [] operators = "+-*/" for c in tokens: if c not in operators: stack.append(int(c)) else: b, a = stack.pop(), stack.pop() if c == "+": stack.append(a + b) elif c == "-": stack.append(a - b) elif c == "*": stack.append(a * b) elif c == "/": stack.append(int(float(a) / b)) return stack.pop()
true
b12cb8e6a34c038f0101677a30e6b6d0516c152d
DeanHe/Practice
/LeetCodePython/MinimumRoundsToCompleteAllTasks.py
1,479
4.125
4
""" You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Input: tasks = [2,2,3,3,2,4,4,4,4,4] Output: 4 Explanation: To complete all the tasks, a possible plan is: - In the first round, you complete 3 tasks of difficulty level 2. - In the second round, you complete 2 tasks of difficulty level 3. - In the third round, you complete 3 tasks of difficulty level 4. - In the fourth round, you complete 2 tasks of difficulty level 4. It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. Example 2: Input: tasks = [2,3,3] Output: -1 Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1. Constraints: 1 <= tasks.length <= 10^5 1 <= tasks[i] <= 10^9 """ from collections import Counter from typing import List class MinimumRoundsToCompleteAllTasks: def minimumRounds(self, tasks: List[int]) -> int: res = 0 cnt = Counter(tasks) for freq in cnt.values(): if freq == 1: return -1 res += (freq + 2) // 3 return res
true
be312d6f0f96fd863f820a60a6e90ece3402949d
DeanHe/Practice
/LeetCodePython/DiagonalTraverse.py
1,151
4.15625
4
""" Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation: Note: The total number of elements of the given matrix will not exceed 10,000. Constraints: m == mat.length n == mat[i].length 1 <= m, n <= 10^4 1 <= m * n <= 10^4 -10^5 <= mat[i][j] <= 10^5 """ from typing import List class DiagonalTraverse: def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: rows, cols, r, c, res = len(mat), len(mat[0]), 0, 0, [] for i in range(rows * cols): res.append(mat[r][c]) if (r + c) % 2 == 0: if c == cols - 1: r += 1 elif r == 0: c += 1 else: r -= 1 c += 1 else: if r == rows - 1: c += 1 elif c == 0: r += 1 else: r += 1 c -= 1 return res
true
8d11d7a8dd15d7f14065f5add86461c7df0f2f50
DeanHe/Practice
/LeetCodePython/FindAllDuplicatesInAnArray.py
837
4.125
4
""" Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice. You must write an algorithm that runs in O(n) time and uses only constant extra space. Example 1: Input: nums = [4,3,2,7,8,2,3,1] Output: [2,3] Example 2: Input: nums = [1,1,2] Output: [1] Example 3: Input: nums = [1] Output: [] Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= n Each element in nums appears once or twice. """ from typing import List class FindAllDuplicatesInAnArray: def findDuplicates(self, nums: List[int]) -> List[int]: res = [] for n in nums: i = abs(n) - 1 if nums[i] < 0: res.append(i + 1) nums[i] = -nums[i] return res
true
ccb2064dbc964d22eb4bee06e3d645b1a471d10c
DeanHe/Practice
/LeetCodePython/SpiralMatrixIV.py
1,586
4.375
4
""" You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers. Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1. Return the generated matrix. Example 1: Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0] Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]] Explanation: The diagram above shows how the values are printed in the matrix. Note that the remaining spaces in the matrix are filled with -1. Example 2: Input: m = 1, n = 4, head = [0,1,2] Output: [[0,1,2,-1]] Explanation: The diagram above shows how the values are printed from left to right in the matrix. The last space in the matrix is set to -1. Constraints: 1 <= m, n <= 105 1 <= m * n <= 105 The number of nodes in the list is in the range [1, m * n]. 0 <= Node.val <= 1000 """ from typing import Optional, List from AddTwoNumbers import ListNode class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: matrix = [[-1] * n for _ in range(m)] r, c, dr, dc = 0, 0, 0, 1 while head: matrix[r][c] = head.val if matrix[(r + dr) % m][(c + dc) % n] != -1: dr, dc = dc, -dr r += dr c += dc head = head.next return matrix
true
0bcf3dc0b60184a6dcea836244be4078142597ec
DeanHe/Practice
/LeetCodePython/MinimumScoreOfaPathBetweenTwoCities.py
2,451
4.21875
4
""" You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between cities 1 and n. Note: A path is a sequence of roads between two cities. It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path. The test cases are generated such that there is at least one path between 1 and n. Example 1: Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]] Output: 5 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5. It can be shown that no other path has less score. Example 2: Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]] Output: 2 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2. Constraints: 2 <= n <= 10^5 1 <= roads.length <= 10^5 roads[i].length == 3 1 <= ai, bi <= n ai != bi 1 <= distancei <= 10^4 There are no repeated edges. There is at least one path between 1 and n. hints: 1 Can you solve the problem if the whole graph is connected? 2 Notice that if the graph is connected, you can always use any edge of the graph in your path. 3 How to solve the general problem in a similar way? Remove all the nodes that are not connected to 1 and n, then apply the previous solution in the new graph. analysis: since it guarantees to exist a path from 1 to n, bfs from 1 and track the shortest dist. TC O(N) """ import collections from typing import List class MinimumScoreOfaPathBetweenTwoCities: def minScore(self, n: int, roads: List[List[int]]) -> int: res = float('inf') graph = collections.defaultdict(dict) for a, b, dist in roads: graph[a][b] = graph[b][a] = dist visited = set() q = collections.deque([1]) while q: cur = q.popleft() for nb, dist in graph[cur].items(): if nb not in visited: visited.add(nb) q.append(nb) res = min(res, dist) return res
true
6d458c64d633e36514f328028523552662fb7cde
DeanHe/Practice
/LeetCodePython/SmallestStringWithSwaps.py
2,210
4.3125
4
""" You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after using the swaps. Example 1: Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[1] and s[2], s = "bacd" Example 2: Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]] Output: "abcd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[0] and s[2], s = "acbd" Swap s[1] and s[2], s = "abcd" Example 3: Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" Explaination: Swap s[0] and s[1], s = "bca" Swap s[1] and s[2], s = "bac" Swap s[0] and s[1], s = "abc" Constraints: 1 <= s.length <= 10^5 0 <= pairs.length <= 10^5 0 <= pairs[i][0], pairs[i][1] < s.length s only contains lower case English letters. hint: 1 Think of it as a graph problem. 2 Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ? 3 We can sort each connected component alone to get the lexicographically minimum string. """ import collections from typing import List class SmallestStringWithSwaps: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: parent = list(range(len(s))) def findRoot(x): root = x while parent[root] != root: root = parent[root] while x != root: fa = parent[x] parent[x] = root x = fa return fa def union(a, b): root_a = findRoot(a) root_b = findRoot(b) if root_a != root_b: parent[root_a] = root_b res, graph = [], collections.defaultdict(list) for a, b in pairs: union(a, b) for i in range(len(s)): graph[findRoot(i)].append(s[i]) for i in graph.keys(): graph[i].sort(reverse=True) for i in range(len(s)): res.append(graph[findRoot(i)].pop()) return ''.join(res)
true
11b1c94525690e9d36624e25cb529c7b86cc04dc
DeanHe/Practice
/LeetCodePython/MaximumWidthOfBinaryTree.py
1,760
4.28125
4
""" Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation. It is guaranteed that the answer will in the range of 32-bit signed integer. Example 1: Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). Example 2: Input: root = [1,3,null,5,3] Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3). Example 3: Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width existing in the second level with the length 2 (3,2). Constraints: The number of nodes in the tree is in the range [1, 3000]. -100 <= Node.val <= 100 """ # Definition for a binary tree node. import collections from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class MaximumWidthOfBinaryTree: def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: if not root: return 0 res = 0 q = collections.deque() q.append((1, root)) while q: sz, l, r = len(q), q[0][0], q[-1][0] res = max(res, r - l + 1) for i in range(sz): idx, cur = q.popleft() if cur.left: q.append((idx * 2, cur.left)) if cur.right: q.append((2 * idx + 1, cur.right)) return res
true
38182bdebe7cf53b1813723b2bea1a5c1352734b
DeanHe/Practice
/LeetCodePython/SlidingSubarrayBeauty.py
2,409
4.25
4
""" Given an integer array nums containing n integers, find the beauty of each subarray of size k. The beauty of a subarray is the xth smallest integer in the subarray if it is negative, or 0 if there are fewer than x negative integers. Return an integer array containing n - k + 1 integers, which denote the beauty of the subarrays in order from the first index in the array. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,-1,-3,-2,3], k = 3, x = 2 Output: [-1,-2,-2] Explanation: There are 3 subarrays with size k = 3. The first subarray is [1, -1, -3] and the 2nd smallest negative integer is -1. The second subarray is [-1, -3, -2] and the 2nd smallest negative integer is -2. The third subarray is [-3, -2, 3] and the 2nd smallest negative integer is -2. Example 2: Input: nums = [-1,-2,-3,-4,-5], k = 2, x = 2 Output: [-1,-2,-3,-4] Explanation: There are 4 subarrays with size k = 2. For [-1, -2], the 2nd smallest negative integer is -1. For [-2, -3], the 2nd smallest negative integer is -2. For [-3, -4], the 2nd smallest negative integer is -3. For [-4, -5], the 2nd smallest negative integer is -4. Example 3: Input: nums = [-3,1,2,-3,0,-3], k = 2, x = 1 Output: [-3,0,-3,-3,-3] Explanation: There are 5 subarrays with size k = 2. For [-3, 1], the 1st smallest negative integer is -3. For [1, 2], there is no negative integer so the beauty is 0. For [2, -3], the 1st smallest negative integer is -3. For [-3, 0], the 1st smallest negative integer is -3. For [0, -3], the 1st smallest negative integer is -3. Constraints: n == nums.length 1 <= n <= 10^5 1 <= k <= n 1 <= x <= k -50 <= nums[i] <= 50 """ from typing import List class SlidingSubarrayBeauty: def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: res = [] buckets = [0] * 50 for i, n in enumerate(nums): if n < 0: buckets[n + 50] += 1 if i - k >= 0: pre = nums[i - k] if pre < 0: buckets[pre + 50] -= 1 if i + 1 >= k: count = 0 for j, cnt in enumerate(buckets): count += cnt if count >= x: res.append(j - 50) break if count < x: res.append(0) return res
true
6c81710c6bd12f2be15e2a65ac086a0f3fc3f62d
DeanHe/Practice
/LeetCodePython/NestedIterator.py
2,710
4.40625
4
""" You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the NestedIterator class: NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList. int next() Returns the next integer in the nested list. boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res If res matches the expected flattened list, then your code will be judged as correct. Example 1: Input: nestedList = [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. Example 2: Input: nestedList = [1,[4,[6]]] Output: [1,4,6] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. Constraints: 1 <= nestedList.length <= 500 The values of the integers in the nested list is in the range [-10^6, 10^6]. """ """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation Your NestedIterator object will be instantiated and called as such: i, v = NestedIterator(nestedList), [] while i.hasNext(): v.append(i.next()) """ class NestedInteger: def isInteger(self) -> bool: """ @return True if this NestedInteger holds a single integer, rather than a nested list. """ def getInteger(self) -> int: """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list """ def getList(self) -> [NestedInteger]: """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer """ class NestedIterator: def __init__(self, nestedList: [NestedInteger]): self.stack = [] self.pushAll(nestedList) def next(self) -> int: return self.stack.pop().getInteger() def hasNext(self) -> bool: while self.stack and not self.stack[-1].isInteger(): ls = self.stack.pop().getList() self.pushAll(ls) return len(self.stack) > 0 def pushAll(self, nestedList: [NestedInteger]) -> None: for n in reversed(nestedList): self.stack.append(n)
true
4c78d4e5275c5876f65381339bb2fa4446c85bd8
DeanHe/Practice
/LeetCodePython/BasicCalculatorII.py
1,750
4.15625
4
""" Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2^31, 2^31 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). Example 1: Input: s = "3+2*2" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s = " 3+5 / 2 " Output: 5 Constraints: 1 <= s.length <= 3 * 10^5 s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0, 231 - 1]. The answer is guaranteed to fit in a 32-bit integer. """ class BasicCalculatorII: def calculate(self, s: str) -> int: stack = [] res, cur, sign = 0, 0, '+' for i, c in enumerate(s): if c.isdigit(): cur = cur * 10 + ord(c) - ord('0') if (not c.isdigit() and c != ' ') or i == len(s) - 1: if sign == '+': stack.append(cur) elif sign == '-': stack.append(-cur) elif sign == '*': stack.append(stack.pop() * cur) elif sign == '/': tmp = stack.pop() if tmp // cur < 0 and tmp % cur != 0: stack.append(tmp // cur + 1) else: stack.append(tmp // cur) sign = c cur = 0 while stack: res += stack.pop() return res
true
810bd042c218118cbc37224bc70a6a7ff41908a7
DeanHe/Practice
/LeetCodePython/StringCompressionII.py
2,700
4.5
4
""" Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3". Notice that in this problem, we are not adding '1' after single characters. Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length. Find the minimum length of the run-length encoded version of s after deleting at most k characters. Example 1: Input: s = "aaabcccd", k = 2 Output: 4 Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4. Example 2: Input: s = "aabbaa", k = 2 Output: 2 Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2. Example 3: Input: s = "aaaaaaaaaaa", k = 0 Output: 3 Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3. Constraints: 1 <= s.length <= 100 0 <= k <= s.length s contains only lowercase English letters. hints: 1 Use dynamic programming. 2 The state of the DP can be the current index and the remaining characters to delete. 3 Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range """ from functools import lru_cache class StringCompressionII: def getLengthOfOptimalCompression(self, s: str, k: int) -> int: @lru_cache(None) def dfs(start, pre_char, pre_char_cnt, remain_delete): if remain_delete < 0: return float('inf') if start >= len(s): return 0 if s[start] == pre_char: inc = 1 if pre_char_cnt == 1 or pre_char_cnt == 9 or pre_char_cnt == 99 else 0 return inc + dfs(start + 1, pre_char, pre_char_cnt + 1, remain_delete) else: keep = 1 + dfs(start + 1, s[start], 1, remain_delete) delete = dfs(start + 1, pre_char, pre_char_cnt, remain_delete - 1) return min(keep, delete) return dfs(0, '', 0, k)
true
509c8bd395006d72234f8e1ebaa163a657272a44
DeanHe/Practice
/LeetCodePython/LexicographicallySmallestEquivalentString.py
2,883
4.25
4
""" You are given two strings of the same length s1 and s2 and a string baseStr. We say s1[i] and s2[i] are equivalent characters. For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'. Equivalent characters follow the usual rules of any equivalence relation: Reflexivity: 'a' == 'a'. Symmetry: 'a' == 'b' implies 'b' == 'a'. Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'. For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr. Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2. Example 1: Input: s1 = "parker", s2 = "morris", baseStr = "parser" Output: "makkek" Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek". Example 2: Input: s1 = "hello", s2 = "world", baseStr = "hold" Output: "hdld" Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld". Example 3: Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode" Output: "aauaaaaada" Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada". Constraints: 1 <= s1.length, s2.length, baseStr <= 1000 s1.length == s2.length s1, s2, and baseStr consist of lowercase English letters. analysis: Here, N is the length of strings s1 and s2, M is the length of string baseStr, and ∣Σ∣ is the number of unique characters in s1 or s2, which is 26 for this problem. Time complexity: O((N+M)log∣Σ∣). """ class LexicographicallySmallestEquivalentString: def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str: res = [] parent = {} def find_root(x): root = x parent.setdefault(x, x) while parent[root] != root: root = parent[root] while parent[x] != root: fa = parent[x] parent[x] = root x = fa return root def union(a, b): root_a, root_b = find_root(a), find_root(b) if root_a < root_b: parent[root_b] = root_a else: parent[root_a] = root_b n = len(s1) for i in range(n): union(s1[i], s2[i]) for c in baseStr: res.append(find_root(c)) return ''.join(res)
true
074543c4bf98194eee8df87f0eb1cc44d7986784
DeanHe/Practice
/LeetCodePython/PartitionLabels.py
1,195
4.125
4
""" A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partitions are "ababcbaca", "defegde", "hijhklij". A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. Example 2: Input: S = "abcab" Output: [5] Explanation: We can not split it. Notice 1.S will have length in range [1, 500]. 2.S will consist of lowercase letters ('a' to 'z') only. tag: greedy find the last index of each letter in S first. iterate letter from start to last[start], and expand the partition to last[cur] """ from typing import List class PartitionLabels: def partitionLabels(self, s: str) -> List[int]: res, last, start, end = [], {}, 0, 0 for i, c in enumerate(s): last[c] = i for i, c in enumerate(s): end = max(end, last[c]) if i == end: res.append(end - start + 1) start = end + 1 return res
true
9099ed0b6953d30c9a5621e96823f14b466a914f
DeanHe/Practice
/LeetCodePython/MinimumJumpsToReachHome.py
2,470
4.3125
4
""" A certain bug's home is on the x-axis at position x. Help them get there from position 0. The bug jumps according to the following rules: It can jump exactly a positions forward (to the right). It can jump exactly b positions backward (to the left). It cannot jump backward twice in a row. It cannot jump to any forbidden positions. The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1. Example 1: Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9 Output: 3 Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home. Example 2: Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11 Output: -1 Example 3: Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7 Output: 2 Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home. Constraints: 1 <= forbidden.length <= 1000 1 <= a, b, forbidden[i] <= 2000 0 <= x <= 2000 All the elements in forbidden are distinct. Position x is not forbidden. hints: 1 Think of the line as a graph 2 to handle the no double back jumps condition you can handle it by holding the state of your previous jump """ import collections from typing import List class MinimumJumpsToReachHome: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: visited = {(0, True)} for pos in forbidden: visited.add((pos, True)) visited.add((pos, False)) steps = 0 furthest = max(x, max(forbidden)) + a + b # pos:direction q = collections.deque([(0, True)]) while q: sz = len(q) for _ in range(sz): pos, is_right = q.popleft() if pos == x: return steps right, left = (pos + a, True), (pos - b, False) if pos + a <= furthest and right not in visited: visited.add(right) q.append(right) if is_right and pos - b > 0 and left not in visited: visited.add(left) q.append(left) steps += 1 return -1
true
03728766edfcd9ff0d48545c420d5c1b1f5fcd47
DeanHe/Practice
/LeetCodePython/MakeNumberOfDistinctCharactersEqual.py
2,206
4.1875
4
""" You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j]. Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise. Example 1: Input: word1 = "ac", word2 = "b" Output: false Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string. Example 2: Input: word1 = "abcc", word2 = "aab" Output: true Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters. Example 3: Input: word1 = "abcde", word2 = "fghij" Output: true Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap. Constraints: 1 <= word1.length, word2.length <= 10^5 word1 and word2 consist of only lowercase English letters. hints: 1 Create a frequency array of the letters of each string. 2 There are 26*26 possible pairs of letters to swap. Can we try them all? 3 Iterate over all possible pairs of letters and check if swapping them will yield two strings that have the same number of distinct characters. Use the frequency array for the check. TC: O(26 * 26 * (m + n)) """ from collections import Counter class MakeNumberOfDistinctCharactersEqual: def isItPossible(self, word1: str, word2: str) -> bool: cnt1 = [0] * 26 cnt2 = [0] * 26 for c in word1: cnt1[ord(c) - ord('a')] += 1 for c in word2: cnt2[ord(c) - ord('a')] += 1 def same(): return len([x for x in cnt1 if x > 0]) == len([x for x in cnt2 if x > 0]) for i in range(26): if cnt1[i] == 0: continue for j in range(26): if cnt2[j] == 0: continue cnt1[i] -= 1 cnt2[j] += 1 if same(): return True cnt2[j] += 1 cnt1[i] -= 1 return False
true
7f249e49eba5ae7295208d8f15cb7d297277da3a
MrThoe/CV_Turt_Proj
/1_Square.py
504
4.125
4
""" 1. Create a function that will draw a Square - call it DrawSquare() 2. Allow this function to have 1 Parameter (s) for the side length. 3. Use a FOR Loop for this function. """ """ 4. Inside a for loop, call the Square function 100 times, for the sidelength of 10*i. 5. Using the pen up and pendown functions (YourTurtle.pu()) use the .goto(x,y) to move the turtle before drawing the next square. Try and see if you can get it to make all the squares share the same center. """
true
76339afe4f8ed4e8bd260b872016b116b8ddc8d0
Sahha2001000/Paradigm
/lab_1/t7.py
268
4.1875
4
print("\ntask7") chosen_number = int(input("Сhoose number: ")) print("Can be divided by 2" if chosen_number % 2 == 0 else "Cannot divided by 2. Choose another one") print("Last number is 5" if chosen_number % 10 == 5 else "Last number is not 5. Choose another one")
true
c00fa047e97983fc4276343207ac8185c1a52548
Sahha2001000/Paradigm
/lab_1/t4.py
306
4.125
4
print("\ntask4") number = input("Choose three-digit number: ") tmp = number number_list = list(number) number_list.reverse() number = "".join(number_list) print("The reversed number of {} is ".format(tmp) + number) """ tmp = tmp[::-1] print("Второй вариант через срез:" + tmp) """
true
fd0777adf5b1fe5e6d8195ccc82e407ef9befc36
chrissyblissy/CS50x
/pset6/caesar/caesar.py
854
4.5625
5
# means command line arguments can be used import sys # checks that only 2 arguments have been given if len(sys.argv) != 2: exit(1) # exits the program if the key is not an integer while True: try: key = int(sys.argv[1]) break except: exit() if key < 0: exit() while key > 26: key -= 26 plaintext = input("plaintext: ") print("ciphertext: ", end="") for char in plaintext: """Cycles through each character in the plaintext and prints its ciphertext version.""" char = ord(char) if char >= 65 and char <= 90: char += key if char > 90: char -= 26 print(chr(char), end="") elif char >= 97 and char <= 122: char += key if char > 122: char -= 26 print(chr(char), end="") else: print(chr(char), end="") print()
true
f8e27eeb55fa7cd5fb20ddb667309bfc3897ac65
jofabs/210-COURSE-WORK
/Task 2.py
655
4.1875
4
"""TASK 2 Count the number of trailing 0s (number of 0s at the end of the number) in a factorial number. Input: 5 Output: 1, Input: 10 Output: 2 Hint: Count the prime factors of 5""" #get input factorial number from user f = int(input("Enter a factorial number you want to trail zeros for: ")) def tailingZeros(f):#function defined containing users factorial number a = 1 # defining that a is 1 result = 0 while f >= a: # if f is greater or equal to a a *= 5 result += f//a # (floor divide) return result # elegant print statement print(str(f) + " has " + str(tailingZeros(f)) + " trailing zeros.")
true
106635ff03b655232dc33dba990e26341105f220
jofabs/210-COURSE-WORK
/Task 13.py
2,702
4.125
4
"""TASK 13 Write the pseudocode for an unweighted graph data structure. You either use an adjacency matrix or an adjacency list approach. Also, write a function to add a new node and a function to add an edge. Following that,implement the graph you have designed in python. You may use your own linked list from previous labs, the STL LL, or use a simple fixed size array (10 elements would be fine).""" class vertex(): #Class definition def __init__(self,value):#function definition self.value = value self.adjacentlist = [] def edgeaddition(self,vertex): #function definition self.adjacentlist.append(vertex) vertex.adjacentlist.append(self)#linking the nodes class Graph(): #Class definition def __init__ (self):#function definition self.listofnodes = [] def nodeaddition (self,value):#function definition self.listofnodes.append(vertex(value))#appenging the node to list return self.listofnodes[-1] def printing(self):#function definition for items in self.listofnodes: print(items.value, ":", end='') for m in items.adjacentlist: print(str(m.value),end='') print() #displays items of the graph eg: L:LL if __name__ == '__main__': #perfoming node addition print("The graph structure is:") d = Graph() #10 items(elements) nodeA = d.nodeaddition('A') nodeL = d.nodeaddition('L') nodeE = d.nodeaddition('E') nodeX = d.nodeaddition('X') nodeV = d.nodeaddition('V') nodeI = d.nodeaddition('I') nodeC = d.nodeaddition('C') nodeT = d.nodeaddition('T') nodeO = d.nodeaddition('O') nodeR = d.nodeaddition('R') nodeV.edgeaddition(nodeA) nodeI.edgeaddition(nodeL) nodeC.edgeaddition(nodeE) nodeT.edgeaddition(nodeX) nodeO.edgeaddition(nodeV) nodeR.edgeaddition(nodeI) nodeA.edgeaddition(nodeC) nodeL.edgeaddition(nodeT) nodeE.edgeaddition(nodeO) nodeX.edgeaddition(nodeR) #printing the items d.printing() """ #PSEUDOCODE CLASS VERTEX() value <- 0 adjacentlist = [] EDGEADDITION(VERTEX): APPEND THE VERTEX TO THE adjacentlist CLASS GRAPH() listofnodes <- [] FUNCTION NODEADDITION(VERTEX) APPEND VALUE OF VERTEX TO listofnodes FUNCTION PRINTING() FOR ITEMS IN LISTOFNODES DISPLAY THE VALUE OF ITEMS FOR EDGE IN adjacentlist OF ITEMS DISPLAY EDGE END FOR d <- Graph nodeA <- d.NODEADDITION('A') nodeA.EDGEADDITION(nodeA) d.PRINTING() """
true
22df9eade79c6d2944530289d6fd1750fdb8f154
Robert1GA/Python_Practice
/read_file.py
432
4.15625
4
# Read an entire file read_a_file = open('filename.txt', 'r') print(read_a_file.read()) read_a_file.close() # Read a line read_a_file = open('filename.txt', 'r') print('first line: ' + read_a_file.readline()) print('second line: ' + read_a_file.readline()) print('third line: ' + read_a_file.readline()) read_a_file.close() # Or.... read_a_file = open('filename', 'r') for line in read_a_file: print(line) read_a_file.close()
false
2c5ebc4a893593397a899518c1a65f492b213930
tbehailu/wat-camp-2014
/Day3/ex3sol.py
1,673
4.1875
4
# Q1 class VendingMachine(object): """A vending machine that vends some product for some price. >>> v = VendingMachine('crab', 10) >>> v.vend() 'Machine is out of stock.' >>> v.restock(2) 'Current crab stock: 2' >>> v.vend() 'You must deposit $10 more.' >>> v.deposit(7) 'Current balance: $7' >>> v.vend() 'You must deposit $3 more.' >>> v.deposit(5) 'Current balance: $12' >>> v.vend() 'Here is your crab and $2 change.' >>> v.deposit(10) 'Current balance: $10' >>> v.vend() 'Here is your crab.' >>> v.deposit(15) 'Machine is out of stock. Here is your $15.' """ "*** YOUR CODE HERE ***" def __init__(self, product, price): self.product = product self.price = price self.stock = 0 self.balance = 0 def vend(self): if self.stock == 0: return 'Machine is out of stock.' if self.balance < self.price: return 'You must deposit $' + str(self.price-self.balance) + ' more.' change = self.balance-self.price self.balance = 0 self.stock -= 1 if change != 0: return 'Here is your ' + self.product + ' and $' + str(change) +' change.' return 'Here is your ' + self.product + '.' def restock(self,more_stock): self.stock += more_stock return 'Current crab stock: ' + str(self.stock) def deposit(self, amount): if self.stock != 0: self.balance += amount return 'Current balance: $' + str(self.balance) return 'Machine is out of stock. Here is your $' + str(amount) + '.'
true
69803e6698abb9083d8fb9037330158c6785c5c2
Tossani/Phyton
/calculadora.py
748
4.125
4
print ("Calculadora em PYTHON") print (" Escolha uma das alternativas abaixo /n") print (" Digite 1 - para Soma: ") print (" Digite 2 - para Subtração: ") print (" Digite 3 - para Multiplicação: ") print (" Digite 4 - para Divisão: ") op = input(" Selecione a operação: ") num1 = int(input("Digite o primeiro número: ")) num2 = int(input("Digite o segundo número: ")) if op == "1": soma = num1 + num2 print ((num1), ' + ', (num2), ' = ', (soma)) if op == "2": sub = num1 - num2 print ((num1), " - ", (num2), " = ", (sub)) if op == "3": mult = num1 * num2 print ((num1), " * ", (num2), " = ", (mult)) if op == "4": divide = num1 / num2 print ((num1), " / ", (num2), " = ", (divide))
false
b9c469c886e07b506d630c3519de52d301fd7332
adityalprabhu/coding_practice
/CodingPad/Algorithms/QuickSort.py
1,141
4.375
4
# Quicksort implementation # function that swaps the elements def swap(arr, left, right): tmp = arr[left] arr[left] = arr[right] arr[right] = tmp # function that partitions the elements # and arranges the left array where elements < pivot and right > pivot def partition(arr, left, right): # pivot selection can also be in some other way # random? pivot = arr[int((left+right)/2)] while left <= right: while arr[left] < pivot: left += 1 while arr[right] > pivot: right -= 1 if left <= right: swap(arr, left, right) left += 1 right -= 1 return left # gets a partition and sorts the array for each partition def quicksort(arr, left, right): index = partition(arr, left, right) if left < index-1: quicksort(arr, left, index-1) if index < right: quicksort(arr, index, right) return arr # initial qsort def quicksort_initial(arr): return quicksort(arr, 0, len(arr)-1) if __name__ == '__main__': elements = [3, 2, 5, 25, 8, 0, 1, 64, 6] print(quicksort_initial(elements))
true
f562bc5a3aac08a4080fef03a43a353408e643af
CT-Kyle/mobiTest
/mobiTest/numPretty.py
2,055
4.34375
4
import sys #This program will take numbers and make them look all pretty #This block accepts any input as raw input and stores as a string. It is stored as a string so that #it can be sliced later for output. print "********** Welcome to the Number Prettifier **********" rawNum = raw_input('Enter a numerical value in the trillions or less: ') print "Input: " , rawNum #This block will remove digits after the decimal from the string and set floatFlag = true #This is done so that the len() method works correctly and to get output with a decimal place for float input if "." in rawNum: intNum = rawNum[0:rawNum.find(".")] floatFlag = True else: floatFlag = False intNum = rawNum if not intNum.isdigit(): print "You inputed a non int or float. Please restart and input an int or float." #This block prints the appropriate output if len(intNum) <= 6: print "Output:" , intNum else: if len(intNum) <= 9: print "Output:" , if floatFlag == True: #slices string to get appropriate value finalNum = intNum[0:len(intNum) - 6] + "." + intNum[len(intNum) - 6:len(intNum) - 4] print (str(round(float(finalNum), 1))) + "M" #converts str to float, rounds, and converts back to str else: print intNum[0:len(intNum) - 6] + "M" #simple print if it is not a float elif len(intNum) <= 12 and len(intNum) > 9: if floatFlag == True: finalNum = intNum[0:len(intNum) - 9] + "." + intNum[len(intNum) - 9:len(intNum) - 7] print (str(round(float(finalNum), 1))) + "B" else: print intNum[0:len(intNum) - 9] + "B" elif len(intNum) <= 15 and len(intNum) > 12: if floatFlag == True: finalNum = intNum[0:len(intNum) - 12] + "." + intNum[len(intNum) - 12:len(intNum) - 12] print (str(round(float(finalNum), 1))) + "T" else: print intNum[0:len(intNum) - 12] + "T" else: print "Number too large, please restart and enter a # in the trillions or less"
true
20836ecc29adb82fe99b29c798d8648b4b6997d8
tomvapon/snake
/logic/input.py
1,022
4.125
4
""" This file implements the load input for the files """ import sys import configparser def load_input_file(file): """ This function load an input file which contains the board dimensions, the snake and the depth. This simplifies the problem of manual console input and let check the three acceptance tests. :return: board (list), snake (list of lists), depth (int) """ # Load config parser config = configparser.ConfigParser() # Read first argument (data file) config.read(file) # Parse the inputs from string to its type # Board (str --> list) board_string = config['input']['board'] input_board = [int(element) for element in board_string.split(',')] # Snake (str --> list of lists) snake_string = config['input']['snake'] input_snake = [[int(el.split(',')[0]), int(el.split(',')[1])] for el in snake_string.split(';')] # Depth (str --> int) input_depth = int(config['input']['depth']) return input_board, input_snake, input_depth
true