blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e1cc745d937291b77e99c9ccb4da476efb248dde
rykovv/pytorch-modeling
/model_definition.py
1,982
4.15625
4
import torch from torch import nn # Very general outline for model definition using PyTorch. # models are usually defined using subclasses of nn.Module class class LogisticRegression(nn.Module): # nargs number of inpur variables for the logistic regression def __init__(self, nargs) -> None: super().__init__() # define model architecture # sequential means layering on in a sequential manner: # first linear layer and then # a sigmoid activation function self.log_reg = nn.Sequential ( nn.Linear(nargs, 1), # nargs is the size of the input going in, 1 output from all these inputs nn.Sigmoid() ) # forward method means what your model does on the forward pass given inputs to produce an output # what happens when an input is introduced, what output the model will return def forward(self, x): return self.log_reg(x) # Training a model in PyTorch # x - inputs, y - ground truth def train(x, y, n_epochs): # initialize the model (with 16 input vars) model = LogisticRegression(16) # define a cost function criterion = nn.BCELoss() # choose the optimizer to use (SGD - Stochastic Gradient Descent) # model.parameters is theta values updated during the training # lr - learning rate (hyper parameter) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # training loop for t in range(n_epochs): # Forward Propagation # get a prediction from the model given the input (pick up the input) y_pred = model(x[0]) # compare the prediction to the ground truth loss = criterion(y_pred, y[0]) # Back Propagation # zero out the gradients from before to ensure it is clean and good to go optimizer.zero_grad() # prepare the back propagation step loss.backward() # use SGD to update the parameters with lr learning rate optimizer.step()
true
2056c7f9121d2f0480b8f6eb699ac4aaa35b4abe
jillo-abdullahi/python-codes
/magicMethod__add__.py
333
4.15625
4
class Vector: #Class to demonstrate how to override + using the magic method __add__ def __init__(self,x,y): self.x = x self.y = y def __add__(self,other): return Vector(self.x+other.x,self.y+other.y) first = Vector(2,2) second = Vector(3,3) third = first + second print ('{},{}'.format(third.x,third.y))
true
7d01ec3279f518be1f23a5592721d17e6c7830d3
jillo-abdullahi/python-codes
/pythonCodeWars/nthDigitOfANumber.py
641
4.375
4
#The function findDigit takes two numbers as input, num and nth. It outputs the nth digit of num #(counting from right to left). # #Note # If num is negative, ignore its sign and treat it as a positive value. # If nth is not positive, return -1. # Keep in mind that 42 = 00042. This means that findDigit(42, 5) would return 0. # #Examples # findDigit(5673, 4) returns 5 # findDigit(129, 2) returns 2 # findDigit(-2825, 3) returns 8 def find_digit(num, nth): num = str(abs(num)) if nth < 1: return -1 elif len(num) < nth: return 0 else: return int(num[-nth]) print find_digit(5673, 5)
true
751aaecc64001bc9fe5ef11a279d6e1f7f6021ff
143034/python-study
/python-study/python/python知识点/列表处理.py
2,434
4.125
4
''' 字符串 h,n为数字 str1 + str2 str * h str[h] str[h:n] str[:n]从头开始截取str[h:]从h-1到尾末 格式化输出(占位符): print('%d',%变量) %d %s %f(浮点数)%.3f三位小数 转意符:\ \n, \, \t(加四个空格)r(之后不用转意) eval: eval(str): 将str当成有效计算并返回计算结果 ''' ''' str1 = 'hello' str2 = ' world' a = 10 print(str1 + str2) print(str1 * 5) print(str1[2]) print(str1[1:3]) print('l'in str1) print("%d" %a) print('%s\n%s' %(str1,str2)) print('i am \'a\' good\tman') print(r"\[;") print(r"https://www.bilibili.com/video/av19956343/?p=20") print(eval('123+456')) ''' ''' 闰年判断 闰年:能被四整除但不能被100整除 或能被400整除 ''' ''' date = int(input('请输入年份')) if (date//4==0 and date//100!=0) or (date//400==0): print('yes', date) else: print('no', date) ''' ''' #00000101 #11111010 #10000110(-6) print(~5) ''' ''' 列表: None值和0不是同一个概念,None是一个特殊值 列表里面存储的可以是不同类型的数据 list1 + list2 列表重复: list * num 列表截取: list[num:num] 二维列表: list[[],[],[]] 列表操作方法: append(加一个元素到列表) extend(加多个值到列表末尾)括号内必须使用列表 insert(num,元素)在下标处添加一个元素,源数据向后顺延 pop()删除元素,不传值时默认删除最后一个元素,移除列表中指定下标中的元素,返回删除数据(重要) remove() 删除所指定的列表中的元素 clear()清除所有数据 index(num,start,end)从列表中找到某个值的下标,寻找第一个 len(列表)长度 max(列表)取最大 min(列表)取最小 count()查看元素在列表中出现的次数 reverse()倒序列表 sort()升序 copy()拷贝列表 ''' ''' 元组用小括号表示() 元组转列表 ''' ''' list = [[1,2,3], [4,5,6], [7,8,9]] print(list[1][1]) list.extend([10,11,12]) print(list) list.append(13) print(list) ''' ''' list = [1,2,3,4,5] list.insert(2, 10) print(list) list.remove(10) print(list) list.pop(3) print(list) print(list.pop(2)) print(list) #list.clear() #print(list) print(list.index(2)) ''' #元组转列表 list = list((1,2,3,4)) print(list) #输出列表里第二大值 list = [] n = 0 while n < 5: a = int(input('输入五个数')) list.append(a) n +=1 print(list) list.sort() a = list.count(max(list)) i = 0 while i < a: list.remove(max(list)) i += 1 max(list) print(max(list))
false
b498da41f47dfec7f7a72ad6032a1c07a3713409
elliegarcia/Genome559_HW
/myfactorial_n_choose.py
968
4.3125
4
## This function calculates and returns the factorial of n def my_factorial(n): count = 1 # initialize a count if n <0: print "Cannot take the factorial of a negative number" else: for i in range (1, n+1): # for every integer in 1 to n+1 count = count*i # multiply the count by the integer and call it the new count return count # return the final count ## This function calculates the binomial coefficient "n choose k" def my_choose(n, k): n_k = n - k # make a variable for n - k numerator = my_factorial(n) # define the numerator kfact = my_factorial(k) # define the factorial of k n_kfact = my_factorial(n_k) # define the factorial of n - k binomial = numerator/(kfact*n_kfact) # put all the variables in the formula return binomial # return the binomial coefficient ### Running the functions #### import sys n = int(sys.argv[1]) k = int(sys.argv[2]) print my_factorial(n) print my_choose(n, k)
true
c484690efae090574749b321578a3de992eed6a6
courtneykelly/CodingChallenges
/Company/pinterest/q1.py
2,412
4.375
4
import os import sys """ This is the file with your answer, do not rename or move it. Write your code in it, and save it before submitting your answer. """ # Error Messages invalid_address = """\nInvalid address! Must be of the format: x.y.z.w:port x, y, z, w are integers ranging from 0 and 255, inclusive port is an integer ranging from 1 to 65,535, inclusive""" # Utility Functions # prints error message to help user identify error in socket address format def error(message): print message # checks the IP Address integers passed (ie. 127.12.23.43) are in range def check_ip_ints(ip_ints): r = range(0,256) for d in ip_ints: d = int(d) if d not in r: error('%d is not in range for IP Address integers' % d) return False return True # checks the port number passed is in range def check_port(port): port = int(port) r = range(1,65536) if port not in r: error('%d is not in range for port integers' % port) return False return True # Main Function def is_valid_socket_address(socket_address): """Determine if the provided string is a valid socket address. This function declaration must be kept unmodified. Args: socket_address: A string with a socket address, eg, '127.12.23.43:5000', to be checked for validity. Returns: A boolean indicating whether the provided string is a valid socket address. """ # Parse socket_address try: # replace : with . so split function only needs to be used once arguments = socket_address.replace(':','.').split('.') # check parsed result has the correct number of arguments (x,y,z,w,port) = 5 if len(arguments) == 5: # check IP Address integers and Port integer are in range if check_ip_ints(arguments[:4]) and check_port(arguments[4]): return True else: return False else: error(invalid_address) return False except ValueError as e: error(e) return False # This tests your code with the examples given in the question, # and is provided only for your convenience. if __name__ == '__main__': for socket_address in ["127.12.23.43:5000", "127.A:-12"]: print is_valid_socket_address(socket_address)
true
1d049b77d008595ea3ecbf29f0bb93cda4d621e7
akshaymandhan/Python-for-Data-Science
/List.py
1,805
4.625
5
# List functions # Generate List print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(thislist) # append element in existing list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # This will pop the last element of lIST print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) # This will remove specific item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) # insert element at specific position print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # this will clear the list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) # print length of list print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(len(thislist)) # print second index item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] print(thislist[1]) # change value of an item print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) # remove item from specific position print('----------------------------------------------------') thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist)
true
92213ae90516827ae36566a80c22ae156c224eb8
nagatok1/Python-AWS-Re-Start
/08Examaverage.py
654
4.125
4
def average(number1,number2,number3): if (number1 < 0 or number1 > 100 or number2 < 0 or number2 > 100 or number3 < 0 or number3 > 100): print("Invalid Mark") else: average_mark=(number1+number2+number3)/3 if average_mark >= 65: print(average_mark,"Pass") else: print(average_mark,"Fail") maths_mark= int(input("Maths Mark= ")) english_mark= int(input("English Mark= ")) it_mark= int(input("IT Mark= ")) print("Maths= ",maths_mark,"English =",english_mark,"IT = ",it_mark) average(maths_mark,english_mark,it_mark)
false
ec6501adcb5667c4c3149cc8a1c2fbec6abaac6d
BansiBirajdar/Assignment-8
/assignment8_1.py
984
4.3125
4
'''1.Design python application which creates two thread named as even and odd. Even thread will display first 10 even numbers and odd thread will display first 10 odd numbers.''' from threading import * class CheckNo(Exception): def __init__(self,value): self.value=value def Even(no): j=2 while(j<=no): if((j%2)==0): print("Even no:",j) j=j+1; def Odd(no): i=2 while(i<=no): if((i%2)!=0): print("Odd no:",i) i+=1; def main(): try: no=int(input("enter the no=")); if(no<=0): raise(CheckNo("Enter a positive no")) else: t1=Thread(target=Even,args=(no,)) t2=Thread(target=Odd,args=(no,)) t1.start() t2.start() t1.join() t2.join() except CheckNo as error: print("error occured::",error) if (__name__)=="__main__": main()
true
882b37d36adf7df901c3ab0b5eca7e6acf0834b0
Ashish-singh19/RTE2009
/Functions_database.py
1,009
4.15625
4
import sqlite3 from tkinter import * from tkinter import messagebox as mb #Creating root window and connecting database with our program conn = sqlite3.connect("Rte.db") cur = conn.cursor() def Create_table(): """Using this particular funtion we are creating all necessary tables in our database. """ cur.execute("CREATE TABLE if not exists total_birth (Father_Name TEXT, Date_of_birth DATE, Ration_Status TEXT, Child_Name TEXT)"); conn.commit() cur.execute("CREATE TABLE if not exists school_admission (Stu_Name Text, Father_Name Text, Date_of_birth Date)"); conn.commit() cur.execute("CREATE TABLE if not exists UnAdmissionStudent( Father_Name TEXT, Date_of_birth DATE, Ration_Status TEXT,Studnet_name TEXT)") conn.commit() def fetch_data(): """Using this particular funtion we are fetching all necessary data from our database. """ cur.execute("select * from UnAdmissionStudent order by Studnet_name") return cur.fetchall()
true
3a7e90725f9e64b4eaf0d59f0539cbef07d96778
Shreets/python-basisc-II
/q5.py
962
4.53125
5
# 5. Create a tuple with your first name, last name, and age. Create a list, # people, and append your tuple to it. Make more tuples with the corresponding information # from your friends and append them to the list. Sort the list. When you learn about sort method, # you can use the key parameter to sort by any field in the tuple, first name, last name, or age. bio1_tuple = ('shreeti','upreti',24) bio2_tuple = ('saru','shrestha',14) bio3_tuple = ('jasmin','tiwari',19) bio4_tuple = ('stuti','upreti',36) people = [] def list_of_people(*args): for arg in args: people.append(arg) return people people_list = list_of_people(bio1_tuple, bio2_tuple, bio3_tuple, bio4_tuple) people_list.sort(key= lambda item:item[2]) print(f'list of bio tuples sorted by age are: {people_list}') #OUTPUT # list of bio tuples sorted by age are: [('saru', 'shrestha', 14), ('jasmin', 'tiwari', 19), ('shreeti', 'upreti', 24), ('stuti', 'upreti', 36)]
true
89fb851f48edb8c185b00078a2ded0474acfd431
Shreets/python-basisc-II
/q2.py
486
4.3125
4
# 2. Write an if statement to determine whether a variable holding a year # is a leap year. year = input('enter a year to check if it is a leap year : ') if int(year) % 4 == 0 and int(year) % 100 != 0: print(f'The year {year} is a leap year') else: print(f'The year {year} is NOT a leap year') # OUTPUT # enter a year to check if it is a leap year : 2000 # The year 2000 is NOT a leap year # enter a year to check if it is a leap year : 2012 # The year 2012 is a leap year
false
a163da2b9629195892b22ba6e19efd42437ec3c4
Shreets/python-basisc-II
/q17.py
779
4.3125
4
# 17. Write a program that serves as a basic calculator. It asks for two numbers, then it asks for an operator. # Gracefully deal with input that doesn't cleanly convert to numbers. Deal with division by zero errors. first_num = int(input('Enter first number : ')) second_num = int(input('Enter second number : ')) operator = input('Enter operator : ') def calculator(num1, num2, op): if op == '+': return num1 + num2 if op == '-': return num1 - num2 if op == '*': return num1 * num2 try: if op == '/': return num1 / num2 except ZeroDivisionError: print('The number cannot be divided by 0. Please try again with another number') calculate = calculator(first_num, second_num, operator) print(calculate)
true
1e75d1210eb4ded6386adc88ec9663aded38eee3
zainabaderinmola/Python-Crash-Course
/task4.py
1,832
4.21875
4
""" 1) Index to rerun 'how old' from string 'Hello there, how old are you' """ my_string = 'Hello there, how old are you?' h_index = my_string.find('how') d_index = my_string.find('d') + 1 print(f"'how old' will be printed with my_string[{h_index}:{d_index}]") #2 Result of story[2:4] + story[-1] story = "Python is awesome" story_line = story[2:4] + story[-1] print(f"Output of story[2:4] + story[-1] is '{story_line}'.") #3 Find len(mystring) mystring = "Python rocks" length = len(mystring) print(f"len(mystring) is: {length}") #4 Can we change "Rose" to "Pose" "No. Strings are immutable" #5 What is word[-4:] * 3 word = 'Python is so cool' new_word = word[-4:] * 3 print(f"The output of word is: {new_word}") #6 What code that returns 'pepsi' as "PEPSI" drink = 'pepsi' new = drink.upper() print(f"This code: 'code.upper()' returns {drink} as {new}") #7 code that returns 'macdonald' as MacDonald name = 'macdonald' code = name[:3].capitalize() + name[3:].capitalize() print(f"This program:'name[:3].capitalize() + name[3:].capitalize()' returns {name} as MacDonald") #8 code that returns 'MUSHRAH' as 'mushrah' name = 'MUSHRAH' lower = name.lower() print(f"This code: 'name.lower()' changes '{name}' to 'mushrah'.") #9 built-in method to change string to list mystring = "Hello World" code = mystring.split() print(f" 'mystring.split()' will split {mystring} into {code}.") #10 Remove "Hello" from "Hello World" my_string = "Hello World" new_string = my_string.replace("Hello ", "") print(f"I will remove Hello from {my_string} using 'my_string.replace('Hello ', '')'.") #11 Index of first string in a character print(f"The first index of a string is 0") #12 Count of 'o' in a string my_string = "Hello, python is sooo cool" amount = (my_string.count('o')) print(f"The number of 'o' in {my_string} is: {amount}")
true
cedac3f887c4a847b7442b7893e5d425bc4e1c64
crepric/google_jterm
/python_unit_testing/unittest_lab/tic tac toe/tic_tac_toe.py
2,220
4.1875
4
# You are asked to implement a tic-tac-toe game. # You are expected to prepare a class named TicTacToeBoard, that implements # the following methods: # # reset_board(): # prepares you object for a new game. The return value is not important. # player_move(x, y, player_number): # accepts a new move from player, at coordinates x, y. # returns a BaseException if the player numver is not 1 or 2 # # When player_move() is called, it should return an integer value with the # following meaning: # # 0 → No winner, game continues # 1 → This is a winning move, the game is over # -1 → No winner, no more moves, the game is a draw. class TicTacToeBoard: cols = [] rows = [] diag = [] board = [] moves = 0 def __init__(self): self.reset_board() def update_and_check(self, direction_tracker, player_number): if (player_number != 1 and player_number != 2): return False direction_tracker[player_number-1] += 1 return True if direction_tracker[player_number-1] == 3 else False def player_move(self, x, y, player_number): # Sanity Check if (player_number == 1 and player_number == 2): raise BaseException('Illegal player number.') if (self.board[x][y] != 0): raise BaseException('This cell is already occupied by player: %d' & board[x][y]) self.board[x][y] = player_number if self.moves > 9: return -1 # Rows if self.update_and_check(self.rows[x], player_number): return 1 # Columns if self.update_and_check(self.cols[y], player_number): return 1 # Diagonal if (x==y): if self.update_and_check(self.diag[0], player_number): return 1 # Antidiagonal if (x == y-2): if self.update_and_check(self.diag[1], player_number): return 1 self.moves += 1 return 0 def reset_board(self): self.board = [[0 for y in range(3)] for x in range(3)] self.rows = [[0 for y in range(2)] for x in range(3)] self.cols = [[0 for y in range(2)] for x in range(3)] self.diag = [[0 for y in range(2)] for x in range(2)] self.moves = 0
true
084be96cc9cd6fb58b4cb8cb117a2c5120fb8af3
rohitf/experiments
/dynamic-programming/oscillations.py
504
4.125
4
arr = [] def even_odd(n): return "even" if n%2 == 0 else "odd" def longestOscillation(nums): for i, num in enumerate(nums): if i == 0: arr.append(0) if even_odd(num) == "even" and nums[i] > nums[i-1]: arr.append(1 + arr[-1]) if even_odd(num) == "odd" and nums[i] < nums[i-1]: arr.append(1 + arr[-1]) else: arr.append(arr[-1]) return arr[-1] nums = [1,4,3,2,7,9,3] print(longestOscillation(nums)) print(arr)
false
a7e51fd59d29b024fca8ccf17ff9766c96d37280
luckyzachary/Algorithms
/Python3/Textbook/sort/merge_sort.py
1,819
4.1875
4
""" 标准归并排序 """ def merge_sort(arr, temp_arr, left, right): """ 归并排序 稳定 最小、最大、平均时间代价均为 O(nlogn) 空间代价, 为 O(n) """ if left >= right: return arr middle = (left + right) // 2 merge_sort(arr, temp_arr, left, middle) merge_sort(arr, temp_arr, middle + 1, right) merge_1(arr, temp_arr, left, right, middle) return arr def merge(arr, temp_arr, left, right, middle): for i in range(left, right + 1): temp_arr[i] = arr[i] li, ri = left, middle + 1 index = left while li <= middle and ri <= right: if temp_arr[li] <= temp_arr[ri]: arr[index] = temp_arr[li] li += 1 else: arr[index] = temp_arr[ri] ri += 1 index += 1 while li <= middle: arr[index] = temp_arr[li] li += 1 index += 1 while ri <= right: arr[index] = temp_arr[ri] ri += 1 index += 1 """ 改进归并排序 1、复制右半部分数组时,可以倒序复制,避免判断子序列结束的情况。merge_sort()不变。 2、当顺序基本有序时,可以改用插入排序,threshold 可以选用9, 16, 28。这只能在C++中实现, Python中传不了浅复制的数组分段。 """ def merge_1(arr, temp_arr, left, right, middle): for i in range(left, middle + 1): temp_arr[i] = arr[i] for j in range(0, right - middle): temp_arr[middle + 1 + j] = arr[right - j] li, ri = left, right index = left while index <= right: # 或者是 li <= ri if temp_arr[li] <= temp_arr[ri]: arr[index] = temp_arr[li] li += 1 else: arr[index] = temp_arr[ri] ri -= 1 index += 1
false
081d13a79ca7ce7843a0ed20c4f32f9450b42cb3
Skipper609/python
/assignment/M1/q6.py
278
4.5
4
'''6. write a program to take a number as a input and display its reverse''' def reverse_num(num): rev = 0 while num > 0: rev = rev * 10 + num % 10 num = num // 10 return rev num = int(input("Enter the number :")) print("The reverse is ",num)
true
43e1aae6d5c073317b9ed511c0c00d56d5b9c4d5
Skipper609/python
/Sample/big.py
255
4.25
4
num1 = int(input("Enter Num1 :")) num2 = int(input("Enter Num2 :")) num3 = int(input("Enter Num3 :")) if num1 > num2 and num1 > num3: big = num1 elif num2 > num3: big = num2 else: big = num3 print(f"Biggest of {num1},{num2},{num3} is {big}")
false
13f7244cf3668387d2756343cc45248eeb0a90de
Skipper609/python
/Sample/factorial.py
254
4.3125
4
'''To Find the factorial of a number''' N = int(input("Enter a number to find its factorial :")) fact = 1 if N > 0: for i in range(2, N+1): fact *= i print(f"Factorial of {N} is {fact}") else: print(f"Factorial of {N} doesnt exist")
true
4b9395faf32292b9dc5da3aece8284c934c9006b
SujanMaga/Python-prac-for-ref.
/test/Basic/prac2_string.py
310
4.34375
4
# name = input("Enter your name") # print("Good morning,",name) letter = '''Dear <|NAME|>, You are selected! Date: <|DATE|> ''' name = input("Enter name here\n") date = input("Enter date\n") letter = letter.replace("<|NAME|>", name) letter = letter.replace("<|DATE|>", date) print(letter) # Template for mail
false
1f8d5d29fa606ef1ad37e6bd2d6a0bdd04739aba
SujanMaga/Python-prac-for-ref.
/test/Dictionary_sets/Dictionary_01.py
346
4.375
4
myDict = { 'Fast': 'Very rapidly', 'Magnificant' : 'Wonderful', 'Marks' : [1,3,44] } print(myDict['Fast']) print(myDict['Magnificant']) print(myDict['Marks']) # Prints value of keys inside of a dictionary d1 = { "namaste" : {"sagarmatha": "Highest peak in the world"} } print(d1['namaste']['sagarmatha']) # nested dictionaries
false
56482b6d1b784b6135ca00e3fc90e78b34dc3766
SujanMaga/Python-prac-for-ref.
/test/Conditional_Expression/01_conditional.py
255
4.25
4
a = 45 if(a>4): print("The value of a is greater than 4") elif(a>7): print("The value of a is greater than 7") else: print("The value of a is not greater nor lesser than 3 or 7") # demo syntax # to check all the statement if if if can be used
true
581b1fa712d7604e66d2e1cdc81958ee5f4edf98
SujanMaga/Python-prac-for-ref.
/New folder/prac_12.py
262
4.15625
4
# def exponent(base, exp): # print(base**exp) # exponent(2,5) # exp = non negative def exponent(base, exp): num = exp result = 1 while num > 0: result = result * base num = num-1 print(result) exponent(2,5)
false
770af074e1ca854d88fb82b1e3553125c729cae7
brandonjayster/python_newb
/Data analysis/list_in_python.py
597
4.5625
5
computers = ['dell', 'alienware', 'hp', 'lenvoe', 'surfacebook'] #print out the list print('Computer list', computers) #add Apple computers to the list computers.append('Apple') print('Appended:', computers) print(len(computers)) #tuples which are not used much as but is practiclly the same computers = ('dell', 'alienware', 'hp', 'lenvoe', 'surfacebook') print('computers', computers) # below we are indexing this works the same in a list just as a tuple print('computers:', computers[-1]) #the out put will be surfacebook #sets in python is the same as tuples or list but with curly brackets
true
0312823e1a3844dfbaf79d93f6f65201ea5e9f2d
tefsantana/COSTA-ALGO1-public
/Ejercicios/C02 - Ciclos - Parcial de Computacion.py
1,971
4.21875
4
''' Dados los padrones y notas de las 5 cátedras del parcial de Computación, realice un programa que indique: a) Padrón de la primera persona que aprobó de cada curso b) Cuantas personas (por curso) obtuvieron esa misma nota que obtuvo el primero que aprobó (de su curso). c) Porcentaje de reprobados general de todas las cátedras. d) Promedio de cada cátedra. Observaciones: · La cantidad de alumnos por curso es indeterminada inicialmente, debe consultarse al usuario si desea seguir ingresando información o no. · Se considera aprobado cualquier nota mayor o igual a 4 ''' totalAlumnos = 0 totalDesaprobados = 0 for catedraNro in range(1,6): ingreso = True print("-----" + "Catedra " + str(catedraNro) + "-----") aprobados = 0 desaprobados = 0 cantPrimerNotaAprobada = 0 totalNotas = 0 while ingreso: padron = input("Ingrese el Numero de Padron del Alumno: ") nota = float(input("Ingrese la nota del alumno " + str(padron) + ": ")) totalNotas += nota if nota >= 4: aprobados += 1 if aprobados == 1: primerNotaAprobada = nota print("El primer aprobado de la catedra " + str(catedraNro) + " es: " + padron) else: if primerNotaAprobada == nota: cantPrimerNotaAprobada += 1 else: desaprobados += 1 if input("Desea seguir ingresando información? s/n: ").lower() != "s": ingreso = False totalDesaprobados += desaprobados totalAlumnos += desaprobados+aprobados print("La cantidad de alumnos que obtuvieron la misma nota que obtuvo el primero aprobado es: " + str(cantPrimerNotaAprobada)) print("El promedio general de la catedra " + str(catedraNro) + " es: " + str(totalNotas/(aprobados+desaprobados))) print("El procentaje general de alumnos desaprobados es: " + str(totalDesaprobados*100/totalAlumnos)) print("Adios!")
false
5214117335c3178012c63a584d88e42bb5412c1d
tefsantana/COSTA-ALGO1-public
/Ejercicios/C01 - Condicionales - Maximos y Minimos.py
941
4.375
4
''' Escribe un prorgrama en Python que solicite al usuario 5 números enteros. Luego imprimir el máximo y el mínimo de los valores ingresados. El programa deberá permitir el ingreso de valores iguales. ''' num1 = int(input("Ingrese el primer numero: ")) num2 = int(input("Ingrese el segundo numero: ")) num3 = int(input("Ingrese el tercer numero: ")) num4 = int(input("Ingrese el cuarto numero: ")) num5 = int(input("Ingrese el quinto numero: ")) # Inicializo el maximo y el minimo max = num1 min = num1 # Busco el maximo real if max < num2: max = num2 if max < num3: max = num3 if max < num4: max = num4 if max < num5: max = num5 # En otro caso -> num1 era el maximo # Analogamente busco el minimo real if min > num2: min = num2 if min > num3: min = num3 if min > num4: min = num4 if min > num5: min = num5 print(f"El maximo numero ingresado es: {max}") print(f"El minimo numero ingresado es: {min}")
false
0b054b8dae8c09f4c2056325a4cfd09eeb07963f
Shakirsadiq6/Basic-Python-Programs
/Lists-upto-exception handling/Functions, File Handling, Modules and Exception Handling/appending.py
900
4.40625
4
'''Program to append any input text at the end of a file. Find size of a given file before and after appending content''' __author__ = "Shakir Sadiq" import os try: myfile = open("file.txt","r") print(myfile.read()) file_size_before = os.path.getsize("C:\\Users\\Shakir\\OneDrive\\Desktop\\Py\\Assignment5-Functions, File Handling, Modules\\file.txt") print("The size of the file before appending=",file_size_before) open_file = open("file.txt","a") append_file = open_file.write("\nPython is used in web development.") open_file.close() print() mynewfile = open("file.txt","r") print(mynewfile.read()) file_size_after = os.path.getsize("C:\\Users\\Shakir\\OneDrive\\Desktop\\Py\\Assignment5-Functions, File Handling, Modules\\file.txt") print("The size of the file after appending=",file_size_after) except FileNotFoundError: print("File not found.")
true
b88ed4729ec7bd5048f4b7a4c49a19b67a237521
Shakirsadiq6/Basic-Python-Programs
/Lists-upto-exception handling/List, Tuple and Dictonary/name.py
350
4.25
4
'''Return names exists in the list. If you insert any name into the list. It should return with other names automatically''' __author__ = "Shakir Sadiq" name = ['harry','ron'] print("list of names:", name) for i in range(0,5): i = input("Enter a name: ") if i not in name: name.append(i) print(name) else: print(name)
true
41b9c71942232a91f9c500dc08a30e73bfc57380
Shakirsadiq6/Basic-Python-Programs
/Basics_upto_loops/Getting Started/distance.py
436
4.28125
4
'''print the distance between cities in meters, feet, inches and centimeters''' __author__ = "Shakir Sadiq" kilometer = float(input('Enter distance between cities(in km)= ')) meter = kilometer*1000 centimeter = kilometer*100000 feet = kilometer*1000*100*0.0328 inch = kilometer*1000*100*0.3937 print('Distance in meter= ',meter) print('Distance in centimeter= ',centimeter) print('Distance in feet= ',feet) print('Distance in inch= ',inch)
false
0f6756ccebb415fe2f01c8dcfd3b76b0a6402cb7
Shakirsadiq6/Basic-Python-Programs
/Basics_upto_loops/More examples/pos.py
540
4.25
4
'''Decide the place of service of an employee based on their age, sex and marital status''' __author__ = "Shakir Sadiq" age = int(input("Enter your age: ")) sex = input("Enter your gender(M/F): ") marital_status = input("Are you married(Y/N)?: ") if sex == "F" or "f" and age>=20 and age<=60: print("you will work in urban areas only") elif sex == "M" or "m" and age>40 and age<=60: print("You will work in urban areas only") elif sex == "M" or "m" and age>=20 and age<=40: print("You can work anywhere") else: print("ERROR")
true
dd4b25d546c59e5b5f5728597098a8e71f2ce600
Shakirsadiq6/Basic-Python-Programs
/Lists-upto-exception handling/List, Tuple and Dictonary/person.py
638
4.125
4
'''Make a list of cities chosen by adults and print which person has chosen which city''' __author__ = "Shakir Sadiq" persons = ['harry','ron','peter','alishba'] cities = [] for i in range(0,4): print() print("Name:",persons[i]) age = persons[i] = int(input("Age: ")) sex = persons[i] = input("Gender: ") location = persons[i] = input("Location: ") if age > 18: persons = ['harry','ron','peter','alishba'] print("Welcome",persons[i]) city = input("Choose a city: ") cities.append(city) print("City selected by",persons[i],"is",city) print("\nCities selected by adults:",cities)
false
f37dbe73a742e353704bd27561b94c4253df96c3
Shakirsadiq6/Basic-Python-Programs
/Basics_upto_loops/Loops/power.py
328
4.34375
4
'''program to find the value of one number raised to the power of another''' __author__ = "Shakir Sadiq" number1 = int(input("Enter the value of the number=")) number2 = int(input("Enter the power of the number=")) POWER = 1 for i in range(1, number2+1): POWER *= number1 print(number1, "raised to power", number2, "is", POWER)
true
cfa1fd8f0d9d2c7015deab5f91f68d5860d16322
Knadsen/Himen
/is105/lab/python/exercises/ex3.py
881
4.5
4
#This simple print statement will print everything between the parantheses print "I will now count my chickens:" #Prints "Hens" then the problems result. Following the rules of math; 30 / 6 will be calculated first and then add 25 print "Hens", 25 + 30 / 6 #The next line uses subtraction, multiplication and a modulus, though the result seesm to be wrong print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" #Proposes a statement, the Python program will print either True or false, depending on whether it is or isn't print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
af97fcbddb56fb71149dae9ac934ebcf3af7b643
Svyat33/beetroot_python
/lesson_8_try_except/lesson8_task2_foo_try_valueerror_zerodivision.py
940
4.3125
4
# Task 2 # Write a function that takes in two numbers from the user via input(), # call the numbers a and b, and then returns the value of squared a divided by b, # construct a try-except block which raises an exception if the two values given # by the input function were not numbers, and if value b was zero (cannot divide # by zero). def foo(arg1, arg2): try: ret = a ** 2 / b return ret except ZeroDivisionError: print('Dividing by Zero is unacceptable') exit(1) def inp_check(): try: a = int(input(f'Please, enter value for numeric value for "a": ')) b = int(input(f'Please, enter value for numeric value for "b": ')) # print('Numbers accepted') return a, b except ValueError: print('Values for "a" and "b" must be only numeric') exit(1) if __name__ == '__main__': a, b = inp_check() result = foo(a, b) print(result)
true
2c2ba1396871111c2f73a49480eb5d75f9023f15
Svyat33/beetroot_python
/lesson_5_list_tuple_set/lesson5_task3_extracting_numbers.py
928
4.125
4
# Task 3 # Extracting numbers. # Make a list that contains all integers from 1 to 100, then find all integers # from the list that are divisible by 7 but not a multiple of 5, and store them # in a separate list. Finally, print the list. # Constraint: use only while loop for iteration digit_list = [] num_counts = 1 while num_counts <= 100: digit_list.append(num_counts) num_counts += 1 # Checking random/insert # print(digit_list_random) # Checking list num_counts = 0 print('List ready : ' + str(digit_list)) # digit_list_random = [] # count_index = 0 # # while count_index <= 9: # digit_list_random.insert(0, randint(1, 10)) # count_index += 1 # # Checking random/insert # # print(digit_list_random) # # Checking list # # print('List ready : ' + str(digit_list_random)) # digit_list_sorted = sorted(digit_list_random) # print('The largest number is: ' + str(digit_list_sorted[-1]))
true
609a7960b2bc17474463cae41028c560e9eeb0be
Svyat33/beetroot_python
/lesson_7_functions/lesson7_task3_simple_calculator.py
2,428
4.5625
5
# lesson_7_functions. Task 3 # A simple calculator. # Create a function called make_operation, which takes # in a simple arithmetic operator as a first parameter # (to keep things simple let it only be ‘+’, ‘-’ or ‘*’) # and an arbitrary number of arguments (only numbers) as # the second parameter. Then return the sum or product of # all the numbers in the arbitrary parameter. For example: # # the call make_operation(‘+’, 7, 7, 2) should return 16 # the call make_operation(‘-’, 5, 5, -10, -20) should return 30 # the call make_operation(‘*’, 7, 6) should return 42 def make_operation(action, *args): def my_add(a, b): return a + b def my_sub(a, b): return a - b def my_mul(a, b): return a * b def my_div(a, b): return a / b actions_list = ['+', '-', '*', '/'] if action in actions_list: print(f'ARGS имеет следующие значения: {args}, с длиной {len(args)} и типом {type(args)}') i = 0 res = args[0] print(f'Первичный res равен: {res}') if action == '+': for i in args[1:]: res = my_add(res, i) print(f'при добавлении {i} к {res}, получен результат: {res}') return res elif action == '-': for i in args[1:]: res = my_sub(res, i) print(f'при вычитании {i} от {res}, получен результат: {res}') return res elif action == '*': for i in args[1:]: res = my_mul(res, i) print(f'при умножении {i} на {res}, получен результат: {res}') return res elif action == '/': try: for i in args[1:]: res = my_div(res, i) print(f'при делении {i} на {res}, получен результат: {res}') except ZeroDivisionError: print(f'На 0 делить нельзя') return res else: print('Был использован неправильный оператор') if __name__ == "__main__": try: a = make_operation('*', 5, 5, 10, -20) print(a) except: print('Что то не получилось')
true
c9799bbf2afd042cb251a753c7db70d6aab280ee
smg111/CodeAcademy
/python/number-guess.py
996
4.15625
4
# Guess a number.. you win if the number guessed is greater than the sum of the two rolls of a pair of 7-sided dice. from random import randint from time import sleep def get_user_guess(): user_guess = int(raw_input("Please guess now: ")) return user_guess def roll_dice(number_of_sides): first_roll = randint(1,number_of_sides) second_roll= randint(1,number_of_sides) max_val = number_of_sides*2 print "The maximum possible value is " + str(max_val) sleep(1) user_guess = get_user_guess() if user_guess > max_val: print "Guess is larger than the max value." return else: print "Rolling..." sleep(2) print "First roll: "+ str(first_roll) sleep(1) print "Second roll: "+ str(second_roll) sleep(1) total_roll = first_roll + second_roll print str(total_roll) print "Result..." sleep(1) if user_guess > total_roll: print "You won!" return else: print "Sorry, you lost!" return roll_dice(7)
true
24137250b1bb9324948df3ef12e91d5c78074bc4
AnLi-Mi/Python_Studying_Projects
/mini_projects/Project Checking Odd and Even numbers.py
1,145
4.25
4
#Ask the user for a number. #Depending on whether the number is even or odd, #print out an appropriate message to the user. #Hint: how does an even / odd number react differently when divided by 2? #Extras: #1-If the number is a multiple of 4, print out a different message. #2- Ask the user for two numbers: one number to check (call it num) #and one number to divide by (check). #If check divides evenly into num, tell that to the user. #If not, print a different appropriate message. #---------------Solution--------------- #requesing the user for the numbers num = int(input('Proszę podać dowolną liczbę: ')) divider = int(input('Proszę wpisać dowolną liczbę przez którą chcesz podzielić powyższą liczbę: ')) # checking if the inserted number is odd or even and a multiple of 4 if num%2==0 and num%4==0: print (f'{num} jest parzysta i podzielna przez 4.') elif num%2==0: print (f'{num} jest parzysta,ale niepodzielna przez 4.') else: print (f'{num} jest nieparzysta.') if num%divider==0: print (f'{num} jest podzielna przez {divider}.') else: print (f'{num} nie jest podzielna przez {divider}.')
false
8fc0935e70f2e689d731803a7028fb72c7ea68b9
AnLi-Mi/Python_Studying_Projects
/mini_projects/Project Crypting Machine.py
1,745
4.4375
4
print('----------------------Project-Crypto---------------------------') # Creating an encrypting or decrypting (depenading on the usre's request) machine # that replaces each letter of given string with a letter with the same index in # the rotated alphabet (zyxwu...) import random, string #asking user to choose if they want to encode or decode task = input("Type 'E' if you wnat to encrypt or 'D' if you want to decrypt") #asking user to input the messange they want to encrypt/decrypt word = str(input("Type in the secret word: ")) word_new = [] # creating a string of the alphabet letter to use in the crypting machine keys= string.ascii_lowercase # creating a string of the roteated alphabet letter to use in the crypting machine values = keys[::-1] # actual code of the encoding machine replacing letters code_en=dict(zip(keys, values)) # actual code of the decoding machine replacing letters code_de=dict(zip(values, keys)) # executing the replacing code and putting the replaced latters together into a new word if task=="e" or task=="E": for letter in word: letter = code_en[letter] word_new.append(letter) elif task=="d" or task=="D": for letter in word: letter = code_de[letter] word_new.append(letter) #printing the result as a whole word print("".join(word_new)) print('----------------------solution with compehension---------------------------') if task=="e" or task=="E": word_en = [code_en[letter] for letter in word] print("Encrypted word is: " + "".join(word_en)) elif task=="d" or task=="D": word_de = [code_de[letter] for letter in word] print("Encrypted word is: " + "".join(word_de)) else: print('error')
true
e8be666dbffe89a525829f7e8757e46f83e9f8f2
AnLi-Mi/Python_Studying_Projects
/mini_projects/Project Listing Overlaping Elements.py
1,101
4.25
4
#Take two lists, say for example these two: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #and write a program that returns a list that contains only #the elements that are common between the lists (without duplicates). #Make sure your program works on two lists of different sizes. #Extras: #Randomly generate two lists to test this #Write this in one line of Python #---------------------------SOLUTION--------------------- import random #random selection of a lenght of the first list r=random.randrange(1,11) #random selection of a lenght of the second list p=random.randrange(1,11) #generating list of random numbers between 1 and 9 a = random.choices(range(1,10),k=r) print(f'lista a= {a}') b = random.choices(range(1,10),k=p) print(f'lista b= {b}') #preparing an empty list to generate it with common numbers c=[] #solution with 'in' for i in a: if i in b: c.append(i) #turning into a set to get rid of duplicates c=list(set(c)) c.sort() #turnig back to list again print (f'Wspólnymi elementami obu list są: {c}')
true
f1426a636d7eb70e1f41f90c86cf5e96f72a6b8d
AnLi-Mi/Python_Studying_Projects
/mini_projects/Project Max of Three.py
597
4.65625
5
# Implement a function that takes as input three variables, #and returns the largest of the three. #Do this without using the Python max() function! #The goal of this exercise is to think about some #internals that Python normally takes care of for us. #All you need is some variables and if statements! #--------------------SOLUTION --------------- #requestig an inpit of 3 numbers numbers = input('Please enter 3 numbers: ') # turning a string input into a list of numbers numbers = list(numbers.split(' ')) # returning the highest number print (f'The highest number is: {max(numbers)}')
true
c1410748304b55786f8c6db11787614ef6237e11
AnLi-Mi/Python_Studying_Projects
/mini_projects/Project Element Extracting from List.py
1,179
4.25
4
# Take a list, say for example this one: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # and write a program that prints out all the elements of the list #that are less than 5. #Extras: #Instead of printing the elements one by one, #make a new list that has all the elements less than 5 from this list in it #and print out this new list. #Write this in one line of Python. #Ask the user for a number and return a list that contains #only elements from the original list a that are smaller #than that number given by the user. # ------------------------------- solution ---------------------------------- #defining the list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #asking user to input the number the program comares the list's elements to num = int(input(f'Proszę podać dowolną liczbę: ')) print('solution 1----------------------') for i in a: if i<num: print (i) print('solution 2----------------------') i=0 while i <len(a): if a[i]<num: print (a[i]) i+=1 print('solution 3----------------------') #prepearing empty list to fill it out with extracted elements of list a b=[] for i in a: if i<num: b.append(i) print (b)
true
322b61c84b2b4fe5a3623ee6d88930466dde994e
stitchelle/PizzaJoint
/classes.py
1,321
4.65625
5
# 1. Create a Pizza type for representing pizzas in Python. Think about some basic properties that would define a pizza's values; things like size, crust type, and toppings would help. Define those in the __init__ method so each instance can have its own specific values for those properties. # 2. Add a method for interacting with a pizza's toppings, called add_topping. # 3. Add a method for outputting a description of the pizza (sample output below). # 4. Make two different instances of a pizza. If you have properly defined the class, you should be able to do something like the following code with your Pizza type. class Pizza: def __init__(self): # Establish the properties of each book # with a default value self.size = "" self.style = "" self.topping = [] self.sauce = "" def add_topping(self, topping): self.topping.append(topping) print(f'{self.topping}') meat_lovers = Pizza() meat_lovers.size = 16 meat_lovers.style = "Deep dish" meat_lovers.add_topping("Pepperoni") meat_lovers.add_topping("Olives") # meat_lovers.print_order() for n in meat_lovers.topping: print(n) s = " and " s = s.join(meat_lovers.topping) print(s) print(f'I would like a {meat_lovers.size} inch, {meat_lovers.style} pizza with {s}.')
true
2d038acc3495d63826185fdb8629cedc2e86feb6
Edywang/Curated-Schoolwork
/CSE30MSI/exercises/inheritance.py
1,804
4.125
4
class Person: def __init__(self, fname, lname): self._firstname = fname self._lastname = lname def printname(self): print(self._firstname, self._lastname) class Adult: def __init__(self, name0 = "Edwin", name1 = "Wang", gender = "non-binary", married = False): if gender.lower() == "male": self._lname = "Mr. " + name1 elif gender.lower() == "female": self._lname = "Ms. " + name1 else: self._lname = "Mx. " + name1 self._fname = name0 def printname(self): print(self._lname) class Student(Person): pass # Use the pass keyword when you do not want to add any other properties or methods to the class. class Professor(Person, Adult): pass # Use the pass keyword when you do not want to add any other properties or methods to the class. # TODO: Create a person class and call its printname function # TODO: Create a student class and call its printname function # Replace this comment with your code for the above TODOs # BEFORE YOU CREATE A PROFESSOR CLASS, What do you think it'll print when we call its printname function? # Replace this comment with your answer to the above question # TODO: Create a professor class and call its printname function # What happened to the professor? Which printname did it use? # Replace this comment with your answer to the above question # Why might the professor may have used the printname that it did? # Replace this comment with your answer to the above question # Do we remember what the underscore before a variable name means? # Replace this comment with your answer to the above question # What if we put two underscores before a method name? (If you don't remember, try it) # Replace this comment with your answer to the above question
true
346c20a6d4381f830e6560b560fdcca809b748b8
arthurshmidt/Udemy-Python
/HW_ObjO_Prog.py
1,313
4.21875
4
# Homework Object Oriented Programming # Problem: Fill in the line methods to accept coordinates as a pair of tuples # and return the slope and distance of the line. class Line: def __init__(self,coor1,coor2): self.coor1 = coor1 self.coor2 = coor2 def distance(self): return ((self.coor2[0]-self.coor1[0])**2 + (self.coor2[1]-self.coor1[1])**2)**0.5 def slope(self): return (self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]) # Testing class coordinate1 = (3,2) coordinate2 = (8,10) li = Line(coordinate1,coordinate2) print(li.coor1) print(li.coor2) slope = li.slope() print("The Line slope is: {}".format(slope)) print("The Line distance is: {}\n".format(li.distance())) # Problem: Fill in the class class Cylinder: pi = 3.1415 def __init__(self,height=1,radius=1): self.height = height self.radius = radius def volume(self): return Cylinder.pi*(self.radius**2)*self.height def surface_area(self): top_bottom = 2 * (Cylinder.pi * (self.radius**2)) sides = 2 * Cylinder.pi * self.radius * self.height return top_bottom + sides # Testing of the Cylinder Class: c = Cylinder(2,3) print("The volume of the cylinder is: {}".format(c.volume())) print("The surface area of the cylinder is: {}\n".format(c.surface_area()))
true
5ad26b671525512ef3e562cd55c29eff4c46a710
prohladenn/SPbSTU_PIS
/hw1/kovshov_hw1_slide3.py
1,467
4.34375
4
"""Нарисовать рамочку шириной w символов и высотой h символов.""" print("Начало первого задания") def print_square_1(width, height): print("*" * width) for i in range(height - 2): s = " " * (width - 2) print("*" + s + "*") print("*" * width) print_square_1(5, 4) print("Конец первого задания") """Пускай символ, которым рисуется рамочка – тоже входной параметр.""" print("Начало второго задания") def print_square_2(width, height, custom_char): print(custom_char * width) for _ in range(height - 2): tmp_str = " " * (width - 2) print(custom_char + tmp_str + custom_char) print(custom_char * width) print_square_2(5, 4, "%") print("Конец второго задания") """Нарисовать рамочку шириной w символов и высотой h символов, и толщиной f символов.""" print("Начало третьего задания") def print_square_3(width, height, frame): for _ in range(frame): print("*" * width) for _ in range(height - 2): tmp_str = " " * (width - frame * 2) print("*" * frame + tmp_str + "*" * frame) for _ in range(frame): print("*" * width) print_square_3(6, 7, 2) print("Конец третьего задания")
false
ad1efeabab426834753d98f71f76ec0424a85ee3
RyanAldy/Python-Work
/overloadingOperators.py
876
4.3125
4
class One: # Constructor def __init__(self): self.a = 0 self.b = 0 def assign(self, x, y): self.a = x self.b = y # Overloading add method def __add__(self, R): x = One() x.a = self.a + R.b x.b = self.b + R.b return x def __sub__(self, R): x = One() x.a = self.a - R.a x.b = self.b - R.b return x def __mul__(self, R): x = One() x.a = self.a * R.a x.b = self.b * R.b return x def __div__(self, R): x = One() x.a = self.a / R.a x.b = self.b / R.b a = One() a.assign(2,4) b = One() b.assign(10,20) # Adding two objects of the one class here as overloaded the addition operator c = b + a print(c.a) print(c.b) d = One() d.assign(20,10) e = One() e.assign(15,2) f = d - e print(f.a) print(f.b)
false
6f8bb8bf6a9effbf8f271f8e9621ac88c0c094f0
KenNaNa/Python_learning
/sort.py
1,910
4.21875
4
''' 排序也是在程序中经常用到的算法。 无论使用冒泡排序还是快速排序, 排序的核心是比较两个元素的大小。 如果是数字,我们可以直接比较, 但如果是字符串或者两个dict呢? 直接比较数学上的大小是没有意义的, 因此,比较的过程必须通过函数抽象出来 ''' #Python内置的sorted()函数就可以对list进行排序 sor = sorted([12,3,4,5,613,345,234,566]) print(sor) ''' sorted()函数也是一个高阶函数, 它还可以接收一个key函数来实现自定义的排序, 例如按绝对值大小排序 ''' print(sorted([36, 5, -12, 9, -21], key=abs)) ''' key指定的函数将作用于list的每一个元素上, 并根据key函数返回的结果进行排序。 对比原始的list和经过key=abs处理过的list ''' ''' key指定的函数将作用于list的每一个元素上, 并根据key函数返回的结果进行排序。 对比原始的list和经过key=abs处理过的list: list = [36, 5, -12, 9, -21] keys = [36, 5, 12, 9, 21] 然后sorted()函数按照keys进行排序, 并按照对应关系返回list相应的元素: keys排序结果 => [5, 9, 12, 21, 36] | | | | | 最终结果 => [5, 9, -12, -21, 36] ''' strr = sorted(['bob', 'about', 'Zoo', 'Credit']) print(strr) #即可实现忽略大小写的排序 strr = sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower) print(strr) #要进行反向排序, #不必改动key函数, #可以传入第三个参数reverse=True strr = sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True) print(strr) def by_name(t): return t[0].lower() def by_score(t): return t[-1] L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88),('at',20)] L1 = sorted(L, key=by_name) L2 = sorted(L, key=by_score) print(L1) print(L2)
false
13c95a24f12e0f03179793deeb702db568c8d923
KenNaNa/Python_learning
/string111.py
1,006
4.21875
4
freg = '欢迎来到python这个快乐的编程世界' print (freg) ''' 如果遇到了需要转义的字符的话 一定要加上反斜杠(\) 此处是注释内容 在Python一般用的是 # \'\'\' 三个逗号 ''' exm = 'why are\'t learn the python' print(exm) ''' 在字符串中嵌入值 我们可用%s %s 为 num 的占位符 ''' num = 1000 str = 'I got %s points' print(str % num) ''' 一个字符串中可以使用多个 占位符%s 占位符的个数要与 对应的内容的个数相等 ''' str2 = 'what did the number %s say to the number %s %s Nice belt' print(str2 % (0,8,10)) #str3 = 'what did the number %s say to the number %s Nice belt' #print(str3 %(0,8,10))#会报错 #str3 = 'what did the number %s say to the number %s Nice belt' #print(str3 %(0))#会报错 ''' 字符串也有除法 乘法 ''' str4 = 10 * 'a' print(str4)#aaaaaaaaaa str5 = 'aaaaaaaaaa' print(str5 * 1/5)#报错
false
ff6e2afd1a8cd9e24ae6e209cefee8cbdb0c4494
iggy18/data-structures-and-algorithms
/python/python/reverse_string_3_ways_new/reverse_string.py
255
4.1875
4
def reverse_one(string): return string[::-1] def reverse_two(string): results = "" for char in string: results = char + results return results def reverse_three(string): return ''.join(reversed(string))
true
039437b41b48880d95b850c2b7ae11d6552fc6a5
mubaraqqq/electric-utilities-data-analytics
/Data.py
1,986
4.28125
4
import numpy as np # #One dimensional array # a = np.array([1, 2, 3]) # print(type(a)) # print(a.dtype) # #rank or axis # print(a.ndim) # #size attribute for array length # print(a.size) # ##shape attribute for shape # print(a.shape) # #Two dimensional array # b = np.array([[1.3, 2.4], [0.3, 4.1]]) # print(b.dtype) # print(b.ndim) # print(b.size) # print(b.shape) # #itemsize defines the size in bytes of each item in the array # print(b.itemsize) # #data is the buffer containing the actual elements of the array # print(b.data) # #Creating an array # c = np.array([[1, 2, 3], [4, 5, 6]]) # print(c) # d = np.array(((1, 2, 3), (4, 5, 6))) # print(d) # e = np.array([(1, 2, 3), [4, 5, 6], (7, 8, 9)]) # print(e) # print(e.ndim) # print(e.size) # print(e.shape) # #Types of Data # g = np.array([['a', 'b'], ['c', 'd']]) # print(g) # print(g.dtype.name) # #Intrinsic Creation of an array # #the zeros() function creates an array full of zeroes with dimensions defined by the shape argument # print (np.zeros((3, 3))) # #the ones() function creates an array full of ones in a very similar way # print (np.ones((3,3))) # #arange() function is used for generating a range of numbers specified as arguments # print(np.arange(10)) # print(np.arange(2, 8)) # print(np.arange(0, 6, 0.6)) # #use the reshape() function to create two dimensional arrays # print(np.arange(0, 12).reshape(3, 4)) # #the linspace() function acts like arange but specifies the number of elements the range should be divided into, instead of the number of steps between one element and the next # print(np.linspace(0, 10, 5)) # #the random function returns random numbers # print(np.random.random(3)) # print(np.random.random((3, 3))) #Basic Operations #Arithmetic Operators a = np.arange(4) print(a + 4) print(a*2) b = np.arange(4, 8) print (a + b) print (a - b) print (a * b) print (a * np.sin(b)) print (a * np.sqrt(b)) A = np.arange(9).reshape(3, 3) B = np.ones((3, 3)) print (A * B) #The Matrix Product
true
d8eb183e70b3bb0d0e5cf5a3a333802f88058a8c
NikolaRadan/Year9DesignCS-PythonNR
/LoopDemo.py
1,806
4.40625
4
#A Loop Demo is a structure that allows us to run #a section of code a number of times. It is great for #when we need to repeat a process. It is also great when #we need to run trhough apattern #To brand catagries of a loop #Conditional Loop: This loops if something is true #Counted loop: This loops a set number of times print("0") print("1") print("2") print("3") print("4") print("5") print("6") print("****************") #the general structure if a counted loopis # Count: this is the variable we use to track #the number of times a loop runs #Check: This is the boolean (true or false) satement we evaluate # to decide is to keep going # Change: This is the change in the count that happens after #each loop.each #we use i in range loop for i in range(0, 6 ,1): print(i) #how would the above loop run #would we recah line 27 #i = 0, 0 < 6, True RUN LOOP #i = 1, 1 < 6, True RUN LOOP #i = 2, 2 < 6, True RUN LOOP #i = 3, 3 < 6, True RUN LOOP #i = 4, 4 < 6, True RUN LOOP #i = 5, 5 < 6, True RUN LOOP #i = 6, 6 < 6, False EXIT LOOP AND MOVE ON print("*******************") print("wite a loop that will print out 7 to 104 inclusive") for i in range(7, 105, 1): print(i) print("*******") print("write a loop that will print out even numbers from -22 to 134 inclusive") for i in range(-22, 135, 2): print(i) print("*********************") print("We can count backwards as well. Python3 will assume the check is based on") print("relative value of the count and check") for i in range(3, 0, -1): print(i) print("**********") print("all numbers from 101 to 0 inclusive") for i in range(101, -1, -1): #anything that is tabbed is the loop code block print(i) s = "Fish food" for i in range(0, 9, 1): print(i) #Can you print s ount in reverse? for i in range(len(s) -1,-1,-1): print(s[i])
true
3e8b997a38fbdb888a89f976848cbbf5e5379b0b
sivaneshl/python_data_analysis
/intro_data_science_python/python_fundamentals/python_types_sequences/dict1.py
852
4.59375
5
# Dictionaries are similar to lists and tuples in that they hold a collection of items, but they're labeled collections # which do not have an ordering. This means that for each value you insert into the dictionary, you must also give a key # to get that value out. In other languages the structure is often called a map. In Python we use curly braces to denote a dictionary. x = {'Cristiano Ronaldo' : 'cronaldo@realmadrid.com', 'Wayne Rooney' : 'wrooney@manchesterunited.com'} print(x['Wayne Rooney']) # add another item to the dict x['Danielle Rossi'] = 'drossi@roma.com' print(x) x['Anthony Martial'] = None print(x['Anthony Martial']) print(x) # iterate over the dict for name in x: print(x[name]) # iterate over the values using the values() function for name in x.values(): print(name) # iterate over the key and the values at once using the items() function for name, email in x.items(): print(name) print(email)
true
5808641b6a57557736ec47c0ffb551cc857596a6
swati90-git/46_Simple_Python_Exercises_solution
/problem_8.py
817
4.40625
4
"""Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.""" #1st method def is_palindrome(string): s = "" for i in range(len(string)): s += string[-i-1] if s == string: return True else: return False print(is_palindrome("radar")) print(is_palindrome("abcba")) print(is_palindrome("Was it a car or a cat I saw")) # 2nd method def is_palindrome(string): ab = '' length = len(string) for i in range(length): ab += string[length-1] length -= 1 if string == ab: return True else: return False print(is_palindrome("radar")) print(is_palindrome("Was it a car or a cat I saw"))
false
434e73d494e74f26fe5c2b78f684c3ecb985e775
codexdelta/DSA
/leetcode/1252_Cells_with_Odd_Values_in_a_Matrix.py
1,427
4.40625
4
""" 1252. Cells with Odd Values in a Matrix Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1. Return the number of cells with odd values in the matrix after applying the increment to all indices. Example 1: Input: n = 2, m = 3, indices = [[0,1],[1,1]] Output: 6 Explanation: Initial matrix = [[0,0,0],[0,0,0]]. After applying first increment it becomes [[1,2,1],[0,1,0]]. The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers. Example 2: Input: n = 2, m = 2, indices = [[1,1],[0,0]] Output: 0 Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix. Constraints: 1 <= n <= 50 1 <= m <= 50 1 <= indices.length <= 100 0 <= indices[i][0] < n 0 <= indices[i][1] < m """ def oddCells(n, m, indices): ans = 0 viva = [[0 for i in range(m)] for j in range(n)] for x in range(len(indices)): row = indices[x][0] col = indices[x][1] for i in range(n): viva[i][col] += 1 for i in range(m): viva[row][i] += 1 for x in range(n): for y in range(m): if viva[x][y]%2 != 0: ans += 1 return ans n = 2 m = 3 indices = [[0,1],[1,1]] print(oddCells(n, m, indices))
true
c9cfd424d66ccbb075b184c3bea68f3a4a1c1df5
codexdelta/DSA
/leetcode/1389_create-target-array-in-the-given-order.py
2,173
4.28125
4
""""Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] Example 3: Input: nums = [1], index = [0] Output: [1] Constraints: 1 <= nums.length, index.length <= 100 nums.length == index.length 0 <= nums[i] <= 100 0 <= index[i] <= i " Returns: [type] -- [description] """ def createTargetArray(nums, index): viva = dict() for x in range(len(index)): if index[x] in viva: temp = viva[index[x]] viva[index[x]] = nums[x] z = list(viva.keys()) z.sort() z.reverse() for k in z: if k > index[x]: viva[k+1] = viva[k] viva[index[x] + 1] = temp else: viva[index[x]] = nums[x] return list(viva.values()) # others def other_1(nums, index): arr = [] for i in range(len(nums)): if index[i] == i: arr.append(nums[i]) else: arr = arr[:index[i]] + [nums[i]] + arr[index[i]:] return arr # others def other_2(nums, index): data = [] for i in range(0, len(nums)): data.insert(index[i], nums[i]) return data nums = [0,1,2,3,4] index = [0,1,2,2,1] target = [0,4,1,3,2] print(other_2(nums, index))
true
11acfa4dc567720d513cf7ef076192f69b214539
sabrinarwong/ccsf-cs131b
/coinToss.py
2,525
4.53125
5
# -*- coding: utf-8 -*- # @Author: Sabrina # @Date: 2019-08-28 08:47:38 # @Last Modified by: sabrina # @Last Modified time: 2019-09-04 13:49:36 import random # module for randomization functions numberOfTosses = int(input("Enter the number of tosses to perform: ")) print() # take user input and convert to an int # print new line counter = 0 while counter < numberOfTosses: # start loop if counter is less than user input # if counter == numberOfTosses: # break # # base case, if counter is same as number of tosses, exit loop flip = random.randint(0,1) # init random variable if flip == 0: print("Heads") # if random function picks 0, print heads elif flip == 1: print("Tails") # if random function picks 1, print tails counter += 1 # increment loop by 1 # END OF PROGRM ''' CS 131B LAB 2 Coin Toss Purpose. Write a computer game program, from scratch, using if-logic and count-controlled loops. Pretend that you have been hired by the National Football League (NFL) to write a program to replace the coin toss. The output should be simple: either the word "Heads" or the word "Tails". Allow the user to specify (via keyboard data entry) the number of coin tosses to perform when you run the program, and have the program display the result of each coin toss (that is, "Heads" or "Tails"). Read about "randomizing" here before you begin writing your program: Gaming.supplemental.pdf Preview the document Here's the algorithm you should use: ============================ Have the user to enter how many coin tosses to perform Input and store the user's value for how many coin tosses to perform Create a counter variable and set it to zero Start the loop here
 If the counter variable equals the number of tosses to perform
 Break from the loop
 Get and store a randomly-generated number in the range 0 to 1
 If the randomly-generated number equals 0
 Output "heads"
 If the randomly-generated number equals 1
 Output "tails"
 Add one to the counter variable Loop back from here ============================ Example running of the program with user input in bold: (you do not need to have your program print out in bold, bold is just used to make the user input easier to see in this lab description) Enter the number of tosses to perform: 3 Heads Tails Heads '''
true
e15cfbea1f67f1cdba371f0aa1021de3d90196d2
2019jrhee/OOP
/binary_search.py
697
4.25
4
# binary search for a number def binary_search (arr, n): #find the middle of the array mid = arr[len(arr)//2] print (mid) #1 what if the search number isn't in the array? #2 what if the number is found? #3 conditional for loawer half & upper half based on our find input #if the number is the middle number, then return true if n == mid: return True # if the number is greater than the middle number, then return one higher if n > mid: return binary_search(arr[len(arr)//2+1:], n) #if the number is less than the middle number, then return one smaller if n < mid: return binary_search(arr[:len(arr)//2], n) arr = [1,2,3,4,5,6,7,8,9] binary_search (arr,6)
true
b220b28f1197c0d43c075006e16bfd39f2fea42b
tiajanee/core-data-structures
/source/set.py
2,108
4.21875
4
class Set(object): def __init__(self, elements=None): #a set is an unordered list, so we initialize a list self.set_list = list() #an empty list has a size of 0 self.size = 0 if elements is not None: for element in elements: #parses through inputted elements and adds them to set self.set_list.append(element) #every time we add an element, we increment the size self.size += 1 def contains(self, element): #will return false if elements not in list return element in self.set_list def add(self, element): #check for duplicated before appending if self.contains(element) is False: self.set_list.append(element) #increment the size after adding self.size += 1 def remove(self, element): #checks if element in list before attempting to delete if set_list.contains(element): #delete if found self.delete(element) #decremenet size by 1 size -= 1 else: raise KeyError("this element is not in this set.") def union(self, other_set): union_set = Set(self.list) #traversing through other set for element in other_set.list: #check for duplicates if not self.contains(element): #if not already set add element union_set.add(element) return union_set def intersection(self, other_set): intersection_set = Set(self.list) #traversing through other set for element in other_set.list: #if the element is already in the list if self.contains(element): #add it to new set intersection_set.add(element) return intersection_set def difference(self, other_set): difference_set = Set(self.list) #traverse through other set for element in other_set.list: #check if element already in self.list if self.contains(element): self.remove(element) #if not in the list add the element else: self.add(element) return difference_set def is_subset(other_set): #if every element in other set in self.list #return True if self.contains(other_set.list): return True return False
true
392c4ecaf249caf3db4c8b7b07dfbdc005edee7c
Ayu-99/python2
/session3(b).py
209
4.15625
4
#dictionary d={"a":1 , "b":2 , "c":3 } # 1.concatenation #print(d + {"d":4 , "e":5}) #2.Repition #print(d*2) #3.Membership testing print("a" in d) #4.slicing #print(d[1:2]) # 5.indexing print(d["a"])
false
fdc3521da31f8f5b05d1eea462749ad76f9e0116
Ayu-99/python2
/session9(c).py
693
4.25
4
#Class and Object Relationship """" class CA: num = 10 def __init__(self): self.a =102 def show(self): print("num is:",self.num) print("a is:",ca.a) ca = CA() ca.show() #Rule: Property of class can be accessed by classname,object or reference variable of object i.i self #But property of object cannot be accessed by class name """ class CA: num = 101 def __init__(self): self.num =102 def show(self): print("num of object is:",self.num) print("num of class is:",CA.num) ca = CA() ca.show() #if object has the variable then it does not take from parent class # if it does not have then only it takes from parent
true
86e709c9565c1634e56d1fb518ebe8649167ca79
Ayu-99/python2
/session8.py
763
4.25
4
class Product: restaurantName = "ABC" #Constructor def __init__(self,name, price): self.name = name self.price = price #Function def showPrice(self): print(self.name, self.price, Product.restaurantName) #Destructor this will be executed when object will be deleted from memory def __del__(self): print("Product Deleted",self) #if we want to display a msg at the time of deletion of object then we use destructor #otherwise if we do not write destructor , the also object will be deleted p1 = Product("paneer",150) p2 = Product("dal",200) p1.showPrice() p2.showPrice() print(p1.__dict__) print(p2.__dict__) print(Product.__dict__) print(hex(id(p1))) print(hex(id(p2))) #del p1
true
1c866ac447232216df45c1f5eac79276cf1a0e9d
Yeshwanthyk/algorithms
/leetcode/079_leet_minimum_substring.py
2,040
4.15625
4
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Similar template: - Longest Substring with At Most Two Distinct Characters - Longest Substring Without Repeating Characters """ from collections import Counter # Psuedo Code # * Two pointer system - start, end # * Move end to find all the characters of T in S # * Retract start to find min_win # * Keep moving `end` till S is over and keep updating min_win def min_window(S, T): if not S: return "" start = 0 # Make a hashmap of the string we need to find T_map = Counter(T) # Keep track of the number of chars of T we found in S T_len = len(T) min_win = "" for end, char in enumerate(S): # If we find a char from T in S, we reduce `T_len`. If `T_len` becomes 0 we know that we found all the # chars in T if T_map[char] > 0: T_len -= 1 # We keep adding all the chars of S we move through to the hashmap # Later when we start retracting `start`, this would help us to ensure we retract correctly T_map[char] -= 1 while (T_len == 0): # Find length of the current substring that contains all chars of `T`. Later on as we keep retracting # if we find a smaller substring we can update `min_win` with that min_len = end - start + 1 # if min_win is empty or if the len of new window is lesser than the older substring, we update it if not min_win or min_len < len(min_win): min_win = S[start:end+1] # we update the first char, and we check if is a part of `T`. If it is, we move `end` until we # find another substring T_map[S[start]] += 1 if (T_map[S[start]] > 0): T_len += 1 start += 1 return min_win S = "ADOBECODEBANC" T = "ABC" ans = min_window(S, T) print(ans)
true
b93039ca2dd5f7c35bdafd38c95aac0522d79976
Yeshwanthyk/algorithms
/leetcode/695_max_area_of_island.py
1,656
4.125
4
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) Example 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally. Example 2: [[0,0,0,0,0,0,0,0]] Given the above grid, return 0. Note: The length of each dimension in the given grid does not exceed 50. """ def max_area_island(grid): max_area = 0 rows = len(grid) cols = len(grid[0]) for row in range(rows): for col in range(cols): if grid[row][col] == 1: area = [0] traverse(grid, area, row, col) max_area = max(max_area, area[0]) return max_area def traverse(grid, area, row, col): if not (0 <= row < len(grid) and 0 <= col < len(grid)) or grid[row][col] != 1: return area[0] += 1 grid[row][col] = '#' dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] for dir in dirs: traverse(grid, area, row + dir[0], col + dir[1]) grid = [[0, 0, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0]] ans = max_area_island(grid) print(ans)
true
714467aad747e449117daf3dd6aa48910572ae9b
Yeshwanthyk/algorithms
/leetcode/692_top_k_frequent_words.py
1,337
4.125
4
""" Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. Example 1: Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. Example 2: Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output: ["the", "is", "sunny", "day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Input words contain only lowercase letters. """ from collections import Counter import heapq def top_k(arr, count): ans = [] dic = Counter(arr) # min_heap = [(-dic[i], i) for i in dic] min_heap = [] for k, v in dic.items(): min_heap.append((-v, k)) heapq.heapify(min_heap) for i in range(count): ans.append(heapq.heappop(min_heap)[1]) return ans arr = ["i", "love", "leetcode", "i", "love", "coding"] ans = top_k(arr, 2) print(ans)
true
9a8f16f796d97149731f26226ef08ec34c78223e
Yeshwanthyk/algorithms
/leetcode/236_lowest_common_ancestor_binary_tree.py
1,720
4.125
4
""" Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. """ def lca_bt_iter(root, p, q): parent = {root: None} stack = [root] # We use a dict to keep track of all root nodes and their parents while stack: root = stack.pop() if root.right: parent[root.right] = root root = root.right if root.left: parent[root.left] = root root = root.left ancestors = set() # Starting from `p` we find the path of `p` -> `root` while p: ancestors.add(p) p = parent[p] # we walk through `q` till where it coincides with the path # and that value is q while q not in p: q = parent[q] return q def LCA_rec(root, p, q): if not root: return if p == root.val or q == root.val: return root left = LCA_rec(root, p, q) right = LCA_rec(root, p, q) if left and not right: return left if right and not left: return right if left and right: return root
true
5778f6ac6940245959b4ac23f353810bcc9486ee
ErickDaviContino/Exercicios-URI
/ex1.py
983
4.125
4
# Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, # o valor unitário de cada peça 1, o código de uma peça 2, o número de peças # 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago. # Entrada # O arquivo de entrada contém duas linhas de dados. Em cada linha haverá 3 # valores, respectivamente dois inteiros e um valor com 2 casas decimais. # Saída # A saída deverá ser uma mensagem conforme o exemplo fornecido abaixo, # lembrando de deixar um espaço após os dois pontos e um espaço após o # "R$". O valor deverá ser apresentado com 2 casas após o ponto. linha1 = input().split() linha2 = input().split() linha1[0] linha1[1] linha1[2] linha2[0] linha2[1] linha2[2] cod1 = int(linha1[0]) quant1 = int(linha1[1]) var1 = float(linha1[2]) cod2 = int(linha2[0]) quant2 = int(linha2[1]) var2 = float(linha2[2]) result = (quant1 * var1) + (quant2 * var2) print("VALOR A PAGAR: R$ {:.2f}".format(result))
false
c27def319a836dd025fe43cb688c7cdc0cb962cd
diego-alvirde/python
/ciclos_condicionales/ejercicios.py
2,488
4.25
4
""" Dado un diccionario, el cual almacena las calificaciones de un alumno, siendo las llaves los nombres de las materia y los valores las calificación, mostrar en pantalla el promedio del alumno. """ calificaciones = {"Español":6,"Matematicas":9,"Etica":7,"Ingles":9,"Historia":10} print(calificaciones) sumatoria = 0 lista = list(calificaciones.values()) for valor in lista: sumatoria = sumatoria + int(valor) promedio = sumatoria / len(lista) print("El promedio del alumno es:",promedio) """ A partir del diccionario del ejercicio anterior, mostrar en pantalla la materia con mejor promedio. """ lista_keys = list(calificaciones.items()) mayor = 0 materia_mayor = "" for key, valor in lista_keys: if mayor < int(valor): mayor = int(valor) materia_mayor = key print("La materia con mejor promedio es:",materia_mayor) """ Crear una lista la cual almacene 10 números positivos ingresados por el usuario, mostrar en pantalla: la suma de todos los números, el promedio, el número mayor y el número menor. """ lista = [] contador = 0 sumatoria = 0 while contador < 10: contador+=1 valor = input("Ingrese un numero:\n") lista.append(int(valor)) sumatoria = sumatoria + int(valor) promedio = sumatoria / len(lista) print(lista) print("La sumatoria es:",sumatoria) print("El promedio es", promedio) print("El numero mayor es",max(lista)) print("El numero menor es",min(lista)) """ Dado una lista de frases ingresadas por el usuario, mostrar en pantalla todas aquellas que sean palíndromo. """ lista_frases = ["hola","anita lava la tina","adios","como estas","oro"] for valor in lista_frases: correcta = valor.replace(" ","") revez = valor[::-1].replace(" ","") if correcta == revez: print("La palabra",valor,"es un palíndromo") """ Mostrar en pantalla la cantidad de vocales que existe en una frase dada por el usuario. Mostrar en pantalla la frecuencia de aparición de vocales en una frase dada por el usuario. """ buscar_vocales = "Hola como" lista_vocales = ["a","e","i","o","u"] contador = 0 ac,ec,ic,oc,uc = 0,0,0,0,0 for vocal in buscar_vocales: if vocal in lista_vocales: contador+=1 if vocal == "a": ac+=1 if vocal == "e": ec+=1 if vocal == "i": ic+=1 if vocal == "o": oc+=1 if vocal == "u": uc+=1 print("La cantidad de vocales en la frase son",contador) print("a",ac,"e",ec,"i",ic,"o",oc,"u",uc) """ Listar todos los números pares del 0 al 100 """ for valor in range(0,101,2): print(valor)
false
a12394bef353dac09c0fb526b0aa75a3f8c291d8
mce9/python_codes
/transpositionEncrypt.py
905
4.3125
4
import pyperclip def main(): myMessage = 'Common sense is not so common' myKey = 8 ciphertext = encryptMessage(myKey, myMessage) # print the encrypted string in ciphertext to the screen, with a pipe character to represent space print(ciphertext + '|') # Copy the encrypted string in cipher text to the clipboard pyperclip.copy(ciphertext) def encryptMessage(key, message): # Each string in the ciphertext represent a column in the grid ciphertext = [''] * key # Loop through each column in the ciphertext for column in range(key): currentIndex = column # Keep looping until currentIndex goes past the message length while currentIndex < len(message): ciphertext[column] += message[currentIndex] # move currentIndex over currentIndex += key # convert the ciphertext list into a single string and return it return ''.join(ciphertext) if __name__ == '__main__': main()
true
202d7d6c7894c6dcc4bdd2aa986624bd5381d886
vptuan/COMP1819ADS
/Lab_10/quick_inplace_demo2.py
1,697
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 26 14:45:03 2021 @author: tv6249tw """ def inplace_quick_sort(S, a, b, level): """Sort the list from S[a] to S[b] inclusive using the quick-sort algorithm.""" if a >= b: return # range is trivially sorted print(" "*level,"Level: ", level) print(" "*level,"Sorting: ", a, b, S[a:b+1]) pivot = S[b] # last element of range is pivot print(" "*level,"Pivot =", pivot) left = a # will scan rightward right = b-1 # will scan leftward while left <= right: # scan until reaching value equal or larger than pivot (or right marker) while left <= right and S[left] < pivot: left += 1 # scan until reaching value equal or smaller than pivot (or left marker) while left <= right and pivot < S[right]: right -= 1 if left <= right: # scans did not strictly cross S[left], S[right] = S[right], S[left] # swap values print(" "*level,"Swapped ", S[right], S[left], S) left, right = left + 1, right - 1 # shrink range # put pivot into its final place (currently marked by left index) print(" "*level,"Final left index", left) S[left], S[b] = S[b], S[left] print(" "*level,"Final swap ", S[a:b+1]) # make recursive calls inplace_quick_sort(S, a, left - 1, level+1) inplace_quick_sort(S, left + 1, b, level+1) S = [85, 24, 63, 45, 17, 31, 96, 50] inplace_quick_sort(S, 0, len(S)-1, 0) print(S)
true
fbaef3c694c8870ed1fcca283a5a52233fade04d
TUTPy/TUTSLPtest
/214448653(assignment1).py
1,664
4.25
4
################################ #### EXERCISE 1 30 MARKS ##### ################################ # Time to review all the basic data types we learned! This should be a # relatively straight-forward and quick assignment. ################ ## Problem 1 - 10 Points ## ################ # Given the string: s = 'fullstackslp' # Use indexing to print out the following: # 'f' print(s[0]) # 'p' print(s[-1]) # 'stack' print(s[4:9]) # 'slp' print(s[9:]) # 'cks' print(s[7:10]) # Bonus: Use indexing to reverse the string print(s[::-1]) ################ ## Problem 2 - LISTS - 5 Marks ## ################ # Given this nested list: l = [3,7,[5,[1,4,'hello']]] # Reassign "hello" to be "goodbye" l[2][1][2] = "goodbye" print(l) ################ ## Problem 3 - DICTIONARIES - 6 Marks ## ################ # Using keys and indexing, grab the 'hello' from the following dictionarties: d1 = {'simple_key':'hello'} print(d1['simple_key']) d2 = {'k1':{'k2':'hello'}} print(d2['k1']['k2']) d3 = {'k1':[{'nest-key':['this is deep',['hello']]}]} d3New = d3['k1'][0]['nest-key'][1][0] print(d3New) ############### ## Problem 4 - SETS - 4 Marks ## ############### # Use a set to find the unique values of the list below: mylist = [1,1,1,1,1,2,2,2,2,3,3,3,3] newlist = set(mylist) print(newlist) ############### ## Problem 5 - FORMATTING - 5 Marks ## ############### # You are given two variables: age = 45 name = "Kyle" # Use print formatting to print the following string: s = "Hello my dog's name is {} and he looks {} years old".format(name,age) print(s)
true
09caea991f764933830ff759d07063d1c7276252
griffincalme/RenameFilesAs-Folder_File
/RenameFilesAs-Folder_File.py
1,316
4.40625
4
# Griffin Calme 2017 Python 3 # This program looks into a folder for any subfolders. It takes the name of each subfolder and inserts it into the beginning # of each file's name within that subfolder, it then pulls the files out of the subfolder and deletes the subfolder. # It was written to fix audiobooks that had each chapter as a folder but the files inside the chapter had non-descript naming. # Now I can seamlessly play my books without having to manually switch to the next folder and hit play! import os # Please insert the path to the directory of subfolders, note the example is for Windows filesystems path = r'C:\Users\YOUR USERNAME\MY DOCUMENTS OR WHATEVER\YOUR FOLDER OF SUBFOLDERS WITH FILES IN THEM' subfolders = os.listdir(path) # Generate a list of subfolders in the master folder for subfolder in subfolders: try: files = os.listdir(path + '\\' + subfolder) # generate a list of the files in the subfolder for file in files: print(subfolder + '_' + file) os.rename(path + '\\' + subfolder + '\\' + file, path + '\\' + subfolder + '_' + file) try: os.rmdir(path + '\\' + subfolder) except: print('folder ' + subfolder + ' not found') except: print(subfolder + ' not found') print('\nDone!!! ' + path)
true
1c54aa2520e81d3f53674df4cb7a8e14000c6fba
wallyngson/UFCG-sorting-algorithms
/selection.py
429
4.15625
4
def sort(array): arr = array for i in range(len(arr)): min = i # walking around the list to find the # element smaller than the current. for j in range(i + 1, len(arr)): if (arr[j] < array[i]): min = j _swap(arr, min, i) print(arr) # change the positions of two elements. def _swap(arr, i, j): arr[j], arr[i] = arr[i], arr[j]
true
fa63db34ce9ec4e212147e2b4c2e80a809679d53
keertan12345/CS421
/Assignment 11.py
1,894
4.40625
4
# Assignment 11: Exploring Sets # You will pick yourself and one other family member. # You identify 10 favorite words (sets) for each # You will then compute the union, intersection, difference, # and symmetric_difference between these sets. # You print out results. # TODO: You need to implement these four methods # union method def set_union(my_words, mom_words): x = my_words.union(mom_words) return x # intesection method def set_intersection(my_words, mom_words): y = my_words.intersection(mom_words) return y # difference method def set_difference(my_words, mom_words): z = my_words.difference(mom_words) return z # symmetric_difference method def set_symmetric_difference(x,y): w = my_words.symmetric_difference(mom_words) return w # we will setup the test cases here # TODO: fill in the sets with 10 words in each set my_words = {'Dog', 'Cat', 'Bird', 'Fish', 'Math', 'Science', 'History', 'English', 'French', 'Music'} mom_words = {'Cat', 'Dog', 'Math', 'English', 'Spanish', 'Shirt', 'Hair', 'Science', 'India', 'France'} #Now call the methods and print the results our_union = set_union(my_words, mom_words) our_intersection = set_intersection(my_words, mom_words) me_mom_difference = set_difference(my_words, mom_words) mom_me_difference = set_difference(mom_words,my_words) our_symmetric_difference = set_symmetric_difference(my_words,mom_words) # Now print the output/results print("UNION: List of words that exists in my set or my mom's set") print(our_union) print("INTERSECTION: List of words that exists both sets") print(our_intersection) print("DIFFERENCE 1: List of words that are exclusive to me") print(me_mom_difference) print("DIFFERENCE 2: List of words that are exclusive to my mom") print(mom_me_difference) print("SYMMETRIC DIFFERENCE: List of words that do not have any overlap") print(our_symmetric_difference)
true
2b3dfddfbae3e59bb0c52c107ff2e55016e25a21
savithrik199/python_1
/task8.py
2,025
4.40625
4
task on zip(),reduce(),enemurate() Zip() function The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity. Syntax : zip(*iterators) name = ["Manjeet", "Nikhil", "Shambhavi", "Astha"] roll_no = [4, 1, 3, 2] marks = [40, 50, 60, 70] # using zip() to map values mapped = zip(name, roll_no, marks) # converting values to print as list mapped = list(mapped) # printing resultant values print("The zipped result is : ", end="") print(mapped) for i,j,k in zip(name,y,z): if(i=="Nikhil"): continue print(f" Name is {i} , roll no is {j} ,marks is {k}") output: The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50), ('Shambhavi', 3, 60), ('Astha', 2, 70)] Name is Manjeet , roll no is 4 ,marks is 40 Name is Shambhavi , roll no is 3 ,marks is 60 Name is Astha , roll no is 2 ,marks is 70''' Enemurate() Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. synax= enumerate(iterable, start=0) l1 = ["eat", "sleep", "repeat"] s1 = "geek" # creating enumerate objects obj1 = enumerate(l1) obj2 = enumerate(s1) print ("Return type:", type(obj1)) print(list(enumerate(l1))) # changing start index to 2 from 0 print(list(enumerate(s1, 2))) #[(0, 'eat'), (1, 'sleep'), (2, 'repeat')] #[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')] l1 = ["eat", "sleep", "repeat"] # printing the tuples in object directly for ele in enumerate(l1): print(ele) # changing index and printing separately for count, ele in enumerate(l1, 100): print(f"{count}, {ele}") '''Output: (0, 'eat') (1, 'sleep') (2, 'repeat') 100 eat 101 sleep 102 repeat''' reduce() from functools import reduce lst=[1,2,3,4,5] print(reduce(lambda a,d:a+d ,lst)) print(reduce( lambda a,c:a*c ,lst)) output: 15 120
true
fca7e67351d6e70fd5cd7aaf137ec22bca8e5825
VictoriaBrown/LPTHW
/ex14.py
1,013
4.3125
4
# Simple program with style like Zork or Adventure. # Gets argv when excuted, and asks a series of questions to user. # This is part of the LPTHW series. # Programmer: Victoria Brown # Date: October 2016 # ex14.py # Import module argv from sys import argv # Get arguments from when program is run. script, user_name = argv # Variable for prompt prompt = '> ' # Print out info print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name # Set if likes or not likes = raw_input(prompt) # Set where user lives print "Where do you live %s?" % user_name lives = raw_input(prompt) # Set what kind of computer user has print "What kind of computer do you have?" computer = raw_input(prompt) # Print out info you found out print """ Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)
true
4adbd318adb55a272b672339743a51af9c7d635f
UmmeSalma2614/U_3_Assessment_2
/qstn5.py
289
4.375
4
# Write a Python program to count the number of characters (character frequency) in a string str1= input('Enter the string:') freq = {} for i in str1: if i in freq: freq[i] += 1 else: freq[i] = 1 print ("Count of all characters in string is :\n"), str(freq))
true
b1793546f16f69d2f11212c619e9699e21bba130
YannickEsc/OOP-Python-TWT
/oop0.py
662
4.21875
4
#INTRODUCTION #We know that there are OBJECTS of certain classes in python #x='hello' #print(type(x)) #y=3 #print(type(x)) class Dog: def __init__(self, name, age): self.name = name self.age = age #print(name) def add_one(self, x, y): return x+y+1 def bark(self): print("bark") def get_name(self): return self.name def get_age(self): return self.age def set_age(self, age): self.age = age d = Dog("Tim", 13) d.set_age(23) print(d.get_name(),d.get_age()) #d.bark() #print(d.add_one(5,3)) #print(type(d)) dog1_name = "Tim" dog1_age = 34
false
6512a15ab6b26027fcbce9ee150a9425004f3e29
kedvall/projects
/Python/Automate the Boring Stuff With Python/StrongPassDetection.py
1,933
4.4375
4
#! python3 # Program that check if a password is strong. A strong password: # - Has at least 8 characters # - Contains upper and lowercase letters # - Has at least one digit import re def StrengthCheck(password): helpRegex = re.compile(r'^help$', re.I) helpCheck = helpRegex.findall(password) if helpCheck != []: print(''' A strong password:\n - Has at least 8 characters\n - Contains upper and lowercase letters\n - Has at least one digit''') return False spaceRegex = re.compile(r'\s+') spaceCheck = spaceRegex.findall(password) if spaceCheck != []: print('Spaces are not allowed. Please remove all spaces.') return False lengthRegex = re.compile(r'\w{8,}') lengthCheck = lengthRegex.findall(password) if lengthCheck == []: print('Passwords must be at least 8 characters long.') return False upperRegex = re.compile(r'[A-Z]+') upperCheck = upperRegex.findall(password) if upperCheck == []: print('Passwords must contain at least 1 uppercase letter.') return False lowerRegex = re.compile(r'[a-z]+') lowerCheck = lowerRegex.findall(password) if lowerCheck == []: print('Passwords must contain at least 1 lowercase letter') return False digitRegex = re.compile(r'\d+') digitCheck = digitRegex.findall(password) if digitCheck == []: print('Passwords must contain at least 1 digit.') return False return True # Start of program # Prompt user for password and check against criteria print('-----------------------------------------') print('| Welcome to password strength checker! |') print('| Enter help for password criteria. |') print('-----------------------------------------') print() while True: print('Enter password to check password strength: ', end='') password = input() if StrengthCheck(password): print() print('Good job, your password meets all criteria! Check another? ', end='') ans = input() if not ans.lower().startswith('y'): break print()
true
1bddc121fb609dc48124586d0f4b203ad21a02b5
yeshajt/python-code
/functions_assignments.py
2,310
4.15625
4
#===functions: vowelcount.py=== from time import sleep print "Print your word, and I will tell you how many vowels it has:" def vowelcount(x): vowel_counter = 0 x = x.lower() for i in x: if (i == "a") or (i == "e") or (i == "i") or (i == "o") or (i == "u"): vowel_counter += 1 if (vowel_counter == 1): print "There is " + str(vowel_counter) + " vowel in this word." else: print "There are " + str(vowel_counter) + " vowels in this word." #===functions: alpha.py=== def alpha(x): x = x.lower() x = list(x) if (x == sorted(x)): print "This word is in alphabetical order :)" else: print "This word is not in alphabetical order." n = 0 while (n == 0): word = raw_input() try: vowelcount(word) print print "Now I will tell you if your word is in alphabetical order: " sleep(2) alpha(word) n = 1 except: print "Please print a word \r" sleep(2) #===functions: prime.py=== print print "Print a number, and I will tell you if it's prime:" def prime(x): divisible = 0 not_divisible = 0 for i in range(2, x-1): if (x % i == 0): divisible += 1 else: not_divisible += 1 if (divisible == 0): print "This is a prime number." else: print "This is not a prime number." n = 0 while (n == 0): number = input() try: prime(number) n = 1 except: print "Please print a number." #===functions: factsum_perfect.py=== sleep(2) def factsum(x): factors = 0 for i in range(1, x-1): if (x % i == 0): factors += i else: continue return factors perfect_numbers = [] def perfect(): for i in range(1,10000): if (i == factsum(i)): perfect_numbers.append(i) continue else: continue return perfect_numbers mersenne_numbers = [] def mersenneperfect(): primelist = [11,13,17,19,23,29] for i in primelist: perfect_number = (2**(i-1))*((2**i)-1) mersenne_numbers.append(perfect_number) return mersenne_numbers print print "These are the perfect numbers: " perfect() mersenneperfect() print perfect_numbers + mersenne_numbers
true
09e0b4af9e216c594d848fa6a6e95ba0d21995f3
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/codingbat/codingbat-master/warmup-1/pos_neg.py
410
4.25
4
''' Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. ''' def pos_neg(a, b, negative): match = False if negative: if a < 0 and b < 0: match = True else: if a < 0 < b: match = True elif b < 0 < a: match = True return match
true
db2aac766f19464f144a68664b99b1b91709b2c7
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/842 Split Array into Fibonacci Sequence.py
2,640
4.21875
4
#!/usr/bin/python3 """ Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list F of non-negative integers such that: 0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type); F.length >= 3; and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2. Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from S, or return [] if it cannot be done. Example 1: Input: "123456579" Output: [123,456,579] Example 2: Input: "11235813" Output: [1,1,2,3,5,8,13] Example 3: Input: "112358130" Output: [] Explanation: The task is impossible. Example 4: Input: "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. Example 5: Input: "1101111" Output: [110, 1, 111] Explanation: The output [11, 0, 11, 11] would also be accepted. Note: 1 <= S.length <= 200 S contains only digits. """ from typing import List MAX = 2 ** 31 - 1 class Solution: def splitIntoFibonacci(self, S: str) -> List[int]: """ The first two elements of the array uniquely determine the rest of the sequence. 2^31 - 1 is length 10 brute force """ l = len(S) for i in range(1, l + 1): num_str = S[:i] if len(num_str) > 1 and num_str.startswith("0"): continue num = int(num_str) if num > MAX: break for j in range(i + 1, l + 1): num2_str = S[i:j] if len(num2_str) > 1 and num2_str.startswith("0"): continue num2 = int(num2_str) if num2 > MAX: break ret = [num, num2] k = j while k < l: nxt = ret[-1] + ret[-2] if nxt > MAX: break nxt_str = str(nxt) if S[k:k+len(nxt_str)] == nxt_str: k = k + len(nxt_str) ret.append(nxt) else: break else: if k == l and len(ret) >= 3: return ret return [] if __name__ == "__main__": assert Solution().splitIntoFibonacci("123456579") == [123,456,579] assert Solution().splitIntoFibonacci("01123581321345589") == [0,1,1,2,3,5,8,13,21,34,55,89]
true
1af87380ccaf98c0c61d6f9e41a7cc3812741b74
syurskyi/Algorithms_and_Data_Structure
/Python for Data Structures Algorithms/src/12 Array Sequences/Array Sequences Interview Questions/PRACTICE/Sentence Reversal.py
1,416
4.1875
4
# %% ''' # Sentence Reversal ## Problem Given a string of words, reverse all the words. For example: Given: 'This is the best' Return: 'best the is This' As part of this exercise you should remove all leading and trailing whitespace. So that inputs such as: ' space here' and 'space here ' both become: 'here space' ## Solution Fill out your solution below: ''' # %% def rev_word(s): return " ".join(reversed(s.split())) pass # %% rev_word('Hi John, are you ready to go?') # %% rev_word(' space before') # %% rev_word('space after ') # %% ''' ## Learn - " ".join() - reversed() - s.split() ''' # %% # reversed() ''' Init signature: reversed(self, /, *args, **kwargs) Docstring: reversed(sequence) -> reverse iterator over values of the sequence Return a reverse iterator Type: type ''' # %% ''' _____ ''' # %% ''' # Test Your Solution ''' # %% """ RUN THIS CELL TO TEST YOUR SOLUTION """ from nose.tools import assert_equal class ReversalTest(object): def test(self,sol): assert_equal(sol(' space before'),'before space') assert_equal(sol('space after '),'after space') assert_equal(sol(' Hello John how are you '),'you are how John Hello') assert_equal(sol('1'),'1') print ("ALL TEST CASES PASSED") # Run and test t = ReversalTest() t.test(rev_word) # %% ''' ## Good Job! '''
true
920634d820604de7f30b8a9e6f92f0494c635412
syurskyi/Algorithms_and_Data_Structure
/The Complete Data Structures and Algorithms Course in Python/src/Section 29 Searching Algorithms/BinarySearch.py
767
4.21875
4
# Created by Elshad Karimov # Copyright © AppMillers. All rights reserved. # Searching algorithms - Binary Search import math def binarySearch(array, value): start = 0 end = len(array)-1 middle = math.floor((start+end)/2) while not(array[middle]==value) and start<=end: if value < array[middle]: end = middle - 1 else: start = middle + 1 middle = math.floor((start+end)/2) # print(start, middle, end) if array[middle] == value: return middle else: return -1 custArray = [8, 9, 12, 15, 17, 19, 20, 21, 28] print(binarySearch(custArray, 15)) # [8, 9, 12, 15, 17, 19, 20, 21, 28] # S M E # S M E # SM E # SME
true
0b50dbabfb66cd0463a939f91aed6922c4ffd491
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/Palindrome.py
509
4.125
4
#The word or whole phrase which has the same sequence of letters in both directions is called a palindrome. for i in range(int(input())): rev_str = '' string = ''.join(e for e in input().lower() if e.islower()) #here iam storing the string in the reverse form for j in range(len(string)-1,-1,-1): rev_str += string[j] #once the reverse string is stored then i'm comparing it with the original string if rev_str == string: print('Y',' ') else: print('N',' ')
true
91b02736659b42b533234abaaa6f862f1cb529a8
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/739 Daily Temperatures.py
1,434
4.15625
4
#!/usr/bin/python3 """ Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. """ from typing import List from collections import deque class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: """ maintain a stack of monotonously decresing from right to left (i.e. monotonously increasing from left to right) Why stack? because you can disregard certain non-usefull information scanning from right [73, 74, 75, 71, 69, 72, 76, 73] """ ret = deque() stk = [] for i in range(len(T) - 1, -1 , -1): while stk and T[stk[-1]] <= T[i]: # disregard smaller ones stk.pop() if stk: ret.appendleft(stk[-1] - i) else: ret.appendleft(0) stk.append(i) return list(ret) if __name__ == "__main__": assert Solution().dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
true
6cb797f8d1f1fd62422cef150e2504efd16b6241
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/955 Delete Columns to Make Sorted II.py
2,092
4.21875
4
#!/usr/bin/python3 """ We are given an array A of N lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices. For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef","vyz"]. Suppose we chose a set of deletion indices D such that after deletions, the final array has its elements in lexicographic order (A[0] <= A[1] <= A[2] ... <= A[A.length - 1]). Return the minimum possible value of D.length. Example 1: Input: ["ca","bb","ac"] Output: 1 Explanation: After deleting the first column, A = ["a", "b", "c"]. Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]). We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1. Example 2: Input: ["xc","yb","za"] Output: 0 Explanation: A is already in lexicographic order, so we don't need to delete anything. Note that the rows of A are not necessarily in lexicographic order: ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...) Example 3: Input: ["zyx","wvu","tsr"] Output: 3 Explanation: We have to delete every column. Note: 1 <= A.length <= 100 1 <= A[i].length <= 100 """ from typing import List class Solution: def minDeletionSize(self, A: List[str]) -> int: """ Greedily delete Scannign from left to right Keep a lt array to reprent already sorted pair lt[i] is true meaning A[i] < A[i+1] handle equal case [aa, ab, aa] """ m, n = len(A), len(A[0]) lt = [False for i in range(m)] deleted = 0 for j in range(n): for i in range(m-1): if lt[i]: continue if A[i][j] > A[i+1][j]: deleted += 1 break else: # not deleted # handle equal case for i in range(m-1): lt[i] = lt[i] or A[i][j] < A[i+1][j] return deleted
true
af689ce7ab52be8f95a135083e7cc2156cea7319
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/pybites/PyBites-master/Bite 104. Split and join.py
760
4.21875
4
""" Split up the message on newline (\n) using the split builtin, then use the join builtin to stitch it together using a '|' (pipe). So Hello world:\nI am coding in Python :)\nHow awesome! would turn into: Hello world:|I am coding in Python :)|How awesome! Your code should work for other message strings as well """ message = """Hello world! We hope that you are learning a lot of Python. Have fun with our Bites of Py. Keep calm and code in Python! Become a PyBites ninja!""" def split_in_columns(message=message): """Split the message by newline (\n) and join it together on '|' (pipe), return the obtained output""" pipe = "|" message_split = message.split("\n") message_join = pipe.join(message_split) return message_join
true
1b58d7297893a61254d8b7cf407ac6121dd9e5fb
syurskyi/Algorithms_and_Data_Structure
/Python for Data Structures Algorithms/src/13 Stacks Queues and Deques/Stacks, Queues, and Deques Interview Problems/PRACTICE/Implement a Stack .py
904
4.28125
4
# %% ''' # Implement a Stack A very common interview question is to begin by just implementing a Stack! Try your best to implement your own stack! It should have the methods: * Check if its empty * Push a new item * Pop an item * Peek at the top item * Return the size ''' # %% class Stack(object): # Fill out the Stack Methods here def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, e): self.items.append(e) def pop(self): return self.items.pop() def size(self): return len(self.items) def peek(self): return self.items[self.size()-1] # reuse the size funtion pass # %% stack = Stack() # %% stack.size() # %% stack.push(1) # %% stack.push(2) # %% stack.push('Three') # %% stack.pop() # %% stack.pop() # %% stack.size() # %% stack.isEmpty() # %% stack.peek() # %%
true
bed59ef8a0631f3841318775d2ce615115787a5a
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/961 N-Repeated Element in Size 2N Array.py
1,313
4.15625
4
#!/usr/bin/python3 """ In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element repeated N times. Example 1: Input: [1,2,3,3] Output: 3 Example 2: Input: [2,1,2,5,3,2] Output: 2 Example 3: Input: [5,1,5,2,5,3,5,4] Output: 5 Note: 4 <= A.length <= 10000 0 <= A[i] < 10000 A.length is even """ from typing import List class Solution: def repeatedNTimes(self, A: List[int]) -> int: """ Counter. Straightforward. O(N) space O(1) space 2N items, N + 1 unique, 1 repeat N times N = 2 a t b t t a b t N = 3 a t b t c t window 2, cannot find the target window 3, can find the target? no [9,5,6,9] window 4, can find * There is a major element in a length 2 subarray, or; * Every length 2 subarray has exactly 1 major element, which means that a length 4 subarray that begins at a major element will have 2 major elements. """ n = len(A) for i in range(n - 1): for j in range(3): if A[i] == A[min(n - 1, i + 1 + j)]: return A[i] raise if __name__ == "__main__": assert Solution().repeatedNTimes([1,2,3,3]) == 3
true
44d164a8a29c336dc1e4f88221fb6ece0a5c5032
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/practicepython/practice_python-master/ex18.py
976
4.28125
4
#!/c/Python27/python.exe ''' Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull ... Until the user guesses the number. ''' def main(): pass def something(): pass if __name__ == "__main__": main()
true
c429f0bb7da2ae47e82bd7c455d3f4a485f8767b
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/practicepython/practice_python-master/ex2.py
1,436
4.53125
5
#!/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 ''' Ex 2: Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: (1) If the number is a multiple of 4, print out a different message. (2) Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. ''' def main(): import sys # Get user input str = input("Please enter an integer: ") num = int(float(str)) # force the input to an int # Part the first if num % 2 == 0: print ('Your number is even.') else: print ('Your number is odd.') # Part the second if num % 4 == 0: print ('Your number is a multiple of 4.') # Part the third str1 = input("\nPlease enter an integer numerator: ") str2 = input("Please enter an integer denominator: ") # force both inputs to integers numerator = int(float(str1)) denominator = int(float(str2)) if denominator == 0: print ('Cannot accept zero divisor. Exiting.') sys.exit() else: if numerator % denominator == 0: print ("{} divides evenly into {}".format(denominator, numerator)) else: print ("{} does not divide evenly into {}".format(denominator, numerator)) if __name__ == "__main__": main()
true
a52484cdb71d3cd0b7662fe6e02e8bf71b2b4f1b
syurskyi/Algorithms_and_Data_Structure
/_temp/Cracking Coding Interviews - Mastering Algorithms/template/Section 6 Backtracking/permutations.py
598
4.15625
4
______ copy # Given a collection of distinct integers, return all possible permutations. # Example: # Input: [1,2,3] # Output: # [ # [1,2,3], # [1,3,2], # [2,1,3], # [2,3,1], # [3,1,2], # [3,2,1] # ] ___ permutation_recursive(nums, path __ l..(nums) __ 0: r_ [path] output _ # list ___ i __ r..(l..(nums copy_path _ copy.deepcopy(path) copy_path.a..(nums[i]) permutations _ permutation_recursive(nums[:i] + nums[i + 1:], copy_path) output +_ permutations r_ output ___ permute(nums r_ permutation_recursive(nums, # list) print(permute([1, 2, 3, 4, 5, 6]))
false
74012a774b04d00fd63d98a5e7dcd93b914bd66a
syurskyi/Algorithms_and_Data_Structure
/Linked List Data Structure using Python/src/Section 7 Brain Teasers - Doubly Linked List/3.reverse.py
766
4.25
4
from doublyLinkedList import Node, LinkedList def reverse(linkedList): # (2->13->10->20->None | None<-2<-13<-10<-20) || (20->10->13->2->None | None<-20<-10<-13<-2) currentNode = linkedList.head while currentNode is not None: nextNode = currentNode.next # 13, 10, 20, None currentNode.next = currentNode.previous currentNode.previous = nextNode if currentNode.previous is None: linkedList.head = currentNode currentNode = nextNode nodeOne = Node(2) nodeTwo = Node(13) nodeThree = Node(10) nodeFour = Node(20) linkedList = LinkedList() linkedList.insertEnd(nodeOne) linkedList.insertEnd(nodeTwo) linkedList.insertEnd(nodeThree) linkedList.insertEnd(nodeFour) reverse(linkedList) linkedList.printList()
true
c8be77eb66c960e6f7621bfc5dd10ca1a25300eb
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/pybites/PyBites-master/Bite 108. Loop over a dict of namedtuples calculating a total score.py
1,201
4.21875
4
""" In this Bite you calculate the total amount of points earned with Ninja Belts by accessing the given ninja_belts dict. You learn how to access score and ninjas (= amount of belt owners) from no less than a namedtuple. Why a namedtuple, you did not even mention a tuple yet?! Good point, well in our Bites we might actually use them even more so let's get to know them here (if you have a free evening read up on the collections module as well and thank us later). The function returns the total score int. You learn to write generic code because we test for an updated ninja_belts dict as well, see the TESTS tab. """ from collections import namedtuple # Car = namedtuple('Car', ['color', 'mileadge']) # my_car = Car('blue', 150000) # print(my_car) BeltStats = namedtuple('BeltStats', 'score ninjas') ninja_belts = {'yellow': BeltStats(50, 11), 'orange': BeltStats(100, 7), 'green': BeltStats(175, 1), 'blue': BeltStats(250, 5)} def get_total_points(belts=ninja_belts): total_scores = [] for i in belts: total_scores.append(int(belts[i].score * belts[i].ninjas)) return sum(total_scores) get_total_points()
true
654a80826311d784e12cecb7f9756ae6fb691425
syurskyi/Algorithms_and_Data_Structure
/Algorithmic Problems in Python/factorial.py
458
4.21875
4
def factorial(n): #base case: 1!=1 (factorial 1 is 1) if n == 1: return 1 #we make a recursive call subres1 = factorial(n-1) #we do some operations subres2 = n*subres1 return subres2 def factorial_accumulator(n,accumulator=1): #base case: 1!=1 if n==1: return accumulator #now it is a tail 001_recursion !!! return factorial_accumulator(n-1,n*accumulator) if __name__ == "__main__": print(factorial_accumulator(5))
false
7197b5b983798e3d2afcb75e732ba9ec0274c623
syurskyi/Algorithms_and_Data_Structure
/_temp/Python for Data Structures Algorithms/template/15 Recursion/Memoization.py
1,704
4.5
4
# Memoization # # In this lecture we will discuss memoization and dynamic programming. For your homework assignment, read # the Wikipedia article on Memoization, before continuing on with this lecture! # Memoization effectively refers to remembering ("memoization" -> "memorandum" -> to be remembered) results of method # calls based on the method inputs and then returning the remembered result rather than computing the result again. # You can think of it as a cache for method results. We'll use this in some of the interview problems as improved # versions of a purely recursive solution. # # A simple example for computing factorials using memoization in Python would be something like this: # # # Create cache for known results factorial_memo _ # dict ___ factorial(k __ k < 2: r_ 1 __ n.. k __ factorial_memo: factorial_memo[k] _ k * factorial(k-1) r_ factorial_memo[k] factorial(4) # 24 # # Note how we are now using a dictionary to store previous results of the factorial function! We are now able # to increase the efficiency of this function by remembering old results! # Keep this in mind when working on the Coin Change Problem and the Fibonacci Sequence Problem. # We can also encapsulate the memoization process into a class: c_ Memoize: ___ - f f _ f memo _ # dict ___ __call__ *args __ n.. args __ memo: memo[args] _ f(*args) r_ memo[args] # Then all we would have to do is: ___ factorial(k __ k < 2: r_ 1 r_ k * factorial(k - 1) factorial _ Memoize(factorial) # Try comparing the run times of the memoization versions of functions versus the normal recursive solutions!
true
dac63f048419111d98a368bbb76d04b92331c351
syurskyi/Algorithms_and_Data_Structure
/Python for Data Structures Algorithms/src/14 Linked Lists/Linked Lists Interview Problems/PRACTICE/Linked List Reversal.py
2,359
4.3125
4
# Linked List Reversal # Problem # Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return # the new head of the list. # # You are given the example Linked List Node class: # class Node(object): def __init__(self,value): self.value = value self.nextnode = None # Solution # # Fill out your solution below: # def reverse(head): cur = head pre, nxt = None, None while cur:# watch out nxt = cur.nextnode cur.nextnode = pre pre = cur cur = nxt return pre #watch out pass # Test Your Solution # Note, this isn't a classic run cell for testing your solution, please read the statements below carefully # You should be able to easily test your own solution to make sure it works. Given the short list a,b,c,d with values # 1,2,3,4. Check the effect of your reverse function and make sure the results match the logic here below: # # Create a list of 4 nodes a = Node(1) b = Node(2) c = Node(3) d = Node(4) # Set up order a,b,c,d with values 1,2,3,4 a.nextnode = b b.nextnode = c c.nextnode = d # Now let's check the values of the nodes coming after a, b and c: print (a.nextnode.value) print (b.nextnode.value) print (c.nextnode.value) # 2 # 3 # 4 d.nextnode.value # # --------------------------------------------------------------------------- # AttributeError Traceback (most recent call last) # <ipython-input-46-9ee2d814a788> in <module>() # ----> 1 d.nextnode.value # # AttributeError: 'NoneType' object has no attribute 'value' # # So far so good. Note how there is no value proceeding the last node, this makes sense! Now let's reverse # the linked list, we should see the opposite order of values! # reverse(a) # <__main__.Node at 0x1067a2f28> # print (d.nextnode.value) print (c.nextnode.value) print (b.nextnode.value) # # 3 # 2 # 1 # print a.nextnode.value # This will give an error since it now points to None # # File "<ipython-input-49-42251ca948f9>", line 1 # print a.nextnode.value # This will give an error since it now points to None # ^ # SyntaxError: Missing parentheses in call to 'print' # # Great, now we can see that each of the values points to its previous value (although now that # the linked list is reversed we can see the ordering has also reversed)
true
f4c2557e445626c6f19847b553b684b12524585f
syurskyi/Algorithms_and_Data_Structure
/Linked List Data Structure using Python/src/Section 5 Singly Linked List/SLL-Hard.py
2,045
4.1875
4
# Delete nodes that have a greater value on the right side class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insertEnd(self, newNode): if self.head is None: self.head = newNode return lastNode = self.head while lastNode.next is not None: lastNode = lastNode.next lastNode.next = newNode def deleteRight(self): currentNode = self.head while currentNode.next is not None: # Check if node on the right has a greater value if currentNode.next.data > currentNode.data: # If currentNode is the head node, delete it and make the new node as the head node if currentNode is self.head: self.head = currentNode.next currentNode.next = None currentNode = self.head continue # If currentNode is not head node, make the previous node point to next node and remove this node previousNode.next = currentNode.next currentNode.next = None currentNode = self.head else: # Advance to next node if the data on the right side is not greater than currentNode previousNode = currentNode currentNode = currentNode.next def printList(self): if self.head is None: print("Empty List") return currentNode = self.head while currentNode is not None: print(currentNode.data) currentNode = currentNode.next nodeOne = Node(10) nodeTwo = Node(5) nodeThree = Node(6) nodeFour = Node(2) nodeFive = Node(3) linkedList = LinkedList() linkedList.insertEnd(nodeOne) linkedList.insertEnd(nodeTwo) linkedList.insertEnd(nodeThree) linkedList.insertEnd(nodeFour) linkedList.insertEnd(nodeFive) linkedList.deleteRight() linkedList.printList()
true