blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0dfcd53fb2f4d82b58ce43b5726c6d682b61dc95
SarwarSaif/Python-Problems
/Hackerank-Problems/NestedList.py
1,897
4.25
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 29 12:30:26 2018 @author: majaa """ if __name__ == '__main__': marksheet=[] """ for _ in range(int(input())): marksheet.append([input(),float(input())]) """ n = int(input()) marksheet = [[input(), float(input())] for _ in range(n)] second_lowest= sorted(list(set([marks for name, marks in marksheet])))[1] #list index started from 1 print('\n'.join([a for a,b in sorted(marksheet) if b == second_lowest])) #print(sorted(marksheet)) """ Testcase 0 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Testcase 2 5 Harsh 20 Beria 20 Varun 19 Kakunami 19 Vikas 21 #initialising an empty list! marksheet = [] #iterating through a for loop starting from zero, to some user input(default type string) - that is converted to int for i in range(0,int(input())): #appending user input(some string) and another user input(a float value) as a list to marksheet marksheet.append([raw_input(), float(input())]) #[marks for name, marks in marksheet] - get all marks from list #set([marks for name, marks in marksheet]) - getting unique marks #list(set([marks for name, marks in marksheet])) - converting it back to list #sorting the result in decending order with reverse=True and getting the value as first index which would be the second largest. second_highest = sorted(list(set([marks for name, marks in marksheet])),reverse=True)[1] #printing the name and mark of student that has the second largest mark by iterating through the sorted list. #If the condition matches, the result list is appended to tuple -` [a for a,b in sorted(marksheet) if b == second_highest])` #now join the list with \n - newline to print name and mark of student with second largest mark print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest])) """
true
afb1f832a96caef7312c407477962a7b7ccbd0e5
kubawyczesany/python
/case_swapping.py
253
4.375
4
# Given a string, simple swap the case for each of the letters. # e.g. HeLLo -> hEllO string = input ("Give a string to swap: ") def swap(string_): _string = ''.join([i.upper() if i.islower() else i.lower() for i in string_]) return (_string)
true
dc31d568218f5f710d20afc46f9b876c0e09c8a9
lsaggu/introduction_to_python
/programs/programs.py
1,874
4.28125
4
#! /usr/bin/python import sys ''' her is the task i like you to do to reinforce the learning experience once you are done with the tutorial. a) write a program that uses loops over both x and y coordinates while x is in 1,2,3,4,5 and y is in 5,4,3,2,1 and prints the x and y coordinate b) write a program that sums up all values in x and y c) write a program just like a) but does not print values where x is equal to 2 and y is equal to 4 d) write a function that takes in a word and returns it in reverse order e) provide a program that uses dicts f) read up on classes we will cover this in more detail next week. we will create an icecream machine that produces icecream in with tiny flavor, medium flavor and large flavor. in addition the icecream cone will be wrapped into some paper that has an image on it. Images will be Penguin, Apple, ''' xlist = [1, 2, 3, 4, 5] ylist = [5, 4, 3, 2, 1] zlist = [4, 5, 2, 1, 3] print(xlist) print(ylist) print(zlist) print "GREGORS TASK" for x in xlist: for y in ylist: print (x, y) print ('Hello world') print ("Task A") # x and y cordinates index = 1 for y in ylist: for x in xlist: print index, (x, y) index += 1 print ("Task B") sum = 0 for y in ylist: for x in xlist: sum += y + x print ("The sum is", sum) print ("Task C") for x in xlist: sum = (x, y) print('\n\n The Sum of x and y cordinates is: + str(sum)') for y in ylist: if y == 5 or y < 4: for x in xlist: if x >= 3 or x < 2: print (x, y) print ("task D") tim = {'cheese': xlist, 'burger': ylist} tim['ham'] = zlist for a in tim: print (a) print ("task F") class clown: number_of_noise = 1 jack = clown() jack.number_of_noise = 3 print "Jack has %s noise." % jack.number_of_noise class clown: number_of_noise = 1 def nose(self): print "Big" jack = clown() jack.nose()
true
e689091397f37f3b4b166d1510e3dac045b8f799
AbdulMoizChishti/python-practice
/Pfundamental Lab/Lab 7/task 2.py
269
4.25
4
def max(a, b, c): if a>b and a>c: print(a) elif b>c and b>a: print(b) else: print(c) a=int(input("first number=")) b=int(input("second number=")) c=int(input("third number=")) max(a, b, c) print("is the maximum of three integers")
true
0ec6649be950c71297dbc01a294c67b4ba388fc2
CharlieCarlon/EstructuraDeDatos20188
/Actividad2Unidad1.py
1,693
4.21875
4
"""Iciciamos variables""" n=0 """Creamos la libreria cache esta va a guardar las llamadas a la fuuncion mas renciente para que no gaste tanto en memoria volviendo a llamar a la funcion""" fibonacci_cache = {} def fibonacci(n): """Se revisa si el valor esta guardado en nuestra libreria, si no calculamos el termino de n, esto es para que no tenga que volver a hacer la recursividad y que quede guardado en la libreria para que no gaste tantos recursos la maquina""" if n in fibonacci_cache: return fibonacci_cache[n] if n==1: #Lo que hacemso es calcular el valor, guardarlo en la libreria y luego retornarlo, si el valor es 1 se retorna 1 si es dos lo mismo, sino aplicamos la recursividad restandole 1 y 2 a la suma value=1 elif n == 2: value = 1 elif n>2: value = fibonacci(n-1) + fibonacci(n-2) fibonacci_cache[n]=value#Se guarda el valor en la libreria y lo retornamos return value """Se creo un metodo para la impresion para no usar ciclos se aumenta el valor de n que sera un contador se crea una condicion para que sea menor al valor que entrega el usuario despues se emprime el metodo fibonacci y se manda el valor de n el cual aumenta cada vez que entramos en el metodo y al terminar se imprime que se ha terminado""" def impresion(i,n): n=n+1 if n<=i: print(fibonacci(n)) impresion(i,n) else: print("Fibonacci finalizado") """Se guarda el limite del fibonacci y se manda a llamar el metodo impresion con los parametros i que es el limite y n el contador""" i=int(input("Hasta que numero desea evaluar Fibonacci ")) impresion(i,n)
false
461ad5fff551ecfbb109842b78c03a33c3fe6156
akshaali/Competitive-Programming-
/Hackerrank/minimumDistances.py
1,525
4.375
4
""" We define the distance between two array values as the number of indices between the two values. Given , find the minimum distance between any pair of equal elements in the array. If no such value exists, print . For example, if , there are two matching pairs of values: . The indices of the 's are and , so their distance is . The indices of the 's are and , so their distance is . Function Description Complete the minimumDistances function in the editor below. It should return the minimum distance between any two matching elements. minimumDistances has the following parameter(s): a: an array of integers Input Format The first line contains an integer , the size of array . The second line contains space-separated integers . Constraints Output Format Print a single integer denoting the minimum in . If no such value exists, print . Sample Input 6 7 1 3 4 1 7 Sample Output 3 """ #!/bin/python3 import math import os import random import re import sys # Complete the minimumDistances function below. def minimumDistances(a): flag = 0 min = 888888888 for i in range(len(a)): for j in range(i+1,len(a)): if a[i] == a[j] and abs(i-j)< min: min = abs(i-j) flag = 1 return min if flag else "-1" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) a = list(map(int, input().rstrip().split())) result = minimumDistances(a) fptr.write(str(result) + '\n') fptr.close()
true
34240c8a1cd3c2132e6bd8121ae449b44ec92c58
akshaali/Competitive-Programming-
/Hackerrank/TimeConversion.py
1,432
4.1875
4
""" Given a time in -hour AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock. Function Description Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format. timeConversion has the following parameter(s): s: a string representing time in hour format Input Format A single string containing a time in -hour clock format (i.e.: or ), where and . Constraints All input times are valid Output Format Convert and print the given time in -hour format, where . Sample Input 0 07:05:45PM Sample Output 0 19:05:45 """ #!/bin/python3 import os import sys # # Complete the timeConversion function below. # def timeConversion(s): # # Write your code here. n = len(s) if s == "12:00:00PM": return s[:n-2] if s == "12:00:00AM": return "00:00:00" if s[:2]=="12" and s[n-2:]=="PM": return s[:n-2] if s[:2] == "12" and s[n-2:]=="AM": return (str("00")+ s[2:n-2]) if s[n-2:] == "AM": return(s[:n-2]) else: return(str(int(s[:2])+ 12)+s[2:n-2]) # if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) f.write(result + '\n') f.close()
true
689a7f8c2643819de8930cfc93ceab46697b605a
akshaali/Competitive-Programming-
/Hackerrank/pickingNumbers.py
2,479
4.5625
5
""" Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to . For example, if your array is , you can create two subarrays meeting the criterion: and . The maximum length subarray has elements. Function Description Complete the pickingNumbers function in the editor below. It should return an integer that represents the length of the longest array that can be created. pickingNumbers has the following parameter(s): a: an array of integers Input Format The first line contains a single integer , the size of the array . The second line contains space-separated integers . Constraints The answer will be . Output Format A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is . Sample Input 0 6 4 6 5 3 3 1 Sample Output 0 3 Explanation 0 We choose the following multiset of integers from the array: . Each pair in the multiset has an absolute difference (i.e., and ), so we print the number of chosen integers, , as our answer. Sample Input 1 6 1 2 2 3 1 2 Sample Output 1 5 """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code here if a == None: return 0 ai = list(set(a)) dic = {} for i in ai: dic1 = {i:a.count(i)} dic.update(dic1) l = [] f = 0 print(dic) key1 = ai[0] value1 = dic[ai[0]] dic1 = dic.copy() del dic[ai[0]] print(dic) if not bool(dic): return value1 for key, value in dic.items(): if abs(key1-key) <=1: f = 1 l.append(value1+value) key1 = key value1 = value print(dic1) key_max = max(dic1.keys(), key=(lambda k: dic1[k])) if f: return max(max(l), dic1[key_max]) else: key_max = max(dic1.keys(), key=(lambda k: dic1[k])) return key_max if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = pickingNumbers(a) fptr.write(str(result) + '\n') fptr.close()
true
c9488b2c6856e3c6b87db68ee117bb4e01380325
akshaali/Competitive-Programming-
/Hackerrank/designerPDFViewer.py
2,008
4.21875
4
""" When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In this PDF viewer, each word is highlighted independently. For example: PDF-highighting.png In this challenge, you will be given a list of letter heights in the alphabet and a string. Using the letter heights given, determine the area of the rectangle highlight in assuming all letters are wide. For example, the highlighted . Assume the heights of the letters are and . The tallest letter is high and there are letters. The hightlighted area will be so the answer is . Function Description Complete the designerPdfViewer function in the editor below. It should return an integer representing the size of the highlighted area. designerPdfViewer has the following parameter(s): h: an array of integers representing the heights of each letter word: a string Input Format The first line contains space-separated integers describing the respective heights of each consecutive lowercase English letter, ascii[a-z]. The second line contains a single word, consisting of lowercase English alphabetic letters. Constraints , where is an English lowercase letter. contains no more than letters. Output Format Print a single integer denoting the area in of highlighted rectangle when the given word is selected. Do not print units of measure. Sample Input 0 1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 abc Sample Output 0 9 """ #!/bin/python3 import math import os import random import re import sys # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): max = 0 for i in range(len(word)): if max < h[ord(word[i])-97]: max = h[ord(word[i])-97] return max*len(word) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) fptr.write(str(result) + '\n') fptr.close()
true
0e016e34e46435270dc0bba650016e7ba56a2ced
akshaali/Competitive-Programming-
/Hackerrank/gridChallenge.py
2,281
4.15625
4
""" Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not. For example, given: a b c a d e e f g The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row. Function Description Complete the gridChallenge function in the editor below. It should return a string, either YES or NO. gridChallenge has the following parameter(s): grid: an array of strings Input Format The first line contains , the number of testcases. Each of the next sets of lines are described as follows: - The first line contains , the number of rows and columns in the grid. - The next lines contains a string of length Constraints Each string consists of lowercase letters in the range ascii[a-z] Output Format For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise. Sample Input 1 5 ebacd fghij olmkn trpqs xywuv Sample Output YES Explanation The x grid in the test case can be reordered to abcde fghij klmno pqrst uvwxy This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all lexicographically sorted. """ #!/bin/python3 import math import os import random import re import sys # Complete the gridChallenge function below. def gridChallenge(grid): row = len(grid) column = len(grid[0]) for i in range(row): grid[i] = sorted(grid[i], key=ord) for i in range(column): for j in range(row-1): if ord(grid[j][i]) > ord(grid[j+1][i]): return("NO") return("YES") if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) grid = [] for _ in range(n): grid_item = input() grid.append(grid_item) result = gridChallenge(grid) fptr.write(result + '\n') fptr.close()
true
918519d14aa6d0984c66c9bd431c51d9ac82c263
akshaali/Competitive-Programming-
/Hackerrank/anagram.py
2,668
4.4375
4
""" Two words are anagrams of one another if their letters can be rearranged to form the other word. In this challenge, you will be given a string. You must split it into two contiguous substrings, then determine the minimum number of characters to change to make the two substrings into anagrams of one another. For example, given the string 'abccde', you would break it into two parts: 'abc' and 'cde'. Note that all letters have been used, the substrings are contiguous and their lengths are equal. Now you can change 'a' and 'b' in the first substring to 'd' and 'e' to have 'dec' and 'cde' which are anagrams. Two changes were necessary. Function Description Complete the anagram function in the editor below. It should return the minimum number of characters to change to make the words anagrams, or if it's not possible. anagram has the following parameter(s): s: a string Input Format The first line will contain an integer, , the number of test cases. Each test case will contain a string which will be concatenation of both the strings described above in the problem. The given string will contain only characters in the range ascii[a-z]. Constraints consists only of characters in the range ascii[a-z]. Output Format For each test case, print an integer representing the minimum number of changes required to make an anagram. Print if it is not possible. Sample Input 6 aaabbb ab abc mnop xyyx xaxbbbxx Sample Output 3 1 -1 2 0 1 Explanation Test Case #01: We split into two strings ='aaa' and ='bbb'. We have to replace all three characters from the first string with 'b' to make the strings anagrams. Test Case #02: You have to replace 'a' with 'b', which will generate "bb". Test Case #03: It is not possible for two strings of unequal length to be anagrams of one another. Test Case #04: We have to replace both the characters of first string ("mn") to make it an anagram of the other one. Test Case #05: and are already anagrams of one another. Test Case #06: Here S1 = "xaxb" and S2 = "bbxx". You must replace 'a' from S1 with 'b' so that S1 = "xbxb". """ #!/bin/python3 import math import os import random import re import sys # Complete the anagram function below. def anagram(s): n = len(s) if n % 2 != 0: return("-1") else: coun = 0 for i in set(s[:n//2]): coun += min(s[:n//2].count(i), s[n//2:].count(i)) return n//2 - coun if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): s = input() result = anagram(s) fptr.write(str(result) + '\n') fptr.close()
true
54c0a48e87f31af1f129a16230921cce367a1dbc
akshaali/Competitive-Programming-
/Hackerrank/AppendandDelete.py
2,682
4.125
4
""" You have a string of lowercase English alphabetic letters. You can perform two types of operations on the string: Append a lowercase English alphabetic letter to the end of the string. Delete the last character in the string. Performing this operation on an empty string results in an empty string. Given an integer, , and two strings, and , determine whether or not you can convert to by performing exactly of the above operations on . If it's possible, print Yes. Otherwise, print No. For example, strings and . Our number of moves, . To convert to , we first delete all of the characters in moves. Next we add each of the characters of in order. On the move, you will have the matching string. If there had been more moves available, they could have been eliminated by performing multiple deletions on an empty string. If there were fewer than moves, we would not have succeeded in creating the new string. Function Description Complete the appendAndDelete function in the editor below. It should return a string, either Yes or No. appendAndDelete has the following parameter(s): s: the initial string t: the desired string k: an integer that represents the number of operations Input Format The first line contains a string , the initial string. The second line contains a string , the desired final string. The third line contains an integer , the number of operations. Constraints and consist of lowercase English alphabetic letters, . Output Format Print Yes if you can obtain string by performing exactly operations on . Otherwise, print No. Sample Input 0 hackerhappy hackerrank 9 Sample Output 0 Yes Explanation 0 We perform delete operations to reduce string to hacker. Next, we perform append operations (i.e., r, a, n, and k), to get hackerrank. Because we were able to convert to by performing exactly operations, we print Yes. Sample Input 1 aba aba 7 Sample Output 1 Yes """ #!/bin/python3 import math import os import random import re import sys # Complete the appendAndDelete function below. def appendAndDelete(s, t, k): commonLength = 0 for i in range(min(len(t), len(s))): if s[i] == t[i]: commonLength +=1 else: break if len(s) + len(t) - 2*commonLength > k: return("No") elif (len(s) + len(t) - 2*commonLength)%2 == k%2: return("Yes") elif len(s) + len(t)-k < 0 : return("Yes") else: return("No") if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() t = input() k = int(input()) result = appendAndDelete(s, t, k) fptr.write(result + '\n') fptr.close()
true
ce478a6ae35501cd55525ebe7526d08075507965
ariv14/python
/Day2_number_manipulation/life_left_mini_project/life_left_mini_project.py
676
4.15625
4
# Lifetime calculator print("Lifetime calculator\nEnter your age and maximum expected age\n") age = input("Enter your age : ") max_age = input("Enter your maximum lifetime age :") print("\n") age_in_months = int(age) * 12 age_in_days = int(age) * 365 age_in_weeks = int(age) * 52 max_age_years = int(max_age) max_age_months = int(max_age) * 12 max_age_days = int(max_age) * 365 max_age_weeks = int(max_age) * 52 years_left = max_age_years - int(age) month_left = max_age_months - int(age_in_months) days_left = max_age_days - int(age_in_days) weeks_left = max_age_weeks - int(age_in_weeks) print(f"You have {days_left} days, {weeks_left} weeks and {month_left} months left.")
false
83e4ae0872601c41974ea40725d6dace62e0d338
ariv14/python
/Day3_if_else/ifelse.py
328
4.4375
4
# Even or odd number finder print("Welcome!! Please input any number to check odd or even !!\n") # Get the input number as integer number = int(input("Which number do you want to check? ")) #Write your code below this line if number % 2 == 0: print("The number is even number") else: print("The number is odd number")
true
5b05abfb21bf9b8dea2dd9de4d1d859b09dc0dd5
selinoztuurk/koc_python
/inclass/day1Syntax/lab1.py
1,416
4.25
4
def binarify(num): """convert positive integer to base 2""" if num<=0: return '0' digits = [] division = num while (division >= 2): remainder = division % 2 division = division // 2 digits.insert(0, str(remainder)) digits.insert(0, str(division % 2)) return ''.join(digits) print(binarify(10)) def int_to_base(num, base): """convert positive integer to a string in any base""" if num<=0: return '0' digits = [] division = num while (division >= base): remainder = division % base division = division // base digits.insert(0, str(remainder)) digits.insert(0, str(division % base)) return ''.join(digits) print(int_to_base(10, 3)) def base_to_int(string, base): """take a string-formatted number and its base and return the base-10 integer""" if string=="0" or base <= 0 : return 0 result = 0 for i in range(len(string), 0, -1): int(string[i-1]) return result print(base_to_int("101", 3)) ## 10 def flexibase_add(str1, str2, base1, base2): """add two numbers of different bases and return the sum""" result = int_to_base(tmp, base1) return result def flexibase_multiply(str1, str2, base1, base2): """multiply two numbers of different bases and return the product""" result = int_to_base(tmp, base1) return result def romanify(num): """given an integer, return the Roman numeral version""" result = "" return result
true
6f384b9f9c31765b2c7cb5e22af25202d686deb0
JusticeLenon/ProjectEuler
/project_euler.py
456
4.1875
4
''' List all multiples of 3 and 5 from 0 to 10000 and return the sum''' def if_multiple( nat_number ): '''Return True if it is a multiple of 3 or 5''' for i in range(1,10): if i % 3 == 0 or i % 5 == 0 : print i, 'True' else: print i, 'False return def apppend_to_arrray( myarray, item_to _append ) : '''Appends item_to_append to myarray''' return def sum_numbers( numbers ) : '''Sum of numers''' return
false
c08f06f789fc81a1672e797a41c1d8cc39801864
ptrkptz/udemy_python
/Python_Course/17_conditionals.py
841
4.125
4
grade1 = float(input ("Type the grade of the first test: ")) grade2 = float(input ("Type the grade of the second test: ")) absenses = int(input ("Type the number of absenses: ")) total_classes = int(input("Type the total number of classes: ")) avg_grade = (grade1 + grade2) /2 attendance = (total_classes - absenses) / total_classes print("Avg grade: ", round(avg_grade,2)) print("Attendance rate: ", str(round((attendance*100),2))+"%") if(avg_grade >= 6) : if (attendance >= 0.8) : print ("The student was approved.") else: print ("The student has failed due to attendance rate lower than 80%") elif(attendance >= 0.8): print ("The student has failed due to an average grade lower than 6.0.") else: print ("The student has failed due to an average grade lower than 6.0 & attendance rate lower than 80%")
true
1055f864fb549ae4202482553b16be2c046ff3d6
ptrkptz/udemy_python
/Python_Course/15_booleans.py
249
4.125
4
num1 = float(input("Type the 1st num:")) num2 = float(input("Type the 2nd num:")) if (num1 > num2): print(num1, " is greater than ", num2) elif(num1==num2): print(num1, " is equal to ", num2) else: print(num1, " is less than ", num2)
true
504b12b8de997337e4c6166ded242ff6d93d14ce
nimus0108/python-projects
/Tri1/anal_scores.py
535
4.25
4
# Su Min Kim # Analysis Scores num = input("") num_list = num.split() greater = 0 less = 0 def get_mean (num_list): m = 0 i = 0 x = len(num_list) for i in range (0, x): number = int(num_list[i]) m += number mean = m/x return mean for num in num_list: number = int(num) mean = get_mean(num_list) if number >= mean: greater += 1 else: less += 1 print("# of values equal to or greater than the mean: ", greater) print("# of values less than the mean: ", less)
true
c876053f4a23e86dcda291995c5142396ae5709f
meanJustin/Algos
/Demos/MergeSort.py
1,451
4.15625
4
# Python program for implementation of Selection # Sort import sys import time def mergeSort(arr): if len(arr) >1: mid = len(arr)//2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves mergeSort(L) # Sorting the first half mergeSort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i+= 1 else: arr[k] = R[j] j+= 1 k+= 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i+= 1 k+= 1 while j < len(R): arr[k] = R[j] j+= 1 k+= 1 # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] # Using readlines() file1 = open('myfile.txt', 'r') Lines = file1.readlines() arr = [] # Strips the newline character for line in Lines: arr.append(line.strip()) length = len(arr) print ("count :", length) start_time = time.perf_counter() mergeSort(arr) end_time = time.perf_counter() #Driver code to test above print ("Sorted array") for i in range(length): print(arr[i]) print ("time : Duration : Bubble Sort", end_time - start_time)
true
181accc46b0d03467a765e1b6f1fe8949f2799dc
prathapSEDT/pythonnov
/Collections/List/Slicing.py
481
4.1875
4
myList=['a',4,7,2,9,3] ''' slicing is the concept of cropping sequence of elements to crop the sequence of elements we need to specify the range in [ ] synatx: [starting position: length] here length is optinal, if we wont specify it, the compiler will crop the whole sequence form the starting position ''' # from index 3 get all the elements print(myList[3:]) # from index 3 get exactly one element print(myList[3:4]) # from index 3 get exactly two elements print(myList[3:5])
true
8c94185a47805431f457cb157523350c318ba831
prathapSEDT/pythonnov
/Collections/List/Len.py
208
4.1875
4
''' This length method is used to get the total length of elements that are available in the given list ''' myList=['raj','mohan','krish','ram'] ''' get the toatal length of a given list''' print(len(myList))
true
3aee5a7a4a62a9ab4339ff518c5efaa5e0afa539
prathapSEDT/pythonnov
/looping statements/WhileLoop.py
244
4.1875
4
''' while loop is called as indefinite loop like for loop , while loop will not end by its own in the while we need write a condition to break the loop ''' ''' Print Numbers from 1-50 using while loop ''' i=1 while(i<=50): print(i) i+=1
true
74095d49c7c1c157eb5aaed88edc31662600440c
wangrui-spiderNet/Python-100examples
/homework01.py
1,454
4.15625
4
# coding=UTF-8 ''' 【程序2】 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高    于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提    成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于    40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于    100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? 1.程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。       2.程序源代码: ''' sellary = int(raw_input("请输入利润(万):")) a = 10 b = 20 c = 40 d = 60 e = 100 list = [a, b, c, d, e] def calculate(num, list): if num < list[0]: return num * 0.1 if list[0] < num and num <= list[1]: return list[0] * 0.1 + (num - list[0]) * 0.075 if list[1] < num and num <= list[2]: return list[1] * 0.075 + (num - list[1]) * 0.05 if list[2] < num and num <= list[3]: return list[2] * 0.05 + (num - list[2]) * 0.03 if list[3] < num and num <= list[4]: return list[3] * 0.03 + (num - list[3]) * 0.015 else: return list[4] * 0.015 + (num - list[4]) * 0.01 print ('应得工资:', calculate(sellary, list))
false
9266236293a7e1c49900110e7e408876fcddf99d
VectorSigmaGen1/Basic_Introductory_Python
/Practical 10 - 3rd October 2019/p10p1.py
1,261
4.28125
4
# program to calculate the positive integer square root of a series of entered positive integer """ PSEUDOCODE request input for a positive integer and assign to variable num print "Please enter the positive integer you wish to calculate the square root of (Enter a negative integer to exit program): " WHILE num >= 0 assign the value of 0 to a variable root WHILE root squared < num root = root + 1 IF root squared is exactly equal to num THEN print"The square root of" num "is" root ELSE THEN print num "is not a perfect square." print "You have entered a negative integer. The program is terminated" """ num = int(input('Please enter the positive integer you wish to calculate the square root of\n(Enter a negative integer to exit program): ')) while num >= 0: root = 0 while root**2 < num: root += 1 if root**2 == num: print('The square root of', num, 'is', root) else: print(num, 'is not a perfect square.') num = int(input('Please enter another positive integer you wish to calculate the square root of\n(Enter a negative integer to exit program): ')) print('You have entered a negative integer\nThe program is terminated')
true
13080a3947d52e11797bd399fe8e3e3342dc4091
VectorSigmaGen1/Basic_Introductory_Python
/Practical 13 - 10th October/p13p5.py
1,013
4.53125
5
# Program to illustrate scoping in Python # Added extra variables and operations """ Pseudocode DEFINE function 'f' of variable 'x' and variable 'y' PRINT "In function f:" Set x = x+1 Set y = y * 2 set z = x-1 PRINT "x is", 'x' PRINT "y is", 'y' PRINT "z is", 'z' RETURN 'x' & 'y' Set x = 5 Set y = 10 Set z = 15 print "Before function f:" print "x is", 'x' print "y is", 'y' print "z is", 'z' CALL function 'f' print "After function f:" print "x is", 'x' print "y is", 'y' print "z is", 'z' """ def f(x, y): """Function that adds 1 to its argument and prints it out""" print("In function f:") x+=1 y*=2 z=x-1 print("x is", x) print("y is", y) print("z is", z) return x, y x, y, z = 5, 10, 15 print("Before function f:") print("x is", x) print("y is", y) print("z is", z) x, y=f(x, y) print("After function f:") print("x is", x) print("y is", y) print("z is", z)
true
7d1038aaa9fe2af8374685ac523187026e58280a
VectorSigmaGen1/Basic_Introductory_Python
/Practical 09 - 3rd October 2019/p9p3.py
969
4.28125
4
# program to calculate the factorial of an entered integer """ Pseudocode Set num = 0 WHILE input >= 0; Request input Print "Please enter a positive integer (If you wish to terminate the program, please enter a negative integer): " run = 1 for i in range(1, input+1, 1) run = run * i if input >= 1 print 'The factorial of the integers up to and including your number is: ', run print 'You have entered a negative integer' print 'Program Terminated' """ num = int(0) while num >= 0: num = int(input('Please enter a positive integer (If you wish to terminate the program, please enter a negative integer): ')) run = 1 for i in range(1, num+1): run *= i if num >= 0: print('The factorial of the integers up to and including your number is: ', run) print('You have entered a negative integer') print('Program Terminated')
true
0f1ad4d9a1bb6273f8e442b39f5c3281b4bd7e1a
VectorSigmaGen1/Basic_Introductory_Python
/Practical 07 - 26th Sep 2019/p7p3.py
619
4.34375
4
# program to print the first 50 integers and their squares # for this program, I've used the first 50 positive integers starting with 0 and ending with 49 ''' print 'This is a program to print the integers 0 to 49 and their squares' set variable=int(0) While variable <50 print variable print variable squared set variable=variable+1 print 'the program is now complete' ''' print ('This is a program to print the integers 0 to 49 and their squares') Num=int(0) while Num<50: print ('The square of', Num, 'is', Num**2) Num=(Num+1) print ('The program is now complete')
true
7a63238e5cb6c4ea552dfa07a6c3f7470c452dfa
VectorSigmaGen1/Basic_Introductory_Python
/Practical 12 - 8th October 2019/p12p2.py
1,703
4.40625
4
# Define the function fibonacci which displays 'a' number of terms of the Fibonacci Sequence # Program to check if an entered integer is a positive integer and if so to apply the function factorial to produce an answer """ Pseudocode Define function 'fibonacci' of a variable 'a': IF a > 0 set variable 'num1' = 0 set variable 'num2' = 1 print "Your Fibonacci sequence is " num1 and suppress newline FOR i in range (1,a) set num1 = current value of num 2 set new value of num2 = num1 + num2 print num1 print newline ELSE print "You have entered zero. This has returned no terms." request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " IF length < 0: print "Error: Number entered was less than 0." ELSE execute the function 'fibonacci' on length """ #Defining function to caluclate and display 'a' number of terms of the Fibonacci Sequence def fibonacci(a): if a>0: num1=0 num2=1 print("Your Fibonacci sequence is ", num1, " ", sep="", end="") for i in range(1,a): num1, num2 = num2, (num1+num2) print(num1, " ", sep="", end="") print() else: print("You have entered zero. This has returned no terms.") # program to check entered integer and call function if appropriate length = int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) if length < 0: print("Error: Number entered was less than 0.") else: fibonacci(length)
true
6f859d260c8d4fd41bb03d315defb665e4bc20f2
VectorSigmaGen1/Basic_Introductory_Python
/Practical 11 - 3rd October 2019/p11p3.py
1,772
4.5
4
# Program to check if an entered integer is a positive integer and if so to display that number of terms from the Fibonacci Sequence """ Pseudocode request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " WHILE length >= 0 IF length > 0 set variable 'num1' = 0 set variable 'num2' = 1 print "Your Fibonacci sequence is " num1 and suppress newline FOR i in range (1, length) set new value of num1 = current value of num 2 set new value of num2 = num1 + num2 print num1 print newline ELSE print "You have entered zero. This has returned no terms." request the input of an integer and assign it to variable 'length' print "Please enter the number of terms in the Fibonacci Sequence you would like: " print "You have entered a negative number - it isn't possible to display a negative number of terms. Please run the program again." """ length=int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) while length>=0: if length>0: num1=0 num2=1 print("Your Fibonacci sequence is ", num1, " ", sep="", end="") for i in range(1, length): num1, num2 = num2, (num1+num2) print(num1, " ", sep="", end="") print() else: print("You have entered zero. This has returned no terms.") length=int(input("Please enter the number of terms in the Fibonacci Sequence you would like: ")) print("You have entered a negative number - it isn't possible to display a negative number of terms. Please run the program again.")
true
7fb84f004a36f1ca3e2b6dee6c5c91652c8b46ef
VectorSigmaGen1/Basic_Introductory_Python
/Practical 07 - 26th Sep 2019/p7p4.py
746
4.28125
4
# program to add the first 5000 integers and give an answer # for this program, I've used the first 5000 positive integers, # starting with 0 and ending with 4999. """ print 'This is a program to add the integers 0 to 4999 and give a total' set variable=int(0) set sum=int(0) While variable <5000 set sum=sum+variable set variable=variable+1 print 'the program is now complete' print 'The sum of all of the integers from 0 to 4999 is', sum """ print('This is a program to add the integers from 0 to 4999 and give a total') Num = int(0) Sum = int(0) while Num < 5000: Sum = (Sum+Num) Num = (Num+1) print('The program is now complete') print('The sum of all of the integers from 0 to 4999 is', Sum)
true
db540b0084bd73a4f11a39cdadc04c394ad4e7cb
VectorSigmaGen1/Basic_Introductory_Python
/Practical 18 - 17th October 2019/p18p1.py
1,328
4.34375
4
# an iterative version of the isPal function # Checks whether a supplied string is a palindrome """ Pseudocode DEFINE function 'isPal(s)' Get the length of 's' and assign it to variable 'length' IF 'length' <=1 RETURN TRUE ELSE set variable 'check' = 0 FOR 'i' in range (start = 0, end = 'length'/2, iteration = 1) set variable 'result' = ('s' character[i] = 's' character['length'-1-'i']) IF 'result' is FALSE change variable 'check' to 1 IF check is not equal to 0 variable 'result2' = FALSE print 's' "is not a palindrome" ELSE variable 'result2' = TRUE print 's' "is a palindrome" RETURN 'result2' """ def isPal(s): length = len(s) if length <= 1: return True else: check=0 for i in range(length//2): result = s[i]==s[length-1-i] if not result: check=1 if check!=0: result2=False print(s, "is not a palindrome") else: result2=True print(s, "is a palindrome") return result2 # Container to request arguement and call function s=str(input("please enter a string for palindrome check: ")) isPal(s)
true
bfdacaad653068d62f82e45ace3cb120c33a5572
Vanshikagarg17/StonePaperScissor-Game
/Rock_Paper_Scissors v1.1.py
1,039
4.25
4
from random import randint winning=2 #scores comp=0 p=0 #scores while p<winning and comp<winning: rand_num = randint(0,2) print(f"computer score:{comp} player score:{p}\n") player = input("Player, make your move: \n").lower() if player=="quit" or player=="q": break if rand_num == 0: computer = "rock" elif rand_num == 1: computer = "paper" else: computer = "scissors" print(f"Computer plays {computer} \n" ) if player == computer: print("It's a tie!\n") elif player == "rock": if computer == "scissors": print("player wins!\n") p+=1 else: print("computer wins!\n") comp+=1 elif player == "paper": if computer == "rock": print("player wins!\n") p+=1 else: print("computer wins!\n") comp+=1 elif player == "scissors": if computer == "paper": print("player wins!\n") p+=1 else: print("computer wins!\n") comp+=1 else: print("Please enter a valid move!\n") if comp>p: print("the computer wins") elif p>comp: print("the player wins") else : print("its a tie")
false
6416bbd289069b4ad2208b0db6efe9e78c2cd05b
LuckyTyagi279/Misc
/python/loops_if.py
481
4.1875
4
#!/usr/bin/python # Loops # While Loop while 0 : Var=0 while Var < 5 : Var = Var + 1 print Var print "This is not in the loop!" # Conditional Statement # If statement while 0 : Var=1 if Var == 2 : print "Condition is TRUE!" else : print "Condition is FALSE!" while 0 : Var = 0 while Var <= 100 : if Var % 2 == 0 and Var % 3 == 0 : # Multiple Conditions use 'or' (||) / 'and' (&&) print Var elif Var % 7 == 0 : print Var Var = Var + 1 print "Here"
true
9176b405a1e2bf36da7475b43bc8470864f44aa1
zacherymoy/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,583
4.15625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here # print("merging",arrA,arrB) arrA_idx = 0 arrB_idx = 0 idx = 0 while arrA_idx < len(arrA) and arrB_idx < len(arrB): if arrA[arrA_idx] < arrB[arrB_idx]: merged_arr[idx] = arrA[arrA_idx] idx += 1 arrA_idx += 1 else: merged_arr[idx] = arrB[arrB_idx] idx += 1 arrB_idx += 1 while arrA_idx < len(arrA): merged_arr[idx] = arrA[arrA_idx] idx += 1 arrA_idx += 1 while arrB_idx < len(arrB): merged_arr[idx] = arrB[arrB_idx] idx += 1 arrB_idx += 1 return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here start = 0 end = len(arr) if end > start + 1: mid = int((start + end) / 2) # print(arr[0:mid], arr[mid:end], start, mid, end) arrA = merge_sort(arr[0:mid]) arrB = merge_sort(arr[mid:end]) arr = merge(arrA, arrB) return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input # def merge_in_place(arr, start, mid, end): # # Your code here # def merge_sort_in_place(arr, l, r): # Your code here
false
0adc8e05c38e52d54f8667a0fc8e4a99337941ed
traines3812/traines3812.github.io
/range_demo.py
605
4.5625
5
# The range function generates a sequence of integers a_range = range(5) print('a_range ->', a_range) print('list(a_range) ->', list(a_range)) # It is often used to execute a "for"loop a number of times for i in range (5): print(i, end= ' ') # executed five times print() # It is similar to the slice function with a start, stop, and step a_range = range(10) # stop only print('list(a_range) ->', list(a_range)) a_range = range(10, 16) # start and stop print('list(a_range) ->', list(a_range)) a_range = range(10, -1, -1) # start, stop and step print('list(a_range) ->', list(a_range))
true
7fea623eb32b3b2fbb1b8ef06f61ff42a4f5aeeb
HumayraFerdous/Coursera_Python_Basics
/Week4.py
1,728
4.125
4
#Methods mylist=[] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist.insert(1,12) print(mylist) print(mylist.count(12)) print(mylist.index(3)) print(mylist.count(5)) mylist.reverse() print(mylist) mylist.sort() print(mylist) mylist.remove(5) print(mylist) lastitem=mylist.pop() print(lastitem) print(mylist) #Strings scores=[("Rodney Dangerfield",-1),("Marlon Brando", 1),("You",100)] for person in scores: name=person[0] score=person[1] print("Hello {}.Your score is {}.".format(name,score)) #calculating discount origPrice=float(input('Enter the original price: $')) discount=float(input('Enter discount percentage: ')) newPrice=(1-discount/100)*origPrice calculation='${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice,discount,newPrice) print(calculation) #Accumulator patterns ## nums=[3,5,8] accum=[] for w in nums: x=w**2 accum.append(x) print(accum) ## verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"] ing=[] val="" for word in verbs: val=word+"ing" ing.append(val) print(ing) ## numbs = [5, 10, 15, 20, 25] newlist=[] for item in numbs: newlist.append(item+5) print(newlist) ## numbs = [5, 10, 15, 20, 25] i=0 for item in numbs: item=item+5 numbs[i]=item i+=1 print(numbs) ## lst_nums = [4, 29, 5.3, 10, 2, 1817, 1967, 9, 31.32] larger_nums=[] for item in lst_nums: larger_nums.append(item*2) print(larger_nums) ## s=input("Enter some text: ") ac="" for c in s: ac=ac+c+"-"+c+"-" print(ac) ## s = "ball" r = "" for item in s: r = item.upper() + r print(r) output="" for i in range(35): output+='a' print(output) ## a = ["holiday", "celebrate!"] quiet = a quiet.append("company") print(a)
true
33c556c7f36355f3735523e7cde0cf12868de8ae
Viniciusli/basic-of-python
/5.poo/e6.py
1,500
4.15625
4
# crie uma clsse Elevador. # attrs: andar atual, total de andares (exluindo terreo), capacidade do elevador, # e quantidade de pessoas presentes nele # métodos: incializa, recebe a capacidade, total de andares, entra, acrescenta uma pessoa # sai, subtrae uma pessoa, sobe, sobe um andar, desce, desce um andar # nesse exercício eu vou adotar o prédio como tendo 10 andares =) class Elevador: __capacidade = 10 def __init__(self) -> None: self._terreo = 0 self.andar_atual = self._terreo self.qtd_pessoas = 0 self.andares = 10 def entra(self) -> int: if self.qtd_pessoas < Elevador.__capacidade: self.qtd_pessoas += 1 elif self.qtd_pessoas >= Elevador.__capacidade: print("Capacidade máxima atingida\nPegue outro elevador") def sai(self) -> int: if self.qtd_pessoas == 0: print("Não tem ninguém") else: self.qtd_pessoas -= 1 def sobe(self, andar): if andar > 10: print("O prédio só vai até o 10º andar") else: self.andar_atual += andar - self.andar_atual def desce(self, andar): if andar < 0: print("O térreo é o 0.\nNão tem mais prédio para baixo disso") else: self.andar_atual -= self.andar_atual - andar def __str__(self) -> str: return f"Andar atual: {self.andar_atual}\nNúmero de pessoas: {self.qtd_pessoas}\nCapacidade: {Elevador.__capacidade}"
false
8ab5b7d8b7625d9a4401f9fff431dafc67627cf2
Viniciusli/basic-of-python
/3.lambdas/e12.py
265
4.125
4
# Exercício 2 - Crie uma função que receba uma string como argumento e retorne a mesma # string em letras maiúsculas. Faça uma chamada à função, passando como parâmetro uma # string def str_upper(str): return str.upper() print(str_upper("exemplo"))
false
96bf134d00802ad032852d9f789349fc358b042f
Jennykuma/coding-problems
/codewars/Python/invert.py
368
4.15625
4
''' Invert Values Level: 8 kyu Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] You can assume that all values are integers. ''' def invert(lst): return list(map(lambda x: x*-1, lst))
true
b36a9a9b65550021d6a95067e28fadf68555ec67
nishantgautamIT/python_core_practice
/pythonbasics/SetInPython.py
1,273
4.125
4
# Set in python # method in set # 1.union() set1, set2, set3 = {1, 2, 3}, {3, 4, 5}, {5, 6, 7} set_UN = set1.union(set2, set3) print(set1) print(set_UN) # 2. intersection() set_int = set2.intersection(set1) print(set_int) # 3. difference() set_diff = set1.difference(set2) print(set_diff) # 4. symmetric_difference() setSymDiff = set1.symmetric_difference(set2) print(setSymDiff) # 5. intersection_update() # It update the set on which perform intersection operation set1.intersection_update(set2) print(set1) # 6. difference_update() set4, set5, set6 = {1, 2, 3}, {3, 4, 5}, {5, 6, 7} set4.difference_update(set5) print(set4) # 7. symmetric_difference_update() set5.symmetric_difference_update(set6) print(set5) # 8. copy() set1 = set5.copy() # 9. disjoint() # This method returns True if two sets have a null intersection. set8, set9 = {1, 2, 3}, {4, 5, 6} print(set8.isdisjoint(set9)) # 10. issubset() # 11. issuperset() # Iterating on a Set for i in set5: print(i) # i. The frozenset # A frozen set is in-effect an immutable set. # You cannot change its values. Also, a set can’t be used a key for a dictionary, but a frozenset can. frozenset1 = {{1, 2}: 3} # frozenset2 = {frozenset(1, 2): 3} frozenset3 = {frozenset([1, 2]): 3} print(frozenset3)
true
a250d32dc61ec7b738b96e5e911c09434cc6f25f
nvincenthill/python_toy_problems
/string_ends_with.py
417
4.25
4
# Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). # Examples: # string_ends_with('abc', 'bc') # returns true # string_ends_with('abc', 'd') # returns false def string_ends_with(string, ending): length = len(ending) sliced = string[len(string) - length:] return sliced == ending # print(string_ends_with('abc', 'bc'))
true
c5167aaf0b17bc6b744043c389924270e3e235fe
nguyenlien1999/fundamental
/Session05/homework/exercise3.py
408
4.625
5
# 3 Write a Python function that draws a square, named draw_square, takes 2 arguments: length and color, # where length is the length of its side and color is the color of its bound (line color) import turtle def draw_square(size,colors): f = turtle.Pen() f.color(colors) # f.color(color) for i in range(3): f.forward(size) f.right(90) f.forward(size) f.done() draw_square(200,"blue")
true
3c927b72492f4f9a438ed8711aaff757b0f56009
Elijah-M/Module10
/class_definitions/invoice.py
2,468
4.40625
4
""" Author: Elijah Morishita elmorishita@dmacc.edu 10/26/2020 This program is used for creating an example of the uses of a class """ class Invoice: """ A constructor that sets the variables """ def __init__(self, invoice_id, customer_id, last_name, first_name, phone_number, address, items_with_price={}): self._invoice_id = invoice_id self._customer_id = customer_id self._last_name = last_name self._first_name = first_name self._phone_number = phone_number self._address = address self._items_with_price = items_with_price def __str__(self): """ A string conversion method :return: """ return "Invoice ID: " + self._invoice_id + "\n" \ "Customer ID: " + self._customer_id + "\n"\ + self._last_name + ', ' + self._first_name + "\n" \ + self._phone_number + "\n" \ + self._address def __repr__(self): """ An official true string conversion (more accurate) :return: """ return "Invoice ID: " + self._invoice_id + "\n" \ "Customer ID: " + self._customer_id + "\n"\ + self._last_name + ', ' + self._first_name + "\n" \ + self._phone_number + "\n" \ + self._address def add_item(self, x): """ This function adds items to a dictionary :param x: :return: """ self._items_with_price.update(x) def create_invoice(self): """ This function calculates the values of the dictionary, prints the tax total, and prints the full total :return: """ print(invoice, "\n", "=" * 40) for x, y in self._items_with_price.items(): print(x, y) tax = 0.06 # tax amount tax_total = list(self._items_with_price.values()) # converting the values of the dict to a list tax_total_sum = 0 for x in range(0, len(tax_total)): tax_total_sum = tax_total_sum + tax_total[x] tax = tax_total_sum * tax # Tax Total total = tax_total_sum + tax # Total invoice with tax print("Tax.....", tax) print("Total...", total) # Driver invoice = Invoice("9908", "432", "Morishita", "Elijah", "(555) 555-5555", "123 Main st.\nDes Moines, IA 50265") invoice.add_item({"Soda": 0.99}) invoice.add_item({"Hamburger": 3.99}) invoice.create_invoice()
true
60769c7f9ecb97369f20e2fcbdb9ba9fd8c70b85
jasanjot14/Data-Structures-and-Algorithms
/Algorithms/iterative_binary_search.py
1,661
4.375
4
# Function to determine if a target (target) exists in a SORTED list (list) using an iterative binary search algorithm def iterative_binary_search(list, target): # Determines the search space first = 0 last = len(list) - 1 # Loops through the search space while first <= last: # Updates the midpoint in the search space midpoint = first + (last - first) // 2 # Compares target to the midpoint and returns midpoint if true if target == list[midpoint]: return midpoint # Removes all elements in the right side of the search space if target is lower than the midpoint value elif target < list[midpoint]: last = midpoint - 1 # Removes all elements in the left side of the search space if target is higher than the midpoint value else: first = midpoint + 1 # Returns None if target does not exist in the list return None # Function to display the results of the implemented algorithm def verify(index): # Notifies the user of where the target exists in the list if found if index is not None: print("The target was found at index", index, "in the list.") # Notifies the user that the target does not exist in the list else: print("The target was not found in the list.") # Example case for if target exists in the list result = iterative_binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9) verify(result) # Example case for if target does not exist in the list result = iterative_binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 13) verify(result)
true
cdb88499d6704ec00b71e07c6386dde534e1acfe
316112840/Programacion
/ActividadesEnClase/EjemplosListas.py
771
4.125
4
S = "==========================================================" #Sucesión de Fibonacci: ListaFib = [1,1] for i in range(10): ListaFib.append( ListaFib[i] + ListaFib[i+1]) print(ListaFib) print(S) #Secuencia de Lucas: ListaLucas = [2,1] for i in range(10): ListaLucas.append( ListaLucas[i] + ListaLucas[i+1]) print(ListaLucas) print(S) #Tablas de multiplicar: ListaTablas = [] for i in range(11): Fila = [] for j in range(11): Fila.append(i*j) ListaTablas.append(Fila) print(ListaTablas) print(S) for i in range(11): print(ListaTablas[i]) print(S) for i in range(11): Fila = [] for j in range(11): Fila.append(i*j) print(Fila) print(S) for i in range(1,10): if i%5==0: break print(i)
false
06bf16ed3dc113f6c43578271d1e63088317cfbc
ajit-jadhav/CorePython
/1_Basics/7_ArraysInPython/a1_ArrayBasics.py
2,409
4.40625
4
''' Created on 14-Jul-2019 @author: ajitj ''' ## Program 1 ## Creating an integer type array import array a = array.array('i',[5,6,7]) print('The array elements are: ') for element in a: print (element) ## Program 2 ## Creating an integer type array v2 from array import * a = array('i',[5,6,7]) print('The array elements are: ') for element in a: print (element) ## Program 3 ## Creating an array with group of characters. from array import * arr = array('u',['a','b','c','d','e']) print('The array elements are: ') for ch in arr: print (ch) ## Program 4 ## Creating an array from another array. from array import * arr1 = array('d',[1.5,2.5,3,-4]) #use same type code and multiply each element of arr1 with 3 arr2 = array(arr1.typecode,(a*3 for a in arr1)) print('The array2 elements are: ') for i in arr2: print (i) #################### Indexing and Slicing in Array ############################### ## Program 5 ## A program to retrieve the elements of an array using rray index # accessing elements of an array using index from array import * x = array('i',[10,20,30,40,50]) #find number of elements in array n=len(x) #Display array elements using indexing for i in range(n): # repeat from 0 to n-1 print (x[i],end=' ') ## Program 7 ## A program that helps to know effects of slicingoperations on an array from array import * x = array('i',[10,20,30,40,50]) # create array y with elements from 1st to 3rd from x y = x[1:4] print(y) # create array y with elements from 0th till end from x y = x[0:] print(y) # create array y with elements from 0th to 3rd from x y = x[0:4] print(y) # create array y with last 4 elements from x y = x[-4:] print(y) # create array y with last 4th element and with 3 [-4-(-1)=-3]elements towards right y = x[-4:-1] print(y) # create array y with 0th to 7th elements from x # Stride 2 means, after 0th element, retrieve every 2nd element from x y = x[0:7:2] print(y) ##Program 8: ## Program to retrieve and display only a range of elements from an array using slicing. # using slicing to display elements of an array from array import * x = array('i',[10,20,30,40,50,60,70]) # display elements from 2nd to 4th only for i in x[2:5]: print(i)
true
fac0907fa4db80c8d9aa200e6f2f25d260e7e3d0
alex-gagnon/island_of_miscripts
/pyisland/src/classic_problems/StringToInteger.py
1,677
4.15625
4
import re class Solution: """Convert a string to an integer. Whitespace characters should be removed until first non-whitespace character is found. Next, and optional plus or minus sign may be found which should then be followed by any number of numerical digits. The digits should then be converted to and returned as an integer. """ def myAtoi(str) -> int: """Strips string of white space characters and searches for strings that may only start with 0 or 1 '+' or '-' signs followed by and ending with digits. If the pattern is found, returns the integer or the max or min if it exceed 2**31 - 1 or -2**31. """ str = str.strip() pattern = r"^[+-]?\d+" if re.search(pattern=pattern, string=str): num = re.search(pattern=pattern, string=str).group() return max(-pow(2, 31), min(pow(2, 31) - 1, int(num))) else: return 0 def myAtoi2(str) -> int: """Another possible solution similar to above but utilizes if statements to determine which int value to return. """ int_max = 2**31 - 1 int_min = -2**31 str = str.strip() pattern = re.compile('^[+-]?\d+') result = re.search(pattern, str) if result: num = int(result[0]) if num > int_max: return int_max elif num < int_min: return int_min else: return num else: return 0 if __name__ == '__main__': test = Solution() result = test.myAtoi(" 42") print(result)
true
dc5ec5f58a2ea2a44b36b921354884c3ce20d05b
JuliyaVovk/PythonLessons
/Lesson2/task2.py
883
4.46875
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input() """ my_list = [] while True: item = input('Введите элемент (для завершения нажмите Enter): ') if item == '': break my_list.append(item) print('Список до обмена: ', my_list) for i in range(0, len(my_list)-1, 2): my_list[i], my_list[i+1] = my_list[i+1], my_list[i] print('Список после обмена: ', my_list)
false
d42c35cf40853e6e1b60742c5c8aadf0a840d573
returnzero1-0/logical-programming
/sp-7.py
315
4.21875
4
# Python Program to Read Two Numbers and Print Their Quotient and Remainder ''' Quotient by floor division // Remainder by mod % ''' num1=int(input("Enter number 1 :")) num2=int(input("Enter number 2 :")) quotient=num1//num2 remainder=num1%num2 print("Quotient is :",quotient) print("Remainder is :",remainder)
true
a9356775b5a368568b29edc3b03d8a7f0e4a0a94
hscspring/The-DataStructure-and-Algorithms
/CodingInterview2/32_01_PrintTreeFromTopToBottom/print_tree_from_top_to_bottom.py
1,166
4.25
4
""" 面试题32(一):不分行从上往下打印二叉树 题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。 """ class BinaryTreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def connect_binarytree_nodes(parent: BinaryTreeNode, left: BinaryTreeNode, right: BinaryTreeNode) -> BinaryTreeNode: if parent: parent.left = left parent.right = right return parent def print_binary_tree(tree: BinaryTreeNode) -> list: """ Print tree from top to bottom. Parameters ----------- binary_tree: BinaryTreeNode Returns --------- out: list Tree items list. Notes ------ """ if not tree: return [] queue = [tree] res = [] while len(queue): node = queue.pop(0) res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return res if __name__ == '__main__': pass
false
d480263ae734088e84a8f207e420f2c85babbf91
hscspring/The-DataStructure-and-Algorithms
/CodingInterview2/06_PrintListInReversedOrder/print_list_in_reversed_order.py
1,152
4.40625
4
""" 面试题 6:从尾到头打印链表 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。 """ class Node: def __init__(self, x): self.val = x self.next = None def print_list_reverse(node) -> list: """ print_list_reverse(Node) Print a linklist reversedly. Parameters ----------- Node: Node Returns ------- out: list """ res, stack = [], [] while node: stack.append(node.val) node = node.next while len(stack): res.append(stack.pop()) return res def print_list_reverse_recursive(node, res) -> list: if node: res.insert(0, node.val) print_list_reverse_recursive(node.next, res) def lst2link(lst): root = Node(None) ptr = root for i in lst: ptr.next = Node(i) ptr = ptr.next ptr = root.next return ptr if __name__ == '__main__': lst = [1, 2, 3, 4, 5] # lst = [1] node = lst2link(lst) # while node: # print(node.val) # node = node.next res = [] print_list_reverse_recursive(node, res) print(res)
false
fd8f8bb43ed0602c7c7d022d9113e0e1b2707462
hscspring/The-DataStructure-and-Algorithms
/CodingInterview2/58_02_LeftRotateString/left_rotate_string.py
1,034
4.125
4
""" 面试题 58(二):左旋转字符串 题目:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。 请定义一个函数实现字符串左旋转操作的功能。比如输入字符串 "abcdefg" 和数 字 2,该函数将返回左旋转 2 位得到的结果 "cdefgab"。 """ def left_rotate_string(s: str, index: int) -> str: """ Parameters ----------- Returns --------- Notes ------ """ if not s: return s left = reverse(s[:index]) right = reverse(s[index:]) return reverse(left+right) def reverse(s: str) -> str: res = [] for i in range(1, len(s)+1): res.append(s[-i]) return "".join(res) def left_rotate_string_easy(s: str, index: int) -> str: if not s: return s return s[index:] + s[:index] if __name__ == '__main__': s = "abcdefg" res = left_rotate_string(s, -7) print(res) res = left_rotate_string_easy(s, -7) print(res)
false
d30ef4fe2f71d84f33e76247a4952772ccbbbdb1
hscspring/The-DataStructure-and-Algorithms
/CodingInterview2/55_02_BalancedBinaryTree/balanced_binary_tree.py
2,994
4.25
4
""" 面试题55(二):平衡二叉树 题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中 任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 """ class BSTNode: """docstring for BSTNode""" def __init__(self, val): self.val = val self.left = None self.right = None def connect_bst_nodes(head: BSTNode, left: BSTNode, right: BSTNode) -> BSTNode: if head: head.left = left head.right = right def tree_depth(bst: BSTNode) -> int: if not bst: return 0 left = tree_depth(bst.left) right = tree_depth(bst.right) if left > right: return left + 1 else: return right + 1 # max(depth(bst.left), depth(bst.right)) + 1 def tree_is_balanced(bst: BSTNode) -> bool: """ Parameters ----------- lst: the given bst Returns --------- the depth Notes ------ """ if not bst: return True left = tree_depth(bst.left) right = tree_depth(bst.right) diff = left - right if diff > 1 or diff < -1: return False return tree_is_balanced(bst.left) and tree_is_balanced(bst.right) def dfs_height(bst: BSTNode) -> int: if not bst: return 0 left = dfs_height(bst.left) if left == -1: return -1 right = dfs_height(bst.right) if right == -1: return -1 diff = left - right if diff > 1 or diff < -1: return -1 return max(left, right) + 1 def tree_is_balanced2(bst: BSTNode) -> bool: return dfs_height(bst) != -1 def tree_is_balanced3(bst: BSTNode) -> bool: # or set res as a global variable return get_height(bst)[1] def get_height(bst: BSTNode): if not bst: return 0, True left, res = get_height(bst.left) right, res = get_height(bst.right) diff = left - right if diff > 1 or diff < -1: res = False return max(left, right) + 1, res if __name__ == '__main__': tree = BSTNode(10) connect_bst_nodes(tree, BSTNode(6), BSTNode(14)) connect_bst_nodes(tree.left, BSTNode(4), BSTNode(8)) connect_bst_nodes(tree.right, BSTNode(12), BSTNode(16)) tree = BSTNode(1) connect_bst_nodes(tree, None, BSTNode(2)) connect_bst_nodes(tree.right, None, BSTNode(3)) connect_bst_nodes(tree.right.right, None, BSTNode(4)) connect_bst_nodes(tree.right.right.right, None, BSTNode(5)) tree = BSTNode(1) connect_bst_nodes(tree, BSTNode(2), BSTNode(2)) connect_bst_nodes(tree.left, BSTNode(3), None) connect_bst_nodes(tree.right, None, BSTNode(3)) connect_bst_nodes(tree.left.left, BSTNode(4), None) connect_bst_nodes(tree.right.right, None, BSTNode(4)) # res = tree_is_balanced(tree) # print(res) # res = True # res = tree_is_balanced3(tree) # print(res) height = dfs_height(tree) print(height) print(tree_is_balanced4(tree))
false
533516eaf7b44a007b79a9f00e283bfd865ad017
friedaim/ITSE1359
/PSET4/PGM1.py
1,934
4.125
4
# Program to calculate loan interest, # monthly payment, and overall loan payment. def calcLoan(yrRate,term,amt): monthRate = yrRate/12 paymentNum = (pow(1+monthRate,term)*monthRate) paymentDen = (pow(1+monthRate,term)-1) payment = (paymentNum/paymentDen)*amt paybackAmt = payment*term totalInterest = paybackAmt-amt print(f""" Loan Amount: ${amt} Annual Interest Rate: {round(yrRate*100,2)}% Number of Payments: {term} Montly Payment: ${round(payment,2)} Amount Paid Back: ${round(paybackAmt,2)} Interest Paid: ${round(totalInterest,2)}""") print("Loan Calculator Program- Type 'help' for help.") while True: command = input("Enter Command: ") if(command=="exit"): break # Help menu if(command=="help"): print(""" ----------- Available commands: 'help' - displays this menu 'loan' - calculate a loan payment 'exit' - leave the program ----------- """) # Loan calculations and input validation if(command == "loan"): rate = 0 term = 0 amount = 0 while True: # Use try catch for taking only the corrent input try: rate = float(input("What is the yearly interest rate? ")) except: continue break #rate = float(input("What is the yearly interest rate? " #"(exclude % sign) ")) while True: try: term = int(input("What is the loan term (months)? ")) except: continue break while True: try: amount = float(input("What is the total amount for the loan? $")) except: continue break rate = rate/100 calcLoan(rate,term,amount)
true
532eb7059007dab0ce39b0e7a53559d12c696d86
mjadair/intro-to-python
/functions/arguments.py
1,473
4.375
4
# Navigate to functions folder and type python arguments.py to run # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Define a function "sayHello" that accepts a "name" parameter. It should return a string of 'Hello (the name)!' # ? Call and print the result of the function twice, passing different "name" arguments. # ? Define a function "add" that accepts two numbers, "a" and "b" as parameters. It should return the result of adding them together # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "wordLength" that takes a string as a parameter, it should return a number of the length of that passed string # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "shout" that accepts two strings as parameters. It should return the strings joined together in all uppercase eg 'hello', 'world' --> 'HELLOWORLD' # ? Call and print the result of the function a few times, passing different arguments. # ? Define a function "findCharacterIndex" that accepts two parameters, a string, and a number. The function should return the character in the passed string found at the passed index number. If the index to return is longer than the string, it should return the string 'Too long' # ? Call and print the result of the function a few times, passing different arguments.
true
485f7f408cbe0ba4f7ed22f940dfe1da28fc18b4
mjadair/intro-to-python
/control-flow/loops.py
1,190
4.1875
4
# * ----- FOR LOOPS ------ * # ! Navigate to the directory and type `python loops.py` to run the file # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Write a for loop that prints the numbers 0 - 10 # ? Write a for loop that prints the string 'Hello World' 10 times # ? Write a for loop that prints the numbers 50 to 88 # ? BONUS - Declare a "let" with the label "result" and the value empty string. # ? use a for loop and string concatenation to built the string '123456789' and print it to the console # * ----- WHILE LOOPS ------ * # ! Remember, run`python loops.py` to run the file # * 🦉 Practice # ! ⚠️Remember to comment out your practice code before attempting below, "cmd" + "/" # ? Write a while loop that prints the numbers 0 - 10 # ? Write a while that prints the string 'Hello World' 5 times # ? BONUS - Write a while loop that will check if a random number is above or below 0.5, If it is the loop should print 'still running!' and the random number. When it has finished, it should print 'Stopped', and the randomNumber is stopped with. How many times will this log print?
true
afca7c31b72f51f3cf3b96c33dcf0e9da76a4f39
Zahidsqldba07/Python_Practice_Programs
/college/s3p4.py
235
4.1875
4
# WAP to find largest and smallest value in a list or sequence nums = [] n = int(input("How many numbers you want to input? ")) for i in range(n): nums.append(int(input(">"))) print("Max: %d\nMin: %d" % (max(nums), min(nums)))
true
1d91eda9d5e992d2ba82dd74cec9586b5d0c58b4
Zahidsqldba07/Python_Practice_Programs
/college/p7.py
279
4.375
4
# WAP to read a set of numbers in an array & to find the largest of them def largest(arr): return max(arr) arr = list() num = input("How many elements you want to store? ") for i in range(int(num)): num = input("Num: ") arr.append(int(num)) print(largest(arr))
true
6c39bdf7ab868326265d9724569004623651d493
Zahidsqldba07/Python_Practice_Programs
/college/s2p7.py
269
4.125
4
# WAP that demonstrates the use break and continue statements to alter the flow of the loop. while True: name = str(input("Name: ")) if name.isalpha(): print("Hello %s" % name) break else: print("Invalid name.\n") continue
true
b237f52ce5495587b91a32e80c9ab9645fde6c1d
Zahidsqldba07/Python_Practice_Programs
/college/2_9.py
2,585
4.15625
4
relation=raw_input('Enter the relationship:') name=raw_input('Enter the name:') if relation=='parents' and (name=='madd' or name=='sally'): print 'parents are cathy and don' elif relation=='parents' and name=='sarah' : print 'parents are frank and jill' elif relation=='parents' and (name=='frank' or name=='cathy' or name=='bill'): print 'parents are ann and marty' elif relation=='parents' and (name=='bart' or name=='mary' or name=='jane') : print 'parents are betty and paul' elif relation=='parents' and (name=='jill' or name=='betty') : print 'parents are debby and phil' elif relation=='child' and (name=='ann' or name=='marty') : print 'child ren are bill , cathy and frank' elif relation=='child' and (name=='cathy' or name=='don') : print 'children are madd and sally' elif relation=='child' and (name=='frank' or name=='jill') : print 'child is sarah' elif relation=='child' and (name=='debby' or name=='phil') : print 'children are jill and betty' elif relation=='child' and (name=='alice' or name=='bill') : print 'NO child' elif relation=='child' and (name=='paul' or name=='betty') : print 'child ren are bart , mary and jane' elif relation=='grandParent' and (name=='madd' or name=='sally' or name=='sarah') : print 'grandparents are ann and marty' elif relation=='grandParent' and (name=='sarah' or name=='bart' or name=='mary' or name=='jane') : print 'grandparents are debby and phil' elif relation=='grandchild' and (name=='ann' or name=='marty') : print 'grandchild are madd , sally and sarah' elif relation=='grandchildren' and (name=='debby' or name=='phil') : print 'grandchildren are sarah , bart , mary and jane' elif relation=='sibbling' and name=='madd' : print 'sibbling is sally' elif relation=='sibbling' and name=='sally' : print 'sibbling is madd' elif relation=='sibbling' and name=='bill' : print 'sibbling are cathy and frank' elif relation=='sibbling' and name=='cathy' : print 'sibbling are bill and frank' elif relation=='sibbling' and name=='frank' : print 'sibbling are bill and cathy' elif relation=='sibbling' and name=='bart' : print 'sibbling are mary and jane' elif relation=='sibbling' and name=='mary' : print 'sibbling are jane and bart' elif relation=='sibbling' and name=='jane' : print 'sibbling are mary and bart' elif relation=='sibbling' and name=='jill' : print 'sibbling is betty' elif relation=='sibbling' and name=='betty' : print 'sibbling is jill' elif relation=='sibbling' and name=='sarah' : print 'NO sibblings'
false
b2cece558ed3391220af52e1e13b2329bca82ab3
Zahidsqldba07/Python_Practice_Programs
/college/s8p2.py
358
4.1875
4
# Define a class name circle which can be constructed using a parameter radius. # The class has a method which can compute the area using area method. class Circle: radius = 0 def __init__(self, radius): self.radius = radius def displayArea(self): print("Area:", (3.14 * (self.radius ** 2))) a1 = Circle(5) a1.displayArea()
true
1905d855a2b37259c47229175eefec2625df5482
Zahidsqldba07/Python_Practice_Programs
/college/s4p1.py
264
4.1875
4
# WAP to create a function to swap values of a pair of integers def swap(a, b): a, b = b, a return (a, b) in_a, in_b = input("a: "), input("b: ") print("Before swap a:", in_a, " b:", in_b) s = swap(in_a, in_b) print("After swap a:", s[0], " b:", s[0])
false
6a77a5bca7b96861c6bbd9404ebc467afd28d470
kokilavemula/python-code
/inheritances.py
922
4.25
4
#Create a Parent Class class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("kokila", "vemula") x.printname() #Create a child class class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): pass x = Student("Mysore", "palace") x.printname() #super() Function class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) x = Student("vemula", "kokila") x.printname()
true
403e3c0dc245a2f412c3de8ed7d78c3f12fd2e4a
kokilavemula/python-code
/dictionaries.py
611
4.40625
4
thisdict = { "brand": "moto", "model": "2nd gen", "year": 2016 } print(thisdict) #Accessing Items thisdict = { "brand": "moto", "model": "2nd gen", "year": 2016 } x = thisdict["model"] print(x) #Accessing Item in another method thisdict = { "brand": "moto", "model": "2nd gen", "year": 2016 } x = thisdict.get("model") print(x) #Change Values thisdict = { "brand": "moto", "model": "2nd gen", "year": 2016 } thisdict["year"] = 2020 print(thisdict) #Copy a Dictionary thisdict = { "brand": "moto", "model": "2nd gen", "year": 2016 } mydict = thisdict.copy() print(mydict)
false
7b2d2d37f5acf56da96b52e0665532969285978c
gnoubir/Network-Security-Tutorials
/Basic Cryptanalysis/basic-analyze-file.py
1,983
4.15625
4
#!/usr/bin/python # # computer the frequency of lowercase letters __author__ = "Guevara Noubir" import collections import argparse import string import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='Analyze a file.') # ./basic-analyze-file.py file # program has one parameter the name of the file to analyze # parser.add_argument("file", type=str, help="counts characters frequency file") # parse arguments args = parser.parse_args() # known statistics of alphabet letters in English text used for comparison english_alphabet_stats = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.0236, 0.0015, 0.01974, 0.00074] letters = collections.Counter('') # opens file and processes line by line using collections module with open(args.file,'r') as f: for line in f: for word in line.split(): letters.update(word.lower()) #print letters count = 0 stats = [] # counts the total number of lowercase letters for l in string.ascii_lowercase: count += letters[l] # computes and prints frequency/probability of each lowercase letter for l in string.ascii_lowercase: stats += [float(letters[l])/count] print l, ": ", float(letters[l])/count print "\n ----------------- \n" #print letters.keys() #print letters.values() pos = np.arange(26) width = 1.0 # gives histogram aspect to the bar diagram ax = plt.axes() ax.set_xticks(pos ) ax.set_xticklabels(string.ascii_lowercase) # rects1 is english_bars = plt.bar(range(len(list(string.ascii_lowercase))), english_alphabet_stats, -width/3, color='r', alpha=0.5, align='edge') this_file_bars = plt.bar(range(len(stats)), stats, width/3, color='g', alpha=0.5, align='edge') ax.legend((english_bars[0], this_file_bars[0]), ('English Stats', args.file)) # plt.show()
true
ae9f2189f73437e8ab24932c8f44108d7cbb467d
UMBC-CMSC-Hamilton/cmsc201-spring2021
/classes_start.py
1,501
4.21875
4
""" A class is a new type ints, floats, strings, bool, lists, dictionaries class <-- not really a type a type maker. What kind of things can types have? data inside of them (member variables, instance variables) functions inside of them. """ class Lion: """ Constructor for the lion class. """ # 2x underscore init 2x underscore def __init__(self, name): self.lion_name = name self.position = '' def eat(self, food): print(self.lion_name, 'eats', food) def roar(self): print(self.lion_name, 'roars... ROAR!!!!') def run(self, destination): """ secret of self is that it knows that the first argument is actually the calling class. :param destination: :return: """ print(self.lion_name, 'has run to ', destination) self.position = destination def sleep(self, time): print(self.lion_name, 'has slept for {} hours'.format(time)) """ Each class has its own variables, it's own data. They all kind of share the functions though. We are making built-in functions for a variable type. """ leo_the_lion = Lion('Leo') hercules = Lion('Hercules') simba = Lion('Simba') simba.sleep(5) # Lion.sleep(simba, 5) # that's the secret. # self is actually "simba" hercules.eat('villager') # hercules.eat('villager') # Lion.eat(hercules, 'villager') leo_the_lion.roar() # Lion.roar(leo_the_lion)
true
0fac1e302275fd8c77181ceca7f85afdf0056bc4
mackrellr/PAsmart
/rock_paper_scissors.py
2,208
4.1875
4
import random player_choice = 0 npc_choice = 0 game_on = True # Indicate choices for win def choices(p1, p2): print() if p1 == 1: print('Player choose Rock.') if p1 == 2: print('Player choose Paper.') if p1 == 3: print('Player choose Scissors.') if p2 == 1: print('Opponent choose Rock.') if p2 == 2: print('Opponent choose Paper.') if p2 == 3: print('Opponent choose Scissors.') def winner(p1, p2): # Rock (1) beats scissors (3) if p1 == 1 and p2 == 3: print('You win. Rock crushes scissors.') if p2 == 1 and p1 == 3: print('You loose. Rock crushes scissors.') # Scissors (3) beats paper (2) if p1 == 3 and p2 == 2: print('You win. Scissors cuts paper. ') if p2 == 3 and p1 == 2: print('You loose. Scissors cuts paper.') # Paper (2) beats rock (1) if p1 == 2 and p2 == 1: print('You win. Paper covers rock.') if p2 == 2 and p1 == 1: print('You loose. Paper covers rock.') # Indicate a tie if p1 == p2: choices = ['rock', 'paper', 'scissors'] print('Tie. You both choose ' + choices[p1-1] + '.') #Loop the game until a specified number of wins while game_on: # Player input choice_bank = input('Rock [1], paper [2], scissors [3], shoot! ') if choice_bank != '1' and choice_bank != '2' and choice_bank != '3': print('Incorrect entry, please choose: ') else: player_choice = int(choice_bank) # Random computer input npc_choice = random.randrange(1, 4) choices(player_choice, npc_choice) winner(player_choice, npc_choice) # Offer to exit the game game_quit = True while game_quit: exit_game = input('Would you like to play again y/n? ') if exit_game == 'n': print('Thank you for playing!') game_quit = False game_on = False elif exit_game != 'y' and choice_bank != 'n': print('Incorrect entry.') elif exit_game == 'y': game_quit = False game_on = True
true
9ee2c7e4e8b520c97faf5a6e0c176c1732f991a2
EharaProgramming/python_introduction
/4/4_1.py
814
4.3125
4
# リストの関数 list1 = ["Banana", "Apple", "Tomate", 4000] print(list1) # 要素の追加 list1.append("dddd") print(list1) # リストの結合 list += ["z","c","v","b"] list1.extend(["z","c","v","b"]) print(list1) # 指定した場所に要素を挿入 list1.insert(4, "n") print(list1) # 要素の削除 関数ではない del list1[4] print(list1) # 要素の削除 値指定 list1.remove("Banana") print(list1) # 要素を取り出して削除 デフォルトは indexが-1 val = list1.pop(0) print(val) print(list1) # ソート float型も自動で判別してくれる list2 = [100, 222, 231, 1233, 100.1, -123] print(list2) list2.sort() print(list2) list2.sort(reverse=True) print(list2) # リストの要素数を取得 len = len(list2) print(len)
false
a41f693540a8e551d59dc79c64619b7f56220c31
EharaProgramming/python_introduction
/10/10.py
406
4.21875
4
# イテレータ # まずはリストの確認 list = [1, 2, 3, 4, 5] for i in list : if i < 3 : print(i) elif i == 3 : print(i) break for i in list : print(i) # リストからイテレータを生成 it = iter(list) for i in it : if i < 3 : print(i) elif i == 3 : print(i) break for i in it : print(i)
false
bde72147f0609811ecca5e12bd8a2b56f1c8d06f
kaliadevansh/data-structures-and-algorithms
/data_structures_and_algorithms/challenges/array_reverse/array_reverse.py
2,916
4.53125
5
""" Reverses input array/list in the order of insertion. """ def reverseArray(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by iterating half of the list and without using additional space. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list list_length = len(input_list) counter = 0 while counter < floor(list_length / 2): input_list[counter] += input_list[list_length - counter - 1] input_list[list_length - counter - 1] = input_list[counter] - input_list[list_length - counter - 1] input_list[counter] = input_list[counter] - input_list[list_length - counter - 1] counter += 1 return input_list def reverse_array_stack(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by using additional space of a stack and then popping elements from the stack. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list stack = [] for current_value in input_list: stack.append(current_value) reversed_list = [] list_counter = len(stack) while list_counter > 0: reversed_list.append(stack.pop()) list_counter -= 1 return reversed_list def reverse_array_iterate(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by iterating the input list in reverse. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list reversed_list = [] for current_value in input_list[::-1]: reversed_list.append(current_value) return reversed_list def skip_reverse(input_list): """ Checks if initialized input list has 0 or 1 elements, hence reverse operation can be skipped. :param input_list: The list to be checked for skipping reverse. :return: Input list if list has 0 or 1 elements; none otherwise. """ list_length = len(input_list) if list_length == 0 or list_length == 1: return input_list def floor(input_number): """ This function is local implementation of floor function just for the scope of this problem. This method was created to satisfy the ask of not using in-built language functions. :param input_number: Number whose floor value is to be calculated.. :return: Floor value of input number. """ decimal_digits = input_number % 1 return input_number - decimal_digits
true
a41a499a78fc0dc44174812b5b3b7db1e12239b3
FranVeiga/games
/Sudoku_dep/createSudokuBoard.py
1,654
4.125
4
''' This creates an array of numbers for the main script to interpret as a sudoku board. It takes input of an 81 character long string with each character being a number and converts those numbers into a two dimensional array. It has a board_list parameter which is a .txt file containing the sudoku boards as strings. ''' import random def main(board_file): try: with open(board_file, 'r') as file: boards = file.readlines() file.close() newboards = [] for i in boards: if i.endswith('\n'): i = i.replace('\n', '') newboards.append(i) boards = newboards randomBoard = boards[random.randint(0, len(boards) - 1)] randomBoardArray = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] for i in range(len(randomBoard)): x = i % 9 y = i // 9 randomBoardArray[y][x] = int(randomBoard[i]) return randomBoardArray except FileNotFoundError: print(f'Error loading board {board_file}') if __name__ == '__main__': print(main(input()))
true
b1acafeca378a52e04c04b3935c2cf65a6c65445
chengguobiao/SortAlgorithm
/SelectionSort.py
1,466
4.28125
4
#!usr/bin/env python #-*- coding: utf-8 -*- ''' 名字:直接插入排序(选择排序) 思想:从所有序列中先找到最小的,然后放到第一个位置。之后再看剩余元素中最小的,放到第二个位置 直至排序结束,程序中首轮一般会选第一个元素作为最小值。 ''' import time import random def randomnumber_generate(total_num=100, max_num=1000): num_list = [] n = 1 #得到1000以内的100个随机数 while n <= total_num: lin = random.randint(0, max_num) num_list.append(lin) n += 1 return num_list def selectionsort(num_list): if num_list != None: for i in range(len(num_list)): min_num = i for j in range(i+1,len(num_list)): if num_list[min_num] > num_list[j]: min_num = j if min_num != i: print 'i is ------>' + str(i) print 'min_num is------>' + str(min_num) print '交换前:--------->', num_list num_list[min_num],num_list[i] = num_list[i],num_list[min_num] print '交换后:--------->', num_list if __name__ == '__main__': num_list = randomnumber_generate() start_time = time.time() selectionsort(num_list) end_time = time.time() print '排序结果为:---------->' print num_list print '总耗时:--------->', end_time - start_time
false
828066159ed3f735e0ea6b16ce8c81b23e62ff1d
DipeshDhandha07/Data-Structure
/infix to postfix2.py
1,310
4.1875
4
# The main function that converts given infix expression # to postfix expression def infixToPostfix(self, exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self.isOperand(i): self.output.append(i) # If the character is an '(', push it to stack elif i == '(': self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i == ')': while( (not self.isEmpty()) and self.peek() != '('): a = self.pop() self.output.append(a) if (not self.isEmpty() and self.peek() != '('): return -1 else: self.pop() # An operator is encountered else: while(not self.isEmpty() and self.notGreater(i)): self.output.append(self.pop()) self.push(i) # pop all the operator from the stack while not self.isEmpty(): self.output.append(self.pop()) print "".join(self.output) # Driver program to test above function exp = "a+b*(c^d-e)^(f+g*h)-i" obj = Conversion(len(exp)) obj.infixToPostfix(exp)
true
ca1ad7d1ad24c77156a97b54683f63dc205c2730
kaushikamaravadi/Python_Practice
/Transcend/facade.py
888
4.125
4
"""Facade Design Pattern""" class Vehicle(object): def __init__(self, type, make, model, color, year, miles): self.type = type self.make = make self.model = model self.color = color self.year = year self.miles = miles def print(self): print("vehicle type is",str(self.type)) print("vehicle make is", str(self.make)) print("vehicle model is", str(self.model)) print("vehicle color is", str(self.color)) print("vehicle year is", str(self.year)) print("vehicle miles is", str(self.miles)) class Car(Vehicle): def prints(self): Vehicle.print(self) return Vehicle.print(self) def drive(self, speed): peek = "the car is at %d" %speed return peek car = Car(30, 'SUV', 'BMW', 'X5', 'silver', 2003) print(car.print()) print(car.drive(35))
true
ff5ca971a1feac7ea7c26d34f8e3b63e4a4c2ea5
kaushikamaravadi/Python_Practice
/DataStructures/linked_list.py
2,244
4.1875
4
"""Linked List""" class Node(object): def __init__(self, data=None, next=None): self.data = data self.next = next def get_data(self): return self.data def get_next(self): return self.next def set_next(self, new_next): self.next = new_next class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node def size(self): current = self.head count = 0 while current: count += 1 current = current.get_next() return count def search(self, data): current = self.head while current: if current.get_data() == data: return current else: current = current.get_next() return None def remove(self, data): current = self.head prev = None while current: if current.get_data() == data: if current == self.head: self.head = current.get_next() else: prev.set_next(current.get_next()) return current prev = current current = current.get_next() return None def print(self): final = [] current = self.head while current: final.append(str(current.get_data())) current = current.get_next() print('->'.join(final)) linked_list = LinkedList() while True: default = """ 1. Add 2. Size 3. Search 4. Remove 5. Print the Linked list """ print(default) option = int(input("Select any option")) if option == 1: element = input("\nEnter the element you want to add") linked_list.add(element) if option == 2: print(linked_list.size()) if option == 3: item = input("\nEnter the element you want to search") print(linked_list.search(item)) if option == 4: data1 = input("\nEnter the element you want to search") linked_list.remove(data1) if option == 5: linked_list.print()
true
98dbb8522901dbbc9af3fc2f30eecf2a88dce9b9
toopazo/static_MT_BET_analysis
/python_code/eg_abstract.py
1,252
4.125
4
# Python program showing # abstract base class work from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass def classname(self): print('Base class method: type(self) %s ' % type(self)) class Triangle(Polygon): def noofsides(self): print("I have 3 sides") class Pentagon(Polygon): def noofsides(self): print("I have 5 sides") class Hexagon(Polygon): def noofsides(self): print("I have 6 sides") class Quadrilateral(Polygon): def noofsides(self): print("I have 4 sides") def classname(self): super(Quadrilateral, self).classname() # print(super().classname()) print('Quadrilateral class method: type(self) %s ' % type(self)) if __name__ == "__main__": # Driver code obj = Triangle() obj.noofsides() obj.classname() print('--') obj = Quadrilateral() obj.noofsides() obj.classname() print('--') obj = Pentagon() obj.noofsides() obj.classname() print('--') obj = Hexagon() obj.noofsides() obj.classname() print('--') assert(isinstance(obj, Polygon)) print('isinstance(obj, Polygon) %s' % isinstance(obj, Polygon))
false
a80c87614a06de6b2c9b0293520196b93418e5ea
Rokesshwar/Coursera_IIPP
/miniproject/week 2_miniproject_3.py
2,291
4.1875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random # initialize global variables used in your code range = 100 secret_num = 0 guesses_left = 0 # helper function to start and restart the game def new_game(): global range global secret_num global guesses_left secret_num = random.randrange(0, range) if range == 100 : guesses_left = 7 elif range == 1000 : guesses_left = 10 print "New game. The range is from 0 to", range, ". Good luck!" print "Number of remaining guesses is ", guesses_left, "\n" pass # define event handlers for control panel def range100(): global range range = 100 # button that changes range to range [0,100) and restarts new_game() pass def range1000(): global range range = 1000 # button that changes range to range [0,1000) and restarts new_game() pass def input_guess(guess): # main game logic goes here global guesses_left global secret_num won = False print "You guessed: ",guess guesses_left = guesses_left - 1 print "Number of remaining guesses is ", guesses_left if int(guess) == secret_num: won = True elif int(guess) > secret_num: result = "It's High Need lower!" else: result = "It's low Need higher!" if won: print "Winner Winner Chicken Dinner" new_game() return elif guesses_left == 0: print " Game Ended,Sorry You Lose. You didn't guess the number in time!" new_game() return else: print result pass # create frame frame = simplegui.create_frame("Game: Guess the number!", 250, 250) frame.set_canvas_background('Blue') # register event handlers for control elements frame.add_button("Range is [0, 100)", range100, 100) frame.add_button("Range is [0, 1000)", range1000, 100) frame.add_input("Enter your guess", input_guess, 100) # call new_game and start frame new_game() frame.start()
true
d40fe25d7ba3e8e78e35176b949e7a7b09febedc
asperaa/back_to_grind
/DP/0_1_Knapsack | DP 10.py
880
4.1875
4
"""We are the captains of our ships and we stay 'till the end. We see our stories through. """ """https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem/0 [Naive Recursion] """ def knapsack(weight, value, capacity): number_of_items = len(weight) return knapsack_helper(number_of_items-1, 0, weight, value, capacity) def knapsack_helper(n, curr_weight, weight, value, capacity): if n == -1 or capacity == 0: return 0 if curr_weight + weight[n] > capacity: return knapsack_helper(n-1, curr_weight, weight, value, capacity) left = value[n] + knapsack_helper(n-1, curr_weight+weight[n], weight, value, capacity) right = knapsack_helper(n-1, curr_weight, weight, value, capacity) return max(left, right) if __name__ == "__main__": w = [100, 20, 200, 5] v = [100, 10, 0, 200] c = 0 print(knapsack(w, v, c))
false
0704dff3bae91c29dadd9867b9fc72259f59c1ce
kivensu/learnpython3
/ListAndOperation/bicycles.py
1,246
4.1875
4
# print list bicycles = ['creak', 'cannondale', 'trip', 'alex'] print(bicycles) # list indexes # print(bicycles[0]) # print(bicycles[1]) # print(bicycles[-1]) print("My first bicycles is " + bicycles[0].title() + " !") # change list element motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) # motorcycles[0] = 'ducadi' # print(motorcycles) # in list tail add element # motorcycles.append('dukadi') # print(motorcycles) # element insert into list # motorcycles.insert(0, 'dukati') # print(motorcycles) # use del delete list element #del motorcycles[0] # print(motorcycles) #del motorcycles[1] # print(motorcycles) # use pop delete list element #poped_motorcycles = motorcycles.pop() # print(motorcycles) # print(poped_motorcycles) #last_owned = motorcycles.pop() # print("The last motorcycle I owned was a " + last_owned.title() + " .") # print(motorcycles) # pop is powerful! #first_owned = motorcycles.pop(0) # print('The first motorcycle I owned was a ' + first_owned.title() + '!') # motorcycles.remove('yamaha') # print(motorcycles) # according to element value to delete too_expensive = 'yamaha' motorcycles.remove(too_expensive) print("\nA" + too_expensive.title() + "is too expensive for me!") # print(motorcycles)
false
7928e5ce41ebcaada9146563521dc9cb61776715
stephra34/MIT-OCW
/turtle_test.py
1,889
4.125
4
#setup import turtle s = turtle.getscreen() t = turtle.Turtle() t.shape("turtle") t.speed(9) #set up screen #turtle.bgcolor("blue") turtle.title("Hunter's Game") # #u = input("Would you like me to draw a shape? Type yes or no: ") #if u == "yes": # t.penup() # t.goto(200,200) # t.pendown() # n=10 # while n <= 100: # t.circle(n) # n = n+10 # t.circle(50) # elif u == "no": # print("Okay") # else: # print("Invalid Reply") #first circles # circles 1 t.penup() t.goto(-200,-200) t.pendown() n=10 while n <= 100: t.circle(n) n = n+10 # circles 1 t.penup() t.goto(-200,200) t.pendown() n=10 while n <= 100: t.circle(n) n = n+10 # circles 1 t.penup() t.goto(200,200) t.pendown() n=10 while n <= 100: t.circle(n) n = n+10 # circles 1 t.penup() t.goto(200,-200) t.pendown() n=10 while n <= 100: t.circle(n) n = n+10 #done() #other commands # t.forward(100) # t.right(90) # t.left(100) # t.backward(100) # turtle.bgcolor(hexcode) # t.home() # t.circle(100) # t.dot(30) # t.shapesize(1,5,10) : stretch lengths, stretch width, outline width # t.pensize(5) # t.fillcolor(hex code) # t.pencolor(hex code) # changes both fill and pen color t.color("green", "red") #t.penup() # t.pendown() # t.undo() # t.clear() # t.reset() #fill an image #t.begin_fill() # t.fd(100) #t.lt(120) # t.fd(100) # t.lt(120) # t.fd(100) # t.end_fill() # turtle shapes # t.shape("turtle") # t.shape("arrow") # t.shape("circle") # Square, Triangle, Classic #clone Turtle # c = t.clone() #for loop Square #for i in range(4): # t.fd(100) # t.rt(90) # u = input("Would you like me to draw a shape? Type yes or no: ") # if u == "yes": # t.circle(50) # u = input("Would you like me to draw a shape? Type yes or no: ") # if u == "yes": # t.circle(50) # elif u == "no": # print("Okay") # else: # print("Invalid Reply")
false
fd00acdfa7e5f6187dcef82ca53e2a34595bb3e9
erinmiller926/adventurelab
/adventure_lab.py
2,337
4.375
4
# Adventure Game Erin_Miller import random print("Last night, you went to sleep in your own home.") print("Now, you wake up in a locked room.") print("Could there be a key hidden somewhere?") print("In the room, you can see:") # The menu Function: def menu(list, question): for item in list: print(1 + list.index(item), item) return int(input(question)) items = ["backpack", "painting", "vase", "bowl", "door"] # This is the list of items in the room: key_location = random.randint(1, 4) # the key is not found. key_found = "No" loop = 1 # Display the menu until the key is found: while loop == 1: choice = menu(items, "What do you want to inspect?") print("") if choice < 5: if choice == key_location: print("You found a small key in the", items[choice-1]) key_found = "Yes" else: print("You found nothing in the", items[choice-1]) elif choice == 5: if key_found == "Yes": loop = 0 print(" You insert the key in the keyhole and turn it.") else: print("The door is locked. You need to find the key.") else: print("Choose a number less than 6.") print("You open the door to a long corridor.") print("You creep down the long corridor and tiptoe down the stairs.") print("The stairs lead to a living room.") print("You see the following:") def menu2(list, question): for item in list: print(1 + list.index(item), item) return int(input(question)) items = ["fireplace", "window", "bookcase", "closet", "door"] key_location = random.randint(1, 4) key_found = "No" loop = 1 while loop == 1: choice = menu(items, "What do you want to inspect?") if choice < 5: if choice == key_location: print("You found a small key in the", items[choice-1]) key_found = "Yes" else: print("You found nothing in the", items[choice-1]) elif choice == 5: if key_found == "Yes": loop = 0 print(" You insert the key in the keyhole and turn it.") else: print("The door is locked. You need to find the key.") else: print("Choose a number less than 6.") print("You exit the house before anyone came home. You breathe a sigh of relief.")
true
bc4cf020e12cef8167f0ce3cad98399b5d7d9f8f
michealwave/trainstation
/lesson.py
1,763
4.4375
4
# Calculation, printing, variables # Printing to the screen # The built in function print(), prints to the screen # it will print both Strings and numbers print("Printing to the screen") print("Bruh") # in quotes are called strings print('bruhg') print(6) #a number print("6") print(6 + 6) #prints 12 print("6" + "6") #string concationation; mashes 2 strings together #print("6" + 6)# error # Performing calculations # addition + # subtraction - # multiplication * # division / # exponents ** # modulo % print(4 - 2) #subtraction print(4 * 2) #multiplication print(4 / 3) # division print(4 ** 3) #exponent print("Modulo test") print(5 % 3) print(10 % 2) print(16 % 3) # Module gives remainders. # python operators follow the same order of operations as math print(4 - 2 * 2) # will give zero print((4 - 2) * 2) #will give 4 #Variables #variables are used to hold data # variables are declared and set to a value (initializing) badluck = 13 #delcared a variables called badluck and initialized it to 13 # i can print the variable using its name print("badluck = " + str(badluck)) #cast it to a string # lets do another one goodluck = "4" #string variables print("goodluck = " + goodluck) #don't have to cast because it is already a string badluck + 5 #pointless print(badluck) badluck = badluck + 5 #badluck is now 18 print(badluck) #you can also save input into variables # using input(), a prompt goes into the () name = input("What is your name?") print("Hello " + name) print(name * 10) name = name + "\n" #escape character (newline) print(name * 10) # lets try some math base = input("Enter the base number: ") exponent = input("Enter the exponent: ") print(int(base) ** int(exponent))
true
840ac0b807f67faca806e65f63fb4512c8ec1f40
niskrev/OOP
/old/NotQuiteABase.py
636
4.28125
4
# from Ch 23 of Data science from scratch class Table: """ mimics table in SQL columns: a list """ def __init__(self, columns): self.columns = columns self.rows = [] def __repr__(self): """ pretty representation of the table, columns then rows :return: """ return str(self.columns) + "\n" + "\n".join(map(str, self.rows)) def insert(self, row_values): if len(row_values) != len(self.columns): raise TypeError("wrong number of elements") row_dict = dict(zip(self.columns, row_values)) self.rows.append(row_dict)
true
36872204f3439dbafd3370cc89e3a26fb245930a
pranavnatarajan/CSE-163-Final-Project
/MatchTree.py
2,753
4.15625
4
""" Alex Eidt- CSE 163 AC Pranav Natarajan - CSE 163 AB CSE 163 A Final Project This class represents a Data Structure used to build up the bracket of the UEFA Champions League to create the bracket graphics. """ import random class MatchTree: """ Data Structure used to represent a full bracket of the UEFA Champions League with every node representing a game. """ def __init__(self, data=None, left=None, right=None): """ Initializes the MatchTree class with a left and right MatchTree Node, and a 'data' field which stores the String representing the teams facing off in that Match. """ self.left = left self.right = right self.data = data def get_winner(self, data): """ Determines the winner of a Match in the MatchTree node based on the coefficient data in 'data'. Parameter data - Pandas DataFrame representing coefficients for every team in the MatchTree bracket. Returns The winning team as a String based on whose coefficient is greater. If both coefficients are exactly the same, this is equivalent to the match going to penalty kicks to be decided. Penalty kicks have little to do with a teams strength (and thus coefficient). Penalty kicks are about who can make the big shots in the big moments and comes down to mostly luck. This behavior is simulated by randomly choosing one team if both coefficients are exactly the same. """ team1, team2 = self.data team1_coefficient = data.loc[team1].squeeze() team2_coefficient = data.loc[team2].squeeze() if team1_coefficient > team2_coefficient: return team1 elif team1_coefficient < team2_coefficient: return team2 return random.choice(self.data) def is_leaf_node(self): """ Returns True if the current MatchTree node is a leaf node (no children). Otherwise returns False. """ return self.left == None and self.right == None def __str__(self): """ Returns A String representation of the data in the MatchTree node. If the data is a tuple, this represents a match and a String of the format "Team A vs. Team B" is returned. If the data is a String, this represents the winner of the bracket and so this value is simply returned. """ if type(self.data) != str: return f'{self.data[0]}\nvs.\n{self.data[1]}' return str(self.data)
true
0e180c7692a5807f278056be53142739700d5fce
anitakumarijena/Python_advantages
/deepak.py
1,275
4.1875
4
graph ={ 'a':['c'], 'b':['d'], 'c':['e'], 'd':['a', 'd'], 'e':['b', 'c'] } # function to find the shortest path def find_shortest_path(graph, start, end, path =[]): path = path + [start] if start == end: return path shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest # Driver function call to print # the shortest path print(find_shortest_path(graph, 'd', 'c')) # Python program to generate the first # path of the graph from the nodes provided graph = { 'a': ['c'], 'b': ['d'], 'c': ['e'], 'd': ['a', 'd'], 'e': ['b', 'c'] } # function to find path def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None # Driver function call to print the path print(find_path(graph, 'd', 'c'))
true
4c786e38d93357f3a768506f39993248e8414b64
Isoxazole/Python_Class
/HW2/hm2_william_morris_ex_1.py
447
4.1875
4
"""Homework2, Exercise 1 William Morris 1/29/2019 This program prints the collatz sequence of the number inputted by the user.""" def collatz(number): if number == 1: print(number) return 1 elif number % 2 == 0: print(number) return collatz(int(number/2)) else: print(number) return collatz(int((number*3) + 1)) print("Please enter an integer:") userInput = int(input()) collatz(userInput)
true
5e4d121ef247320d9f3a90162561d10694c2ab49
Isoxazole/Python_Class
/HW4/hm4_william_morris_ex_1.py
1,461
4.21875
4
""" Homework 4, Exercise 1 William Morris 2/22/19 This program has 3 classes: Rectangle, Circle, and Square. Each class has the functions to get the Area, Diagonal, and perimeter of their respective shape. At the end of this program, the perimeter of a circle with radius the half of the diagonal of a rectangle with length 20 and width 10 is calculated """ import math class Rectangle: def __init__(self, length, width): self.length = length self.width = width def getArea(self): return self.width * self.length def getDiagonal(self): return math.sqrt(self.length ** 2 + self.width **2) def getPerimeter(self): return 2 * self.length + 2 * self.width class Circle: def __init__(self, radius): self.radius = radius def getArea(self): return math.pi * self.radius ** 2 def getDiagonal(self): return self.radius * 2 def getPerimeter(self): return self.radius * 2 * math.pi class Square: def __index__(self, side_length): self.side_length = side_length def getArea(self): return self.side_length **2 def getDiagonal(self): return math.sqrt(self.length ** 2 + self.width ** 2) def getPerimeter(self): return 4 * self.side_length length = 20 width = 10 rectangle = Rectangle(length, width) radius = rectangle.getDiagonal() / 2 circle = Circle(radius) perimeter = circle.getPerimeter() print(perimeter)
true
d57991f5faa7b5b8d3ed8ade332d57c55242bb98
Ottermad/PythonBasics
/times_tables.py
564
4.125
4
# times_tables.py # Function for times tables def times_tables(how_far, num): n = 1 while n <= how_far: print(n, " x ", num, " = ", n*num) n = n + 1 # Get user's name name = input("Welcome to Times Tables. What is your name?\n") print("Hello " + name) # Get timestable and how far do you want to go times_table = int(input("Which times table to you want to know?\n")) how_far = int(input("How far do you want to go?\n")) times_tables(how_far, times_table) print("Goodbye " + name + ". Thank you for playing. \nPress RETURN to exit.")
true
7b6739be5389da8351294fa3b430002989b83b84
avin82/Programming_Data_Structures_and_Algorithms_using_Python
/basics_functions.py
2,225
4.59375
5
def power(x, n): # Function name, arguments/parameters ans = 1 for i in range(0, n): ans = ans * x return ans # Return statement exits and returns a value. # Passing values to functions - When we call a function we have to pass values for the arguments and this is done exactly the same way as assigning a value to a name print(power(3, 5)) # Like an implicit assignment x = 3 and n = 5 # Same rules apply for mutable and immutable values # Immutable values will not be affected at calling point # Mutable values will be affected def update(list, i, v): if i >= 0 and i < len(list): list[i] = v return True else: v = v + 1 return False ns = [3, 11, 12] z = 8 print(update(ns, 2, z)) print(ns) # If we pass through parameter a value which is mutable it can get updated in the function and this is sometimes called a side effect. print(update(ns, 4, z)) print(z) # If we pass through parameter a value which is immutable then the value doesn't change no matter what we do inside the function # Return value may be ignored. If there is no return, function ends when last statement is reached. For example, a function which displays an error or warning message. Such a function just has to display a message and not compute or return anything. # Scope of names # Names within a function have local scope i.e. names within a function are disjoint from names outside a function. def stupid(x): n = 17 return x n = 7 print(stupid(28)) print(n) # A function must be defined before it is invoked def f(x): return g(x + 1) def g(y): return y + 3 print(f(77)) # If we define funtion g after invoking function f we will get an error saying NameError: name 'g' is not defined # A function can call itself - recursion def factorial(n): if n <= 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) # Functions are a good way to organise code in logical chunks # Passing arguments to a function is like assigning values to names # Only mutable values can be updated # Names in functions have local scope # Functions must be defined before use # Recursion - a function can call itself
true
ea834767462615e5a124b4e723e4507dcf393cec
MillaKelhu/tiralabra
/Main/Start/board.py
2,127
4.28125
4
from parameters import delay, error_message import time # User interface for asking for the board size from the user def get_board(): while True: print("Choose the size of the board that you want to play with.") print("A: 3x3 (takes three in a row to win)") print("B: 5x5 (takes four in a row to win)") print("C: 7x7 (takes four in a row to win)") print("D: 10x10 (takes five in a row to win)") print("E: 15x15 (takes five in a row to win)") print("F: 20x20 (takes five in a row to win)") print("----------------") board_letter = input("Your choice: ") print("----------------") time.sleep(delay) try: board_letter = board_letter.capitalize() except: continue board_size = 0 if board_letter == "A": board_size = 3 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "B": board_size = 5 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "C": board_size = 7 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "D": board_size = 10 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "E": board_size = 15 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "F": board_size = 20 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break else: print(error_message) print("----------------") return board_size
true
e16aa01c242c5fc654d01f889c1a3cde6551d618
elvargas/calculateAverage
/calculateAverage.py
2,865
4.4375
4
# File: calculateAverage.py # Assignment 5.1 # Eric Vargas # DESC: This program allows the user to choose from four operations. When an operation is chosen, they're allowed to choose # two numbers which will be used to calculate the result for the chosen operation. Option 5. will ask the user how # many numbers they wish to input. This function will use the number of times to run the program within a loop in # order to calculate the total and average. # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbers def multiply(num1, num2): return num1 * num2 # Function to divide two numbers def divide(num1, num2): return num1 / num2 # Function to find average of numbers def average(): return sum / count # Function allows the user to run the program until they enter a value which ends the loop. def cont(): reply = input("Continue? Y/N ") if reply == "n": return True # Main Section while True: # Prompts user to select an operation print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Average") # Take input from the user select = input("Select an operation: ") # Addition if select == '1': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "+", number_2, "=", add(number_1, number_2)) # Subtraction elif select == '2': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "-", number_2, "=", subtract(number_1, number_2)) # Multiply elif select == '3': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "*", number_2, "=", multiply(number_1, number_2)) # Divide elif select == '4': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "/", number_2, "=", divide(number_1, number_2)) # Average elif select == "5": sum = 0 count = int(input("How many numbers would you like to enter? ")) current_count = 0 while current_count < count: print("Number", current_count) number = float(input("Enter a number: ")) sum = sum + number current_count += 1 # Displays average after last number is entered print("The average was:", sum / count) else: print("Invalid Input") if cont(): break
true
c0e32988331e72474e7b50ea59ac3891627ebd6b
georgeescobra/algorithmPractice
/quickSort.py
1,408
4.25
4
# this version of quicksort will use the last element of the array as a pivot import random import copy def quickSort(array, low, high): if(low < high): partitionIndex = partition(array, low, high) quickSort(array, low, partitionIndex - 1) quickSort(array, partitionIndex + 1, high) # don't necessarily have to return, but doing so for the sake of the unit_test return array def partition(array, low, high): index = low - 1 pivot = array[high] for j in range(low, high): if array[j] <= pivot: index += 1 # this swaps the values of array[i] and array[j] array[index], array[j] = array[j], array[index] array[index + 1], array[high] = array[high], array[index + 1] return index + 1 def main(): unordered = [random.randint(0, 100) for i in range(50)] orig = copy.deepcopy(unordered) quickSort(unordered, 0, len(unordered) - 1) print('Sorting List of 50 Elements in Ascending Order') print('{0:5} ==> {1:5}'.format('Original','Sorted')) for orig, sorted in zip(orig, unordered): print('{0:5} ==> {1:5d}'.format(orig, sorted)) # this is the proper way of having a 'main' function in python3 # this is important for the purpose of code reusability and if this module is imported # this means that gives the ability to conditionally execute the main function is important when writing code that could be possibly used by others if __name__ == "__main__": main()
true
e18f0f34927a7aa2398152077a7f88a811466f11
klandon94/python3_fundamentals
/lambda.py
820
4.1875
4
def square(num): return num*num square(3) #Lambda is used to specify an anonymous (nameless) function, useful where function only needs to be used once and convenient as arguments to functions that require functions as parameters #Lambda can be an element in a list: y = ['test_string', 99, lambda x: x ** 2] print(y[2]) print(y[2](5)) #Lambda can be passed to another function as a callback: def invoker(callback): print(callback(2)) invoker(lambda x: 2*x) invoker(lambda y: 5+y) #Lambda can be stored in a variable: add10 = lambda x: x+10 print(add10(2)) #Returned by another function def incrementor(num): return(lambda x: num + x) incrementor(3) def map(list, function): for i in range(len(list)): list[i]=function(list[i]) return list print (map([1,2,3,4], (lambda num:num*num)))
true
96a5711b2d05f6a28605e5ee5a5f9a2c385bb49f
msemjan/coding_interview_questions
/src/pythagoreanTriplets.py
665
4.28125
4
''' # Find Pythagorean Triplets (Uber) Given a list of numbers, find if there exists a pythagorean triplet in that list. A pythagorean triplet is 3 variables a, b, c where a^2 + b^2 = c^2 Example: > Input: [3, 5, 12, 5, 13] > > Output: True Here, 5^2 + 12^2 = 13^2. ''' def findPythagoreanTriplets(nums): nums_sq = [i for i in (map(lambda x: x**2, nums))] for k in range(0, len(nums_sq) - 2): for l in range(k + 1, len(nums_sq) - 1): if nums_sq[k] + nums_sq[l] in nums_sq: return True return False print(findPythagoreanTriplets([3, 12, 5, 13])) # True print(findPythagoreanTriplets([1, 1, 27])) # False
false
107fa70fc1d1525a6f2b78cd0dfd228f3b8d1ad1
Shantti-Y/Algorithm_Python
/chap02/prac13.py
2,456
4.25
4
# coding: utf-8 # 日付を表す構造体が次のように与えられているとする。 # # typedef struct { # int y; # int m; # int d; # } Date; # # 以下に示す関数を作成せよ。 # ・y年m月d日を表す構造体を返却する関数DateOf # Date DateOf(int, y, int m, int d); # ・日付xのn日後の日付を返す関数After # Date After(Date x, int n); # ・日付xのn日前の日付を返す関数Before # Date Before(Date x, int n); # Date Structure class Date(object): def __init__(self, y, m, d): if not isinstance(y, int): raise TypeError("y must be set to a integer") if not isinstance(m, int): raise TypeError("m must be set to a integer") if not isinstance(d, int): raise TypeError("d must be set to a integer") self.y = y self.m = m self.d = d # Express Date class as "y年m月d日" def DateOf(y, m, d): return "{0}年{1:02d}月{2:02d}日".format(y, m, d) # Return the day when n days after the day x def After(date, n): years = n y = date.y + (int(years / 365)) months = years % 365 m = date.m + (int(months / 31)) days = months % 31 d = date.d + (int(days)) if(d > 31): m += 1 d -= 31 if(m > 12): y += 1 m -= 12 return (DateOf(y, m, d)) # Return the day when n days before the day x def Before(date, n): years = n y = date.y - (int(years / 365)) months = years % 365 m = date.m - (int(months / 31)) days = months % 31 d = date.d - (int(days)) if(d <= 0): m -= 1 d += 31 if(m <= 0): y -= 1 m += 12 return (DateOf(y, m, d)) # Main function dates = [ Date(1992, 8, 25), Date(2017, 4, 12), Date(2001, 1, 1), Date(1999, 12, 31) ] print("--- These date list ---") print("Year Month Day") for elem in dates: print("{0} {1:02d} {2:02d}".format(elem.y, elem.m, elem.d)) print("The following shows dates in a speified format") for elem in dates: print(DateOf(elem.y, elem.m, elem.d)) print("The following shows dates after specified days, please input the days you want") d_after = int(input()) for elem in dates: print(After(elem, d_after)) print("The following shows dates before specified days, please input the days you want") d_before = int(input()) for elem in dates: print(Before(elem, d_before))
false
9aa90a2df1734f12f98a22e925575be47ccbb0f8
Shantti-Y/Algorithm_Python
/chap02/prac04.py
778
4.1875
4
from random import randint as rand #coding: utf-8 # List2-6(参考書参照)は身長を乱数で生成した上で身長の最大値を求めるプログラムであった。 # 身長だけでなく人数も乱数で生成するように書き換えたプログラムを作成せよ。 # 人数は、5以上20以下の乱数とすること。 def maxof(a, n): max = a[0] for i in range(n - 1): if(max < a[i + 1]): max = a[i + 1] return max #Main function print("Compare student's height among the specified number of students") print("and determine the lowest height") print("Number of students :") num = rand(5, 20) ar = [] for i in range(num): ar.append(rand(150, 190)) print("The max of height is {0}cm.".format(maxof(ar, num)))
false
1769e7ee9a9dad0296ef5fd1e189ac4f8ac1e6c6
ayush94/Python-Guide-for-Beginners
/FactorialAlgorithms/factorial.py
1,290
4.1875
4
from functools import reduce ''' Recursively multiply Integer with its previous integer (one less than current number) until the number reaches 0, in which case 1 is returned ''' def recursive_factorial(n): # Base Case: return 1 when n reaches 0 if n == 0 : return 1 # recursive call to function with the integer one less than current integer else: return n * recursive_factorial(n-1) ''' Iterative factorial using lambda and reduce function, from range 1 to number + 1 we multiply all the numbers through reduce. ''' def iterative_factorial(n): factorial = reduce(lambda x,y:x*y,range(1,n+1)) return factorial # Taking number from standard input and casting it into Integer n = int(input("Enter the number: ")) # Taking in Calculation stratergy(recursive/iterative) and removing trailing spaces and changing to lowercase stratergy = input("Enter algorithm type (r for Recursive/i for iterative): ").strip().lower() # Just a check to see if right option was entered if(stratergy != "r" and stratergy !="i"): print("wrong algorithm type opted...exiting") quit() # Factorial by opted stratergy if(stratergy == "r"): factorial = recursive_factorial(n) elif(stratergy == "i"): factorial = iterative_factorial(n) print("Factorial of entered number is: ",str(factorial))
true
e224a34ec37f50014e7dde73993710b560d54606
FilipM13/design_patterns101
/pattern_bridge.py
2,431
4.28125
4
""" Bridge. Structure simplifying code by deviding one object type into 2 hierarchies. It helps solving cartesian product problem. Example: In this case if I want to create one class for every combination of plane and ownership i'd need 16 classes (4 planes x 4 ownerships) Thanks to bridge pattern I only have 8 classes. It works even better if there where more types of planes and ownerships. here: Main hierarchy is Plane (with subclasses), it uses Ownership hierarchy to expand it's possibilities. PS. I don't care that you can't have private bomber. """ from abc import ABC, abstractmethod class Ownership(ABC): @abstractmethod def __init__(self, owner_name): self.owner_name = owner_name self.velocity_multiplier = int() def get_owner_name(self): return self.owner_name class Civil(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 3 class Private(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 7 class Military(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 10 class PublicTransport(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 5 class Plane(ABC): @abstractmethod def __init__(self, ownership: Ownership): self.ownership = ownership self.max_velocity = int() def fly(self): print(f'WHOOOOOOOSH! with the speed of {self.ownership.velocity_multiplier * self.max_velocity} distance units / time unit.') def get_owner_name(self): return self.ownership.get_owner_name() class Jet(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 100 class Airbus(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 50 class Bomber(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 70 class Glider(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 30 '''#uncomment for demonstration civil_bomber = Bomber(Civil('Retired bomber pilot.')) civil_bomber.fly() print(civil_bomber.get_owner_name()) private_jet = Jet(Private('Ash Holle Rich')) private_jet.fly() print(private_jet.get_owner_name()) '''
true
78b5b3a4e8076f804716015f9ea3d8bcb419ea2f
samuelluo/practice
/bst_second_largest/bst_second_largest.py
2,041
4.125
4
""" Given the root to a binary search tree, find the second largest node in the tree. """ # ---------------------------------------- class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def bst_insert(root, val): if root is None: return Node(val) if val < root.val: root.left = bst_insert(root.left, val) elif val > root.val: root.right = bst_insert(root.right, val) return root def bst_second_largest_1(root): largest = second_largest = None queue = [root] while len(queue) != 0: node = queue.pop(0) if largest is None or node.val > largest: second_largest = largest largest = node.val elif second_largest is None or node.val > second_largest: second_largest = node.val if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) return [largest, second_largest] def bst_second_largest_2(root): """ For a BST, in-order traversal will pass through the nodes in increasing order. """ bst_second_largest_2_helper(root, 0) def bst_second_largest_2_helper(root, count): if root is None: return count count = bst_second_largest_2_helper(root.right, count) count += 1 if count == 2: print("Second largest: {}".format(root.val)) count = bst_second_largest_2_helper(root.left, count) return count # ---------------------------------------- root = Node(5) root = bst_insert(root, 3) root = bst_insert(root, 2) root = bst_insert(root, 4) root = bst_insert(root, 7) root = bst_insert(root, 6) root = bst_insert(root, 8) result = bst_second_largest_1(root) print(result) bst_second_largest_2(root) print() root = Node(1) root = bst_insert(root, 2) root = bst_insert(root, 3) root = bst_insert(root, 4) root = bst_insert(root, 5) result = bst_second_largest_1(root) print(result) bst_second_largest_2(root) print()
true