blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
09f793ed475b80515b440709e16eeb92d06be6ac
FGG100y/myleetcode
/hwtt/lpalindrome.py
1,536
4.3125
4
#!/usr/bin/env python # # recursive is_pal to help identify the palindrome # def is_palindrome(s): # def is_pal(s): # if len(s) <= 1: # return True # else: # answer = (s[0]) == s[-1] and is_pal(s[1:-1]) # return answer # # return is_pal(s) # # # def validPalindrome(s, left, right): # while left < right: # if s[left] != s[right]: # return False # left, right = left+1, right-1 # return True # O(n^2)) runtime, O(1) space # def expand_pal_center(s, left, right): def xcenter(s, left, right): while (left >= 0 and right < len(s)) and s[left] == s[right]: left -= 1 right += 1 return right - left - 1 def longest_pal(s): """counts the length of the longest palindrome in a string """ start, end = 0, 0 for i in range(len(s)): # len(s) is odd len1 = xcenter(s, i, i) # len(s) is even len2 = xcenter(s, i, i + 1) len_max = max(len1, len2) if len_max > end - start: # 'distance' between start and center start = i - (len_max - 1) // 2 # 'distance' between end and center end = i + len_max // 2 return len(s[start:end+1]) if __name__ == "__main__": # s = '1234321kka' # print(s) # print('-'*len(s)) # ################### # import sys # print(longest_pal(sys.argv[1])) # ################### s = 'dsuehgfqxzrnkmtmiwytshrerjfybxirufrsobkjeghiunftxyqqcyoreevvktxgvjjqzvcujsynsrlgllebyukyxgugrvkesovfhzdznstvtbblmjcngwsdrmfczsihiblqhkfvhzylwopepfmnixeesvugyifdxvpcknpqunolpgjehoxgylnzoggqpbdkhrngchidhfdktblrifjvppttemmplzrsbjhltvwprhkigkvfkxcxfsgyiyuuziqurgcmddqshenindtrfzlrqpfpekfosmugpwjgydtbwexcwrvdedposftffjrfeojsqpxtoguroojsgrwpyiyhurprcfsgnnykjtrjjzdswfqfwuohpcssgjzyikruvomeggqzyslmfurgnmhyvnksktvdcidvutrrxzixbxiypbvozgnmopfjiljggqrronwkfqvlpdwhtzfpsokfbvftyxdinknsrjlxbzyfmsinegprbnuezqlikgsbbixfdjtsjxojqwxdrvwfflrwjsnpcxqvfpmbidyvvlcnvvvvbglhhmkpuzhosfitgzclicpzsvozsbtvtlmjffqieosliqysgyxmceytmezfbtkcprfomftlkyortyfmykslfdmxzfeetmzxbuvoorpwmkerujcjcuuyvmpqidrrksrtmxhqoqdyvjgvcftbhywmbdfoixecfgorpxoxbqlhbnynwflbodsdqvwwoizdfyczefvonoczocvtbixehcvpmimyxgzddvomklofuthtytqougojqwmxvhzpmvtfsjwrgmxuoeizmnfptssolqbmnrhfjitoqxizflyoddgjlxknumclfmpmrzpomrqqogvmwgclpquhuqbkriyjkwcusetkyxozomcrsuyfmsddwubkiyyjoeqlzjsfnwkhdpgxkeicbivlwbdvcbvdqbyxuwdolmtxzgpogtzctlcjemoxdrbrmmtkuuidtiebckmqluiszgichpmgbsxdiurxdgkvvufyihcjejgwwepswxmjducltnxngtylgiqcvxldeebykysdgwokcupxmjnbiqlzovnocuesodotqivceqhimuhtromxxullejgzhzevzvtdhbfhcwbdivgslkfmudzofbmeeqixuprbsyrelcgvvkbtkgckezrrisnnkwwchcfwlqdoucccqinjplgwlqcylqojstlvdjmcjyqjsqwrvxjmujcuzirinocnnwszxjnyszncytltbusmcsxustpxeuxgmwlixnjnigsxnollfbpqrwohbshbohhnpsvenvgreqfwqypkkibenvgjcwmumwcgehehiyediindvppefciihjkcnzvelorusllpbexivekbflpyqpefpjlumctorwejnefenhrlfugnkywvwuvrdrxsxjksgowxholmpjfyjcksmhwpcpjcodwzmolzgkcjxmiqxdpewlyjilcbbwyxmxhqvsxkepiwdvmfxdceiswscupzpmhvmyciyosxuwnmjxnkdhhnquxsmekmcwgcklxzhhqxkebqcvxpsqzuoxikverbskrwvewomemysgcmrdnzgufysnoxuerrqcufevwwumrvbowvvkjuediygphwgwgdrpbgreytkmgcmzonbyxwkolywjcigvyqqhwsjmtkvvhbtuhctcigvfnkkffvsjrjiumlowlwvsbuopmsfcqrxlpprtmswlkdmkoxewhtfkzzoohdbutqccmzsscjdozeeecdqmugcrqqfjingovwfmvnltdfcmrofcftnoozquguyyzdxqqgwbdpotbquhokorykpurvwbvcwdnmzgimuzjipikdtvhstsgeykmunxvbszjmbgwhiymumfmlhennthtjwspxvqrelkhwqxjrzbkqbobfetlejvdhzpmwreqfhnupgovixdemmngzorgfooiruhjbjmvwgmzrvjgrwouxugmysbrdtdujjeffomribgqkhjohitgonqevcweedmleexqjgtywpwbwmoltxbdkiyvgrykhbesgckhvecyvcjryqbhstwrcloqmoivrmkkimzwbywumxfrzyterxmwpqcullcvebkflwmbbexqifohjrrgsnbsqhlxkwkuhwocmjfrhyfkqpqlbvxokbvbufqffclzlnlszcimzucrsrohldxeohdiktubdrvkzvgvhnrkeenmhcvujlxlpcyhohumnuxmswwfwyhuyqhurvcrvmnkgsyygunrvpbvdmpetuixhwtnswhmgtuunzybkyosezpzttrzcdukbtmxxeschlkjgqgrnhvixqbcusimvwdceedhhbbbrxefvztdcfdtzglhmzfthlmc' print(longest_pal(s))
false
8a9f2bb818704eadf12c8838672b63b6259e1b25
FGG100y/myleetcode
/leetcode/reverse_words.py
828
4.28125
4
#!/usr/bin/env python def rwords(s): """reverse the words in string rtype: None """ s = s[::-1] rws = [w[::-1] for w in s.split()] print("".join(rws)) def rwords_1space(s): """reverse the words in string, seperate by only one space between words """ # replace all non-alphabetic chars with Spaces words_mult_spaces = [char if char.isalpha() else ' ' for char in s] # reverse the whole stings rws_spaces = "".join(words_mult_spaces[::-1]) # strip the Spaces print(" ".join([w[::-1].strip() for w in rws_spaces.split()])) if __name__ == "__main__": s1 = 'asdf dadgdd ADbdgDD' s2 = 'ASD#$%,sfd ,FGE#gggd' print(s1) print('--'*10) rwords(s1) rwords_1space(s1) print() print(s2) print('--'*10) rwords(s2) rwords_1space(s2)
false
62ab746c5779f2deb2c4dd5a813fa34795b09978
jleyva82/Resources
/file_creation.py
762
4.125
4
''' Author = Jesus Leyva Last Update: 01/28/2019 Purpose: Sample of how to use python to create a new file sample resources as described via stack skills python lessons ''' newfile = open("newfile.txt", "w+") #newfile variable is like a class. # "open()" function. #"newfile.txt" is the name of the file #"w+" is the note, that we will write on this file string = "This is the content that will be written to the text file." #create a variable and pass it to the file newfile.write(string) #use ".write()" function to pass on text into the file
true
19c4a3143ccb88b7c58e1bd27f380fd739d5958a
Programmer-X31/PythonProjects
/Project Basic/Datetime_Module.py
742
4.25
4
import datetime as dt birth_day = int(input("Enter your birthdate \n")) birth_month = int(input("Enter your birthmonth \n")) birth_year = int(input("Enter your birthyear \n")) today = dt.date.today() print("Today is " + str(today)) birthday = dt.date(birth_year, birth_month, birth_day) print("Your birthday is on " + str(birthday)) days_since_birth = (today - birthday).days print("You have lived " + str(days_since_birth) + " days") days_since_birth_in_years = int((days_since_birth / 365)) print("Your age is " + str(days_since_birth_in_years)) # weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] # weekday = weekdays[today.weekday()] # print('Today is a '+ str(weekday))
false
8633f7141389e8fbfabff287cf97602ff3a65533
BoHyeonPark/BI_test
/bioinformatics_1_4.py
391
4.1875
4
#!/usr/bin/python num1 = raw_input("Enter a integer: ") num2 = raw_input("Enter another: ") try: num1 = int(num1) num2 = int(num2) except: print "Enter only number!" else: if num1 > num2: print "%d is greater than %d" % (num1, num2) elif num1 < num2: print "%d is less than %d" % (num1, num2) else: print "%d is equal to %d" % (num1, num2)
true
93886ea9807f467a784600cbf3be7d2e60522a11
klprabu/myprojects
/Python/HackerRank/DesignerMat.py
1,581
4.21875
4
# Set the design as per the input #Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: #Mat size must be X. ( is an odd natural number, and is times .) #The design should have 'WELCOME' written in the center. #The design pattern should only use |, . and - characters. # Enter your code here. Read input from STDIN. Print output to STDOUT rows, cols = input().split() # print(rows) # print(cols) rows = int(rows) cols = int(cols) hyp = '-' pip = '.|.' print_hyp = 0 odd_nos = [] v_odd_nos = [] if rows % 2 != 0 and cols % 3 == 0 and 5 < rows < 101 and 15 < cols < 303: for j in range(cols): if j % 2 != 0: odd_nos.append(j) if j * 3 >= cols: break # print(odd_nos) r_odd_nos = odd_nos[:len(odd_nos) - 1].copy() r_odd_nos.reverse() v_odd_nos = odd_nos + r_odd_nos # print(v_odd_nos) itr = 0 check = 0 for i in range(1, rows + 1): # v = i * 3 itr = i - 1 # print(itr) n = v_odd_nos[itr] * 3 print_hyp = int((cols - n) / 2) check = int(len(v_odd_nos) / 2) + 1 # print(v_odd_nos[check]) if i < check: print(hyp * print_hyp + pip * v_odd_nos[itr] + hyp * print_hyp) elif i == check: print(hyp * int((cols - 7) / 2) + 'WELCOME' + hyp * int((cols - 7) / 2)) elif i > check: print(hyp * abs(print_hyp) + pip * v_odd_nos[itr] + hyp * abs(print_hyp))
true
cb3f2a2ba89d10eeb06bc7bdb3a1e205ade8ddeb
kiennd13/NguyenDucKien-Fundamentals-C4E30
/Session 5/function_7,8.py
352
4.125
4
def remove_dollar_sign(s): return s.replace("$","") m = str(input("Nhập chuỗi : ")) t=remove_dollar_sign(m) print(t) string_with_no_dollars = remove_dollar_sign("$80% percent of $life is to show $up") if string_with_no_dollars == "80% percent of life is to show up": print("Your function is correct") else: print("Oops, there's a bug")
true
825f18874a543fe5162d409085f17def0aed29e9
kiennd13/NguyenDucKien-Fundamentals-C4E30
/Session 5/function_5,6.py
481
4.21875
4
from turtle import * def draw_star(x,y,length): up() setposition(x,y) down() for _ in range(5): left(144) forward(length) mainloop() length = int(input("Length = ")) x = int(input("Position 1: ")) y = int(input("Position 2: ")) draw_star(x,y,length) speed(0.3) color('blue') for i in range(100): import random x = random.randint(-300, 300) y = random.randint(-300, 300) length = random.randint(3, 10) draw_star(x, y, length)
true
e2d0c4546380e8e7e6a2268b69893dc78732266e
rsdarji/CEGEP-sem-2-Algorithm
/examples.py
2,490
4.28125
4
# ====================================================================================================================== # Printing # ====================================================================================================================== """ Basic user output in Python is done with 'print'. Although we did not see all what print can do. """ # print can print anything, int, string, list, etc. # print can be given multiple things to print # print can be given a separator with print(..., sep=...) # print can be given an end character with print(..., end=...) # ====================================================================================================================== # Input # ====================================================================================================================== """ Basic user input in Python is done with 'input' """ # The function input will return the string the user input # The function 'input' can also take a string to explain to the user what they should input # To input multiple values, we usually use a while loop # ====================================================================================================================== # String formatting # ====================================================================================================================== # lower: make lowercase # upper: make uppercase # capitalise: make the first letter uppercase # title: make the first letter of each word uppercase # format: insert values into a string # split: split a string into a list of string at a character # ====================================================================================================================== # Files # ====================================================================================================================== """ Python uses a with statement to open a file This allows Python to know at what point you no longer need the file and can close it """ # == READ == # You can open a file in read-only mode 'r', this is the default mode # You can read a single line with 'readline' # Or read all lines with 'readlines' # We usually prefer reading lines with a loop. # == WRITE == # You can open a file in write-only mode 'w', this will overwrite the file if it existed # You can open the file in append mode 'a', this will not overwrite the file an write anything at the end # You can open the file in read-and-write mode
true
3f30f28b8f3a8db8e53cab846a248d4b8c8f11ff
jeffrlynn/Codecademy-Python
/removeVowels.py
250
4.3125
4
#Remove all vowels from a string def anti_vowel(text): phrase = "" for letter in text: for vowel in "aeiouAEIOU": if letter == vowel: letter = "" else: letter = letter phrase = phrase + letter return phrase
true
f37185b847d2d868082ab9db5cca9a318f0632bb
GeertenRijsdijk/Theorie
/main.py
2,649
4.15625
4
''' main.py Authors: - Wisse Bemelman - Michael de Jong - Geerten Rijsdijk This file implements the front end for the algorithms and visualisation. usage: python main.py <datafile> <amount of houses> <algorithm> example: python main.py ./data/wijk_2.csv 60 r The algorithm choices are located in the readme. ''' from code.visualize import * from code.classes.grid_class import * from code.algorithms.random import * from code.algorithms.greedy import * from code.algorithms.hillclimber import * from code.algorithms.simann import * import sys import matplotlib.pyplot as plt # Exit if incorrect number of arguments if len(sys.argv) != 4: print("Arguments need to be a path to a file, the amount " "of houses and the algorithm") sys.exit() # Exit if not correct algorithm entered if sys.argv[3] not in ['r', 'g', 'h','s']: print("Please enter valid algorithm: Random = r, Greedy = g, " "Hillclimb = h, Simann = s") sys.exit() # Let user enter parameters for simulated annealing if sys.argv[3] == 's': temperature = input("Please enter temperature (for standard testing " "values: 10000000, press enter): ") cooling_rate = input("Please enter cooling rate (for standard testing " "values: 0.0001, press enter): ") stopT = input("Please enter stop temperature (for standard testing " "values: 0.01, press enter): ") swap_prob = input("Please enter swap probability (for standard testing " "values: 0.3, press enter): ") # Insert standard testing values if user presses enter, else str to int if temperature == '': temperature = 10000000 else: temperature = float(temperature) if cooling_rate == '': cooling_rate = 0.0001 else: cooling_rate = float(cooling_rate) if stopT == '': stopT = 0.01 else: stopT = float(stopT) if swap_prob == '': swap_prob = 0.3 else: swap_prob = float(swap_prob) # Calculate the required amount of the different houses filename = sys.argv[1] c = int(sys.argv[2]) # Exit if non valid number of houses is entered if c <= 0: print("Please enter non-negative number of houses") sys.exit # Run correct algorithm grid = Grid(filename, c) if sys.argv[3] == 'r': random(grid) if sys.argv[3] == 'g': greedy(grid) if sys.argv[3] == 'h': price_list = hillclimb(grid) if sys.argv[3] == 's': price_list = simann(grid,temperature, cooling_rate, stopT, swap_prob) print(grid.calculate_price()) if sys.argv[3] in ['h', 's']: plt.plot(price_list) plt.ylabel('iteration') plt.ylabel('value') plt.show() visualize_map(grid)
true
9c13585b3241bdd8f0d5b538afee7044567cfe32
TanyaMozoleva/python_practice
/Lectures/Lec11/p15.py
736
4.1875
4
''' Using and if ... elif statement complete the compare_nums2() function which is passed two integers and returns a string. The function compares the first number to the second number and returns one of the following three strings (i.e., the string which is applicable): "equal to" OR "less than" OR "greater than" ''' import random def compare_nums2(num1, num2): message = '' if num1 == num2: message = 'equal to ' elif num1 > num2: message = 'greater than ' else: message = 'less than ' return message def main(): num1 = random.randrange(1, 100) num2 = random.randrange(1, 100) comparison = compare_nums2(num1, num2) print(num1, ' is ', comparison, num2, sep='') main()
true
759f3b296db18e6557f46ffa8bd99d48a713c247
TanyaMozoleva/python_practice
/Lectures/Lec12/p13.py
1,040
4.15625
4
''' A perfect number is an integer that is equal to the sum of its divisors (including 1, excluding the number itself), e.g., the sum of the divisors of 28 is 28 (1 + 2 + 4 + 7 + 14). Complete the check_perfection() function which checks for perfection and prints either '#is a perfect number' or '#is NOT a perfect number'. ''' def get_sum_of_divisors(number): divisor = 1 sum_of_divisors = 0 while divisor <= number // 2: if number % divisor == 0: sum_of_divisors = sum_of_divisors + divisor divisor = divisor + 1 return sum_of_divisors def check_perfection(number): message_is = ' is a perfect number' message_is_not = ' is NOT a perfect number' sum_of_divisors = get_sum_of_divisors(number) if number == sum_of_divisors: print(number, message_is, sep='') elif number != sum_of_divisors: print(number, message_is_not, sep='') def main(): check_perfection(28) check_perfection(54) check_perfection(496) check_perfection(100) main()
true
9f3dda1df5bfb23fbc90698d6db2e62c37d0c37c
TanyaMozoleva/python_practice
/Weeks/week2/w2t2.py
506
4.625
5
''' Complete the programm that prompts the user to enter a floatibg point value and an unteger value and calculates and displays the value obtained when the floating point value is raised to the power of the integer value. The result will be rounded to the nearist 3 decimal places. ''' number = float(input('Enter a floating point number: ')) power = int(input('Enter an integer: ')) obtained_value = round(number ** power, 3) print(number, ' to the power of ', power, ' is ', obtained_value, sep = '')
true
713b95248bac2b24e652bd1437ccc055598783c5
TanyaMozoleva/python_practice
/Lectures/Lec4/p24.py
315
4.28125
4
''' Complete the following program so that it prints the name between two rows of stars. The output has three spaces on each side of the name ''' name = 'Philomena Evangeline' extras = 3 symbol = '*' lots_of_symbols = symbol * 26 print(lots_of_symbols) print(' ' * extras, name, ' ' * extras, sep = '') print(lots_of_symbols)
true
06d0a2da145a8c679ffc0c12bf9730233f8ec553
TanyaMozoleva/python_practice
/Weeks/week2/w2t5.py
387
4.28125
4
''' Write a program that prompts the user to enter a word. In then prints a new word where the first and last characters of the word entered by the user are swapped. ''' word = input('Enter a word: ') first_character = word[0] last_character = word[-1] middle_slice = word[1:-1] new_word = last_character + middle_slice + first_character print('The new word is ', new_word, sep = '')
true
00bdd1f1d9b9f76752edd0f65ea483a6fa039089
cvhs-ap-2018/python-practice-exam-Alvarezchris23
/graphics.py
813
4.53125
5
""" 1. Write the lines of code that would import and create a turtle named 'Pong'. """ import turtle Pong = turtle.Turtle('turtle') Pong.pd() """ 2. Draw a square with Pong of length 100 """ import turtle Pong = turtle.Turtle('turtle') for i in range(4): Pong.fd(100) Pong.rt(90) """ 3. Write a function that will allow the user to input the length of a square and then draw a square of that length. """ import turtle Pong = turtle.Turtle('turtle') def square(s): for i in range(4): Pong.fd(s) Pong.rt(90) square() #enter side length in parentheses after square """ 4. Draw a series of squares with different sizes that share the same corner. """ """ 5. Repeat the question above but change the color each time it draws a square. """
true
e229e096226f4e2cca03bc1250f079d122406250
ZR-Huang/AlgorithmsPractices
/Leetcode/Basic/Dynamic_Programming/53_Maximum_Subarray.py
662
4.15625
4
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. ''' class Solution: def maxSubArray(self, nums) -> int: # greedy curr_sum = max_sum = nums[0] for i in range(1, len(nums)): curr_sum = max(nums[i], nums[i]+curr_sum) max_sum = max(curr_sum, max_sum) return max_sum
true
30fd79047b91178674d44118792ab65aedc59a66
ZR-Huang/AlgorithmsPractices
/Divide and Conquer Algorithm/Week1_MergeSort.py
1,062
4.125
4
""" @function: the implement of Merge Sort """ def Merge(A,B): i = 0 j = 0 result = [] for k in range(len(A)+len(B)): if i < len(A) and j < len(B): if A[i] < B[j]: result.append(A[i]) i += 1 elif B[j] < A[i]: result.append(B[j]) j += 1 else: result.append(A[i]) result.append(B[j]) i += 1 j += 1 elif i == len(A): result.append(B[j]) j += 1 elif j == len(B): result.append(A[i]) i += 1 return result def Sort(array): if len(array) == 1: return array left = array[:int(len(array)/2)] right = array[int(len(array)/2):] result_left = Sort(left) result_right = Sort(right) result = Merge(result_left,result_right) return result array = [5,4,1,8,7,2,6,3] print("test1:",Sort(array)) array = [5,4,1,9,8,7,2,6,3] print("test2:",Sort(array))
false
460e74a392f8586e88a120885f7cfe6c1400c525
ZR-Huang/AlgorithmsPractices
/Leetcode/Intermediate/Array_and_string/73_Set_Matrix_Zeroes.py
2,957
4.3125
4
''' Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [   [1,1,1],   [1,0,1],   [1,1,1] ] Output: [   [1,0,1],   [0,0,0],   [1,0,1] ] Example 2: Input: [   [0,1,2,0],   [3,4,5,2],   [1,3,1,5] ] Output: [   [0,0,0,0],   [0,4,5,0],   [0,3,1,0] ] Follow up: - A straight forward solution using O(mn) space is probably a bad idea. - A simple improvement uses O(m + n) space, but still not the best solution. - Could you devise a constant space solution? ''' class Solution: def setZeroes(self, matrix) -> None: """ Do not return anything, modify matrix in-place instead. """ """ Idea (direactly with extra spaces): 1. scan the matrix and store indexes of zeroes. 2. set rows and columns zeroes. """ m = len(matrix) n = len(matrix[0]) if n == 0 or m == 0: return indexes = [] for i, row in enumerate(matrix): for j, element in enumerate(row): if element == 0: indexes.append((i, j)) # print(indexes) for i, j in indexes: matrix[i] = [0] * n for _i in range(m): matrix[_i][j] = 0 def setZeroes_v2(self, matrix) -> None: """ Idea (a constant space solution): 1. Scan the matrix. 2. If meet a zero, label the head elements of this row and this column. For example, if matrix[i][j] = 0, set matrix[i][0] and matrix[0][j] INF. 3. Scan the matrix again. Set rows and columns which have the label to zeroes. Bugs: The problem does not give the range of elements of the matrix, so the solution easily gets the Wrong Answer if the label isn't set appropriately. """ m = len(matrix) n = len(matrix[0]) if n == 0 or m == 0: return col_0 = False for i in range(m): if matrix[i][0] == 0: col_0 = True for i in range(m): for j in range(1, n): if matrix[i][j] == 0: matrix[i][0] = 0 matrix[0][j] = 0 # scan the matrix to find out LABEL, # and set rows and columns to zeroes for i in range(1, m): for j in range(1, n): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 # See if the first row needs to be set to zero if matrix[0][0] == 0: matrix[0] = [0] * n # See if the first column needs to be set to zero if col_0: for i in range(m): matrix[i][0] = 0 matrix = [[8,3,6,9,7,8,0,6],[0,3,7,0,0,4,3,8],[5,3,6,7,1,6,2,6],[8,7,2,5,0,6,4,0],[0,2,9,9,3,9,7,3]] Solution().setZeroes_v2(matrix) print(matrix)
true
17e86d07b7f438a8365650253f65130b0eebde87
ZR-Huang/AlgorithmsPractices
/Leetcode/Basic/Math/326_Power_of_Three.py
1,530
4.46875
4
''' Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Follow up: Could you do it without using any loop / recursion? ''' class Solution: def isPowerOfThree(self, n: int) -> bool: # 84ms if n <= 0: return False while n != 1: if n % 3 == 0: n = n // 3 else: return False return True def isPowerOfThree_v2(self, n: int) -> bool: # 108ms if n <= 0: return False import math exponent = math.log(n, 3) # python calculate as log2(n) / log2(3) # the result may have the error, such as math.log(243, 3) is 4.999999 # validate if the exponent is an integer. epsilon = 0.0000001 return (exponent + epsilon) % 1 <= 2 * epsilon def isPowerOfThree_v3(self, n: int) -> bool: # 72ms # limitation of the integer # get the maximum value of the integer max_int = 2**31 - 1 # get the maximum value of the n # 3**(math.floor(math.log(max_int, 3))) = 3**math.floor(19.56) = 3**19 = 1162261467 max_n = 1162261467 # divisors of max_n are only 3**0, 3**1, ..., 3**19, because three is prime. # Hence, if 3**19 % n == 0, n is the power of three. return n > 0 and max_n % n == 0
true
4b53b20061ab23c8e8f84ef083f0980dd482675f
ZR-Huang/AlgorithmsPractices
/Leetcode/Intermediate/Backtracking/78_Subsets.py
611
4.46875
4
class Solution: ''' Computing the subset of the array can be considered as the selection of every element of the array. Thus, the DFS algorithm is used to search all the possible combinations. This method also called backtrack algorithm. ''' def subsets(self, nums): result = [] n = len(nums) def select_elem(i, n, selected_list): result.append(selected_list) for j in range(i, n): select_elem(j+1, n, selected_list+[nums[j]]) select_elem(0, n, []) return result print(Solution().subsets([1,2,3]))
true
83cc10463f51848197a05dadf1be6a16bc96de01
dziarkachqa/example_pytest
/src/src.py
734
4.125
4
def join_list(some_list: list) -> str: """Function joins list elements and strings""" if not isinstance(some_list, list): return "I need list!" return "".join([str(el) for el in some_list]) def split_list(some_list: list, sep=None) -> tuple: """Function for splitting list by separator""" if not isinstance(some_list, list): return "I need list!" if sep is None or sep not in some_list: return tuple(some_list) return (some_list[:some_list.index(sep)], some_list[some_list.index(sep)+1:]) def common_elements(lst1: list, lst2: list) -> list: """Function for finding common elements""" temp = set(lst2) lst3 = [value for value in lst1 if value in temp] return lst3
true
7d1ed39f4b34b009182e04e7a4b6f62b4329357a
JeffreyAsuncion/SQLite_Databases_with_Python
/db001.py
593
4.21875
4
import sqlite3 # conn = sqlite.connect(':memory:') # to create a database in memory that disappear after done conn = sqlite3.connect('customer.db') # before create table need a cursor # Create a cursor cursor = conn.cursor() # if we recreate a table we get an error # # Create a table # cursor.execute("""CREATE TABLE customers ( # first_name TEXT, # last_name TEXT, # email TEXT # )""") # Datatypes: # NULL # INTEGER # REAL # TEXT # BLOB (mp3,etc) # Commit our command conn.commit() # Close our connection conn.close()
true
03de7319b70da0d4bbbabcd4df51886b767857f9
geniousisme/CodingInterview
/leetCode/Python/281-zigzagIterator.py
946
4.21875
4
# Given two 1d vectors, # implement an iterator to return their elements alternately. # For example, given two 1d vectors: # v1 = [1, 2] # v2 = [3, 4, 5, 6] # By calling next repeatedly until hasNext returns false, # the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. # Follow up: What if you are given k 1d vectors? # How well can your code be extended to such cases? import collections class ZigzagIterator(object): ''' Time: O(n) Space: O(n) ''' def __init__(self, v1, v2): self.dq = collections.deque([(len(v), iter(v)) for v in (v1, v2) if v]) def next(self): length, iterator = self.dq.popleft() if length > 1: self.dq.append((length - 1, iterator)) return next(iterator) def hasNext(self): return bool(self.dq) if __name__ == "__main__": zi = ZigzagIterator([1, 2], [3, 4, 5, 6]) while zi.hasNext(): print zi.next()
true
b67be5db60f242b0a586cac963668509304f2521
geniousisme/CodingInterview
/leetCode/Python/147-insertionSortList.py
1,567
4.125
4
# Time: O(n ^ 2) # Space: O(1) # # Sort a linked list using insertion sort. # # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def insertionSortList(self, head): if head is None or self.is_sorted(head): return head dummy = ListNode(float("-inf")) dummy.next = head curr = dummy while curr.next: if curr.val > curr.next.val: prev = dummy while prev.next.val < curr.next.val: prev = prev.next tmp = curr.next curr.next = tmp.next tmp.next = prev.next prev.next = tmp else: curr = curr.next return dummy.next def is_sorted(self, head): while head.next: if head.val > head.next.val: return False head = head.next return True def print_llst(self, head): llst = "" while head: llst += str(head.val) if head.next: llst += '->' head = head.next print llst if __name__ == '__main__': s = Solution() test = ListNode(1) test.next = ListNode(4) test.next.next = ListNode(0) test.next.next.next = ListNode(3) test.next.next.next.next = ListNode(2) test.next.next.next.next.next = ListNode(5) s.print_llst(s.insertionSortList(test))
false
f6225982288731faa7c4d02b279789b75796ff39
jdmorrone01/Triangle567
/TestTriangle.py
2,140
4.125
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testRightTriangleA(self): self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle') def testRightTriangleC(self): self.assertEqual(classifyTriangle(10,6,8),'Right','10,6,8 is a Right triangle') def testEquilateralTriangleA(self): self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral') def testEquilateralTriangleB(self): self.assertEqual(classifyTriangle(2,2,2),'Equilateral','2,2,2 should be equilateral') def testEquilateralTriangleC(self): self.assertEqual(classifyTriangle(50,50,50),'Equilateral','50,50,50 should be equilateral') def testScaleneTriangleA(self): self.assertEqual(classifyTriangle(10,1,12),'Scalene','10,1,12 should be scalene') def testScaleneTriangleB(self): self.assertEqual(classifyTriangle(8,4,10),'Scalene','8,4,10 should be scalene') def testOutofBoundsTriangleA(self): self.assertEqual(classifyTriangle(201,2,1),'InvalidInput', '201,2,1 is not a valid imput') def testOutofBoundsTriangleB(self): self.assertEqual(classifyTriangle(-1,2,1),'InvalidInput','-1,2,1 is not a valid imput') def testIsocelesTriangleA(self): self.assertEqual(classifyTriangle(2,2,1),'Isoceles','2,2,1 should be isoceles') def testIsocelesTriangleB(self): self.assertEqual(classifyTriangle(50,50,100),'Isoceles','50,50,100 should be isoceles') if __name__ == '__main__': print('Running unit tests') unittest.main()
true
8f425d726835670b203d4f636d41f7157c7592d2
biglocalnews/covid-world-scraper
/covid_world_scraper/utils.py
529
4.1875
4
from datetime import datetime def relative_year(month, day): """Given a month and day, determine the correct year on New Year's Day """ t = today() # If incoming date is Jan 1st if month == 1 and day == 1: # and current UTC is Dec 31st, # then increment the current year if t.month == 12 and t.day == 31: return t.year + 1 return t.year def today(): return datetime.utcnow() def utc_now_timestamp(): return datetime.utcnow().strftime("%Y%m%dT%H%MZ")
false
c46fbcd48b0dae0d7a5c8e6b1b852c7baeb91fb4
mz09code/brutal-algorithm-class
/2019 首期/Chapter 1/4/stack.py
690
4.21875
4
class Stack: # 抽象数据结构 def __init__(self): self.data = [] def length(self): return len(self.data) def peek(self): # 窥, 返回顶上的数据 return self.data[-1] # self.data[len(self.data)-1] def push(self, ele): self.data.append(ele) def pop(self): # return self.data.pop(-1) ele = self.peek() self.data = self.data[:-1] return ele s = Stack() s.push(1) assert s.peek() == 1 s.push(2) assert s.length() == 2 s.push(3) print(s.data) assert s.pop() == 3 assert s.length() == 2 print(s.data) assert s.pop() == 2 print(s.data) assert s.pop() == 1 print(s.data) assert s.length() == 0
false
105907e46fd1d42a49ce22765393ef5a88b39102
anshul-musing/basic_cs_algorithms
/test_heap.py
935
4.21875
4
from src.heap import MaxHeap def testHeap(): ''' Here we test algorithms for a max heap The heap class takes a balanced binary tree as an input and converts it into a max heap We test a) building a max heap b) heapify operation Each node of the max heap is an object of the Node class, which has a value and the left and the right links ''' print('Initialize a max heap') h = MaxHeap() print('Create a binary tree first') elem = [10,7,14,3,8,12,18,20,19,1,2] h.createBalancedTree(elem) print('Tree level-order walk') h.levelorderWalk() print('Convert tree to a max heap') h.buildMaxHeap(h.root) print('Tree level-order walk') h.levelorderWalk() print('Current tree height: ' + str(h.treeHeight())) print('No. of nodes in the tree: ' + str(h.nodecount())) if __name__ == '__main__': print(testHeap.__doc__) testHeap()
true
cc3a38c69c3105c5b40b7d2f968013f695454f8a
anshul-musing/basic_cs_algorithms
/test_graph.py
1,284
4.34375
4
from src.graph import Graph def testGraph(): ''' Here we test algorithms for graphs We test a) breadth first search b) depth first search c) minimum spanning tree using Prim's algorithm d) shortest distance using Dijkstra's algorithm Graph's vertices are specified as a list Graph's edges are represented as a dictionary ''' print('Create a default graph') g = Graph() print(g.E) print('') print('Changing the default graph to the following') g.V = [str(i) for i in range(9)] g.E = { '0': {'1':4, '7':8}, '1': {'0':4, '2':8, '7':11}, '2': {'1':8, '3':7, '5':4, '8':2}, '3': {'2':7, '4':9, '5':14}, '4': {'3':9, '5':10}, '5': {'2':4, '3':14, '4':10, '6':2}, '6': {'5':2, '7':1, '8':6}, '7': {'0':8, '1':11, '6':1, '8':7}, '8': {'2':2, '6':6, '7':7} } print(g.E) strt = '0' print('\nBFS with starting node ' + strt) g.bfs(strt) print('\nDFS with starting node ' + strt) g.dfs(strt) print('\nPrim-MST with starting node '+ strt) g.prim_mst(strt) print('\nDijkstra with starting node ' + strt) g.dijkstra(strt) if __name__ == '__main__': print(testGraph.__doc__) testGraph()
true
0ffd265548c8bda235ed4ad28c81fef877dc48aa
ironxmind/SkillBox
/3.6 homework/task5.py
1,041
4.21875
4
print('Задача 5. Вход в систему') # Что нужно сделать # Исправьте программу и допишите необходимые команды для получения нужного результата. # Будьте внимательны при исправлении и помните о правилах названия переменных. # Программа: first_name = input('Введите имя пользователя: ') greeting = 'Утро доброе' print(greeting, first_name) intro = 'К сожалению, у Вас нет доступа к системе.' info = 'Пожалуйста, обратитесь к системному администратору.' print(intro, '\n' + info) # Ожидаемый результат: # Введите имя пользователя: Роман # Привет, Роман # К сожалению, у Вас нет доступа к системе. # Пожалуйста, обратитесь к системному администратору.
false
11e7d3d78785ed89f7734d05608121ef8d58dd8e
betteridiot/biocomp_bootcamp
/basic_script.py
413
4.75
5
"""Write a Python 'Hello, World' program. A 'Hello, World' program is a program that prints out 'Hello, World' on the screen. In addition to doing 'Hello, World', I want you to go a little further. 1. Print out 'Hello, World' 1. Save your partner's name as a variable 2. Print out 'Hello, <your partner's name>' by passing it the variable """ print('Hello, World') partner = 'P. Diddy' print('Hello, ' + partner)
true
55ae3800c673d4a662d51d3e272a25a8186458d1
acm-kccitm/Python
/Class/Person.py
2,885
4.3125
4
class Person: ''' The class Person describes a person''' count = 0 def __init__(self, name, DOB, Address): ''' Objective: To initialize object of class Person Input Parameters: self (implicit parameter) - object of type Person name - string DOB - string (Date of Birth) address - string Return Value: None ''' self.name = name self.DOB = DOB self.Address = Address Person.count += 1 def getName(self): ''' Objective: To retrieve name of the person Input Parameter: self (implicit parameter) - object of type Person Return Value: name - string ''' return self.name def getDOB(self): ''' Objective: To retrieve the date of birth of a person Input Parameter: self (implicit parameter) - object of type Person Return Value: DOB - string ''' return self.DOB def getAddress(self): ''' Objective: To retrieve address of person Input Parameter: self (implicit parameter) - object of type Person Return Value: address - string ''' return self.Address def getCount(self): ''' Objective: To get count of objects of type Person Input Parameter: self (implicit parameter) - object of type Person Return Value: count: numeric ''' return Person.count def setName(self, name): ''' Objective: To update name of person Input Parameter: self (implicit parameter) - object of type Person name – string value Return Value: None ''' self.name = name def setDOB(self, DOB): ''' Objective: To update DOB of person Input Parameter: self (implicit parameter) - object of type Person DOB – string value Return Value: None ''' self.DOB = DOB def setAddress(self, Address): ''' Objective: To update address of person Input Parameter: self (implicit parameter) - object of type Person address – string value Return Value: None ''' self.Address = Address def __str__(self): ''' Objective: To return string representation of object of type Person Input Parameter: self (implicit parameter)- object of type Person Return Value: string ''' return 'Name:'+self.name+'\nDOB:'+str(self.DOB)\ + '\nAddress:'+self.address def __del__(self): ''' Objective: To be invoked on deletion of an instance of the class Person Input Parameter: self (implicit parameter) – object of type Person Return Value: None ''' print('Deleted !!') Person.count -= 1
true
b3430f9aa7d8b084ea5f8f44a1af6723f12e98a4
jsore/notes
/v2/python-crash-course/python_work/loops.py
818
4.5625
5
items = ['val1', 'val2', 'val3'] # basic syntax for item in items: print(item) # don't forget Python loves whitespace print('this is outside the loop') # ranges for value in range(1, 5): print(value) # 1 # 2 # 3 # 4 # list from ranges numbers = list(range(1, 6)) # [1, 2, 3, 4, 5] # set step size for skipping numbers in range even_numbers = list(range(2, 11)) # 2, 3, ... 10 even_numbers = list(range(2, 11, 2)) # adds 2: [2, 4, 6, 8, 10] # squaring integers in a range squares = [] for value in range(1, 11): # square ints 1-10 # square = value ** 2 # two asterisks represent exponents # squares.append(square) # or... squares.append(value**2) # ...or, just: squares = [value**2 for value in range(1, 11)] print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
true
e3c3ff38d924f380917f5d5b48a755d1e708a06e
Sravya12379/walk2zero
/googlemaps.py
2,089
4.3125
4
import requests def input_locations(): """ This allows the user to input the locations of the origin and destination, assigns them to variables and returns these variables. :return: inputted origins and destination """ origin = input("Your location: ") destination = input("Your destination: ") return origin, destination def get_distance(origin, destination): """ This function takes the inputted origin and destination, then uses the google maps API to calculate the distances and duration (take out if not needed) of the route. These are outputted for each mode of transport so they are all available. :param origin: inputted origin :type origin: string :param destination: inputted destination :type destination: string :return: origin address, destination address and distances & durations of route for each mode of transport. """ api_key = "Your API key here" modes = ["driving", "walking", "bicycling", "transit"] distances = dict() durations = dict() for mode in modes: uri = f'https://maps.googleapis.com/maps/api/distancematrix/json?' \ f'origins={origin}&' \ f'destinations={destination}&' \ f'mode={mode}&' \ f'key={api_key}&language=en-GB' response = requests.get(uri) output = response.json() origin_address = output['origin_addresses'] destination_address = output['destination_addresses'] for obj in output['rows']: for data in obj['elements']: distance = data['distance']['text'] duration = data['duration']['text'] distances[mode] = distance durations[mode] = duration return origin_address, destination_address, distances, durations origin, destination = input_locations() origin_address, destination_address, distances, durations = get_distance(origin, destination) print(f'origin address: {origin_address}') print(f'destination address: {destination_address}') print(distances) print(durations)
true
382c5bc9518497e6d3d972912c33c7cb93ef75d8
HarrisonMS/JsChallenges
/Python/hackerrank/staircase.py
301
4.125
4
#!/bin/python3 import math import os import random import re import sys # Complete the staircase function below. def staircase(n): spaces = n-1 stairs = 1 while n: print(" "*spaces + '#'*stairs) n -= 1 spaces -= 1 stairs += 1 print(staircase(6))
true
7271c2f2f3f3c02b743f365b3d203c9b2fc0085a
shinjita-das/python-learning
/prac.py
848
4.125
4
def calc(input1, input2, operator): value = None # Start here # if else # math operators # how to compare strings in python if operator == "+": value = input1 + input2 elif operator == "-": value = input1 - input2 elif operator == "*": value = input1 * input2 elif operator == "/": value = input1 / input2 else: print("Invalid operator") # End here return value def print_this(name): print('Hey ' + name) # return 0 option = 1 while option != 'exit': print("Enter your first value") number1 = int(input()) print("Enter your second value") number2 = int(input()) print("Enter you operator") op = input() print(calc(number1, number2, op)) # print_this("Mat") option = input("Type exit if you want to exit:")
true
96627c0924c2a27c74ad4e6eef0bfe0ba369027c
sarahmarie1976/cs-guided-project-python-basics
/src/demonstration_03.py
803
4.53125
5
""" Challenge #3: Create a function that takes a string and returns it as an integer. how would we cast string to integer We would instantiate an int object from the string data example --- int("10") then it will return an integer -- 10 if we check the type(int("10")) <class 'int'> We can use the int() constructor to convert other data types to an Interger Examples: - string_int("6") ➞ 6 - string_int("1000") ➞ 1000 - string_int("12") ➞ 12 """ # def string_int(txt): # # Your code here # #sent number to the int value to txt # number = int(txt) # # return number # return number def string_int(txt): # return the int value of text to the caller return int(txt) print(string_int("6")) print(string_int("1000")) print(string_int("12"))
true
6b884ea45e91503820623d0344ba2983c022cdb1
xiaochuanjiejie/python_exercise
/Exercise/15-18/exercise_13.6.py
1,213
4.1875
4
#-*- coding: utf-8 -*- from math import sqrt class Line(object): def __init__(self,x1=0,y1=0,x2=0,y2=0): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.length = 0 self.slope = 0 def getlength(self): if (self.x1 == self.x2) and (self.y1 == self.y2): self.length = 0 elif self.x1 == self.x2: self.length = abs(self.y2 - self.y1) elif (self.y1 == self.y2): self.length = abs(self.x2 - self.x1) else: self.length = sqrt(abs(self.x2 - self.x1) ** 2 + abs(self.y2 - self.y1) ** 2) return self.length def getslope(self): if self.length == 0: self.slope = None elif (self.x1 == self.x2) or (self.y1 == self.y2): self.slope = None else: self.slope = (self.y2 - self.y1) / (self.x2 - self.x1) return self.slope def __str__(self): return '坐标属性:((%d,%d),(%d,%d))' % (self.x1,self.y1,self.x2,self.y2) def __repr__(self): return '((%d,%d),(%d,%d))' % (self.x1,self.y2,self.x2,self.y2) l = Line(1,2,3,4) print l print '%r' % l print l.getlength() print l.getslope()
false
ed72de3aa6354a0e194df8e3ffeead2c69e5f379
diminako/100-days-of-python
/day-03-conditionals/day-03.py
2,425
4.25
4
# conditionals # If / Else statement print('Welcome to the Roller Coaster!') height = int(input("What is your height?\n")) if height >= 100: print('You may ride the roller coaster!') else: print('Grow up kid!') print('Neat!') print('----------------------') # Code Challenge Odd or even check num = int(input('Please input a number... \n')) if num % 2 == 0: # Modulo print(f'{num} is an even number!') else: print(f'{num} is an odd number!') print('----------------------') # Nested if / else print('Welcome to the Roller Coaster!') height = int(input("What is your height?\n")) if height >= 100: print('You may ride the roller coaster!') age = int(input('What is your age?')) if age <= 18: print('That will be $12.') else: print('That will be $20') else: print('Grow up kid!') print('----------------------') # if / elif / else print('Welcome to the Roller Coaster!') height = int(input("What is your height?\n")) if height >= 100: print('You may ride the roller coaster!') age = int(input('What is your age?')) if age < 12: print('That will be $5.') elif age <= 18: print('That will be $8') else: print('That will be $15') else: print('Grow up kid!') print('----------------------') # For Loop for string name= "Dimitri" def hello(name): for i in name: print(i) hello(name) print('----------------------') # BMI 2.0 Exercise height = float(input("What is your height in m? ")) weight = float(input("What is you weight in k? ")) bmi = round(float(weight / height ** 2), 3) if bmi <= 18: print(f"Your BMI is {bmi}, you are underweight.") elif bmi <= 22: print(f"Your BMI is {bmi}, you are normal weight.") elif bmi <= 28: print(f"Your BMI is {bmi}, you are slightly overweight.") elif bmi <= 33: print(f"Your BMI is {bmi}, you are obese.") else: print(f"Your BMI is {bmi}, you are clinically obese.") print('----------------------') # Leap year exercise # year = int(input("What year is it? ")) leap = "leap year" not_leap = "not a leap year" def leap_year(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: year = leap else: year = not_leap else: year = leap else: year = not_leap print(year) leap_year(2400) leap_year(1989) leap_year(2021) leap_year(2020)
true
6d9a4335b26fbea1049b8e593beadc0fb09cf10f
ZrcLeibniz/PythonTest
/mypro01/mypy10.py
277
4.375
4
# 测试zip()并行迭代 for i in [1, 2, 3]: print(i) names = ('rich', 'rich2', 'rich3', 'rich4') ages = (18, 16, 21, 43) jobs = ('老师', '程序员', '公务员') for names, ages, jobs in zip(names, ages, jobs): print("{0}---{1}---{2}".format(names, ages, jobs))
false
3d7ed338c44c8b0bd2bae45b1ee10274995dae07
ZrcLeibniz/PythonTest
/mypro01/mypy04.py
488
4.125
4
# 选择结构的嵌套 score = int(input("请输入学生的分数:")) grade = '' if score > 100 or score < 0: print("请认真输入学生的分数") score = int(input("请输入学生的分数:")) else: if 0 <= score < 60: grade = "不及格" elif 60 <= score < 80: grade = "及格" elif 80 <= score < 90: grade = "良好" elif 90 <= score <= 100: grade = "优秀" print("分数是{0},等级是{1}".format(score, grade))
false
943faf287b532ae4846c8960feb62e7d79a1214a
ZrcLeibniz/PythonTest
/mypro01/mypy08.py
1,020
4.1875
4
# break的学习 # break可用于while和for循环,用来结束整个循环。当有嵌套循环时,break语句只能跳出最近一层循环 # continue的学习 # continue语句用于结束本次循环,继续下一次循环。多个循环嵌套时,continue也是应用于最近一层循环 while True: a = input("请输入一个字符:") if a == 'q' or a == 'Q': print('循环结束,退出') break print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&') empNum = 0 salary = [] salarySum = 0 while True: s = input("请输入员工的薪资:(按q或者Q结束录入)") if s == 'q' or s == 'Q': print('录入结束') break if float(s) < 0: print('请认真输入员工薪资') continue empNum = empNum + 1 salary.append(float(s)) salarySum = salarySum + float(s) print("共有工人:{0}".format(empNum)) print("录入薪资:", salary) print("平均薪资为:{0}".format(salarySum/empNum))
false
449c36aa7b4d056abb31ea4623d7d3d29ec3d14c
TheGrateSalmon/Side-Projects
/Collatz Conjecture.py
1,048
4.1875
4
# Collatz Conjecture (3n+1) # performs the 3n+1 algorithm for any positive integer from time import * def main(): number = int(input('Input any positive integer or "0" to quit: ')) while number < 0: number = int(input('That is not a valid input. Please input any positive integer or "0" to quit: ')) step = 0 # if number = 0, exits program while number != 0: while number > 1: initial_time = process_time() step += 1 # number is even if number % 2 == 0: number = number // 2 # number is odd else: number = 3 * number + 1 elapsed_time = process_time() - initial_time print("This number has a total stopping time of ", step, " and took ", elapsed_time, " seconds to calculate.\n", sep="") number = int(input('Input any positive integer or "0" to quit: ')) # reinitialize step step = 0 main()
true
a43bf45cbc1d6a88280ed77efabc85d471978f6f
uisandeep/ML-Journey
/python/variablescope.py
1,923
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 31 14:57:34 2020 @author: sandeepthakur """ # Example 1 # Although x and y are two different variables, it will have same memory addess x=20 y=20 print(id(x)) print(id(y)) print("-----------------------------------------------------") # Example 2 # The address is not going to be same for lists. list1=[1,2,3] list2=[1,2,3] tuple1=(1,2,3) list3=list(tuple1) print(id(list1)) print(id(list2)) print(id(list3)) print(id(tuple1)) print("-----------------------------------------------------") # Example 3 # Local vs Global Variable a=100 # This is global variable a def func_8(): a=200 # This is local variable a print(a) print(id(a)) # This is the memory address of local variable a func_8() print(a) print(id(a)) # This is the memory address of global variable a print("-----------------------------------------------------") # Example 4 # Local vs Global Variable # I want to modify the gloabl variable inside a function. What should I do? a=100 # This is global variable a def func_8(): global a a=200 # This is now global variable a print(a) print(id(a)) # This is the memory address of global variable a func_8() print(a) print(id(a)) # This is the memory address of global variable a print("-----------------------------------------------------") # Example 5 # In this code, by writing global a before the value assignment line, we have made the behaviour of a to be global. So it is # accessible outside def func_9(): global a a=199 func_9() print(a) print("-----------------------------------------------------") c=100 def func_10(): c=200 print(c) #prints local global d d = 100 print(id(d)) func_10() print(c) #prints global print(id(c)) print("-----------------------------------------------------") print("-----------------------------------------------------")
true
265c8b5a4d091d1c9ee4066dc4ecf06270eb7205
jjliun/Python
/Interactive/project1.py
2,495
4.3125
4
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- # Filename : project1.py # Author : Yang Leo (JeremyRobturtle@gmail.com) # Last Modified : 2014-04-01 '''Demo of rock-paper-scissors-lizard-Spock ''' # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors # Exceptions class NotDefinedError(Exception): pass # Global variables _NAME_LIST = ['rock', 'Spock', 'paper', 'lizard', 'scissors'] _DICT_NAME_TO_NUM = dict([name, idx] for idx, name in enumerate(_NAME_LIST)) # Helper functions def name_to_number(name): '''Convert name of choice into relative number''' # The if/elif/else statements are ugly! try: return _DICT_NAME_TO_NUM[name] except KeyError: raise KeyError, "Valid inputs are: %s" % _NAME_LIST def number_to_name(number): '''Convert integer number into relative choice string''' # Use the built-in list exceptions to handle wrong inputs return _NAME_LIST[number] def rpsls(player_choice): '''Main implementation of rock-paper-scissors-lizard-Spock Player's choice is passed via parameter and computer's choice is random. Para: player_choice : string Returns: None. Results will be printed Raises: KeyError if player_choice is not valid NotDefinedError if the determine process didn't cover the situation ''' # Print player's choice and convert it into integer print print 'player chooses %s' % player_choice player_number = name_to_number(player_choice) # Generate random guess and print computer's choice import random # use len() expression instead of hard code 5 for flexibility # Change the _NAME_LIST and change the determine process then # you will get your own variant version. comp_number = random.randrange(0, len(_NAME_LIST)) comp_choice = number_to_name(comp_number) print 'Computer chooses %s' % comp_choice # Determine process diff = (player_number - comp_number) % len(_NAME_LIST) if diff in [1, 2]: print 'Player wins!' elif diff in [3, 4]: print 'Computer wins!' elif diff is 0: print 'Player and computer tie!' else: raise NotDefinedError, diff # in case of variant version def main(): '''Tests''' rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors") if __name__ == '__main__': main()
true
f15e22655fc5e6225dd18018e07cba2b0089aa93
Vansh-Arora/InteractWithOS
/diff-file-operations/workingOnFiles/last_modification_date.py
525
4.125
4
#!/usr/bin/env python import os import datetime def file_date(filename): # Create the file in the current directory file = open(filename,"w") file.close() timestamp = os.path.getmtime(filename) # Convert the timestamp into a readable format, then into a string date = str(datetime.datetime.fromtimestamp(timestamp)) # Return just the date portion # Hint: how many characters are in “yyyy-mm-dd”? return date[:10] print(file_date("newfile.txt")) # Should be today's date in the format of yyyy-mm-dd
true
8c74e8c55d53a970b46fde0f4305fe7da4988c07
cddas/python27-practice
/exercise-6.py
427
4.34375
4
user_string = raw_input("Enter a name for Palindrome check : ") list_string = [] reverse_list_string = [] for letter in user_string: list_string.append(letter) reverse_list_string = list_string[:] reverse_list_string.reverse() if (list_string == reverse_list_string): print("The entered string " + user_string + " is a pallindrome") else: print("The entered string " + user_string + " is not a pallindrome")
true
76fb884a8571e0cc23d7c1a122f78e3cc386d6c2
Simrang19/sort_n_search
/searching/bisect_library.py
553
4.125
4
# bisect : python library to use binary search # bisect left : find the leftmost possible index to insert in the list such that list is still sorted. # bisect right : find the rightmost possible index to insert in the list such that list is still sorted. import bisect li = list(map(int, input().split())) while True: ch = input() if ch == 'l': x = int(input()) print(bisect.bisect_left(li, x)) elif ch == 'r': x = int(input()) print(bisect.bisect_right(li, x)) else: print('akal nu hath maar')
true
df93e0dfc98976e5101dcf53d6cdad6044d643ea
596050/DSA-Udacity
/practice/data-structures/stacks/reverse-stack.py
347
4.125
4
from stack import * def reverse_stack(stack): """ Reverse a given input stack Args: stack(stack): Input stack to be reversed Returns: stack: Reversed Stack """ reversed_stack = Stack() for i in range(stack.size()): item = stack.pop() reversed_stack.push(item) return reversed_stack
true
2eb8ef40c03c083f60841c7e63e6043792a2fdc1
596050/DSA-Udacity
/practice/data-structures/recursion/string-permutations.py
1,148
4.1875
4
def permutations(string): """ :param: input string Return - list of all permutations of the input string TODO: complete this function to return a list of all permutations of the string """ return _permutations(string, 0) def _permutations(string, index): if index >= len(string): return [""] small_output = _permutations(string, index + 1) # print(small_output) output = list() current_char = string[index] for perm in small_output: for index in range(len(small_output[0]) + 1): new_perm = perm[0: index] + current_char + perm[index:] output.append(new_perm) return output # Test Cases def test_function(test_case): string = test_case[0] solution = test_case[1] output = permutations(string) output.sort() solution.sort() if output == solution: print("Pass") else: print("Fail") # string = 'ab' # solution = ['ab', 'ba'] # test_case = [string, solution] # test_function(test_case) string = 'abc' output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] test_case = [string, output] test_function(test_case)
true
ac702a3e7956293a0f38a414a3b45a22348de3e5
Aditya7256/Demo
/join sets.py
1,348
4.53125
5
# The union() method returns a new set with all items from both sets: set1 = {"a" "b", "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) # The update() method inserts the items in set2 into set1: set1 = {"a", "b", "c"} set2 = {1, 2, 3} set1.update(set2) print(set1) # The intersection_update() method will keep only the items that are present in both sets. # Keep the items that exist in both set x, and set y: # Keep ONLY the Duplicates: set1 = {"apple", "orange", "mango"} set3 = {"orange", "mango", "pineapple"} set1.intersection_update(set3) print(set1) # Return a set that contains the items that exist in both set1, and set2: set1 = {"apple", "orange", "mango"} set2 = {"mango", "pineapple", "grapes"} set3 = set1.intersection(set2) print(set3) # Keep All, But NOT the Duplicates # The symmetric_difference_update() method will keep only the elements that are NOT present in both sets. # Keep the items that are not present in both sets: set1 = {"apple", "orange", "mango"} set2 = {"pineapple", "guava", "apple"} set1.symmetric_difference_update(set2) print(set1) # Return a set that contains all items from both sets, except items that are present in both: set1 = {"apple", "orange", "mango"} set2 = {"grapes", "guava", "orange"} set3 = set1.symmetric_difference(set2) print(set3)
true
61e42234117d666ae39fe3783e82a85ffcb07813
Aditya7256/Demo
/join List.py
431
4.1875
4
# Join two list list1 = ["Apple", "banana", "mango"] list2 = [4, 7, 3] list3 = list1 + list2 print(list3) # append to list2 into list1 list1 = ["mango", "orange", "pineapple"] list2 = [3, 4, 25, 6] for x in list2: list1.append(x) print(list1) # use the extend() method to add list2 at end of list1 list1 = ["Apple", "mango", "banana", "orange"] list2 = [1, 2, 3, 4, 5, 6] list1.extend(list2) print(list1)
true
78b733b769bdba9af2c2676c6ec564442c608fb5
jmvbxx/happiness
/happiness_words.py
823
4.25
4
# This this program does two things: # # 1. Create a dictionary based on the happiness word list (AFINN-111.txt) # 2. Prompts the user to choose a word and returns the value of that word import re words_dict = {} # Generate dictionary from word list with open("AFINN-111.txt") as words: for line in words: word, score = line.strip().split("\t") words_dict[word] = int(score) print("This will return the 'happiness' value of a word!") while True: happy_word = raw_input("Please enter a word: ") try: if any(letter.isdigit() for letter in happy_word): raise ValueError() print words_dict[happy_word] break except KeyError: print("That word doesn't have a 'happiness' rating.") except ValueError: print("Nice try! That's not a word")
true
a3cc9d25bd458d2c080c60a4b15aa10d5cb4563b
SamanthaCorner/100daysPython-DAY-5
/adding_evens.py
618
4.25
4
""" 100 days of Python course DAY 5 """ # calculate the sum of all the even numbers from 1 to 100, # including 2 and 100: using the for ... in range loop # approach using range 2, 101 and stepping by 2 even_sum = 0 for number in range(2, 101, 2): even_sum += number print(even_sum) # a different approach by defining the range 1, 101 alternative_sum = 0 for number in range(1, 101): if number % 2 == 0: alternative_sum += number print(alternative_sum) # note: even_sum and alternative_sum are constant variables # once this subject is covered in future class it will make sense!
true
303698b606fe853364454dc666a8414eb803b920
UCD-pbio-rclub/Pithon_Michelle.T
/pithon_07112018/0711_ex3.py
1,178
4.125
4
#3. Demonstrate inheritance by importing your class "Organism" from problem 2. #Use it to create a new class called "LongOrganism" which inherits "Organism" and #modifies it by adding any other attributes that may be significant about an organism #(ie ploidy, genome size, region). Write new methods which allow a user to see these values in informative ways. class LongOrganism(Organism): def __init__(self, kingdom, phylum, Class, order, family, genus, species, name, ploidy, genome): Organism.__init__(self, kingdom, phylum, Class, order, family, genus, species, name) self.ploidy = ploidy self.genome = genome def description(self): print( 'Kingdom: ', self.kingdom, '\n', 'Phylum: ', self.phylum, '\n', 'Class:' , self.Class, '\n', 'Order: ', self.order, '\n', 'Family: ', self.family, '\n', 'Genus:' , self.genus, '\n', 'Species: ', self.species, '\n', 'Common name: ', self.name, '\n', 'Ploidy: ', self.ploidy, '\n', 'Genome size: ', self.genome) At = LongOrganism('Plantae', 'Magnoliophyta', 'Pentapetalae', 'Brassicales', 'Brassicaceae', 'Arabidopsis', 'thaliana', 'thale cress', '2n', '135 Mbp') print(At.description())
true
713737d145b1f751736a35aa7556e1482bf68e63
yashshah4/Data-Science-Projects
/Miscellaneous/charactercount.py
630
4.21875
4
#The following module helps prettify the printout of a dictionary #This module includes pprint() & pformat() to improve what print() generally offers import pprint #Asking for a text input from the user and saving it as a string message = str(raw_input("Enter a text : ")) #Declaring a dictionary to count characters count={} #iterating through each character for chara in message: count.setdefault(chara,0) count[chara]= count[chara]+1 pprint.pprint (str(count)) #If you want to obtain the prettified text as a string value instead of #dis- playing it on the screen, call pprint.pformat() instead # pprint.pformat(count)
true
e4fe8c8df4a778d3c73c3193df5e5995cf80029c
jovannovarian1117/stephanusjovan
/drivingsimulatorstephj.py
1,255
4.3125
4
# declare data for inputs # initial velocity set to 0 u = 0 time = 0 velocity_data = 0 # user have to input the time below t_input = int(input("Input time spent on the road")) # user have to input their acceleration below a = int(input("Input acceleration")) # user have to input distance travel below s_input = int(input("Input Distance")) v_limit = 60 distance = 0 # Input text for * explanation print ("This * indicates every 10 m ! ") # star loops for distance star = "*" star_count = 0 t = 0 while t <= t_input: distance = 0.5*a*(t**2) velocity_data = a * t_input star_count = int(distance/10) print ("Duration:" + str(t) + " Distance:" + star*star_count) t = t + 1 # data output 1 if velocity_data >= v_limit: print("The person went over the speed limit") print("Max speed was " + str(v_limit) +"m/s") else: print("The person did not go over the speed limit") print("Max speed was " + str(v_limit) +"m/s") # data output 2 if s_input <= distance: print("The person reach the destination") print("Reached " + str(distance) + " m") else: print("The person did not reach the destination") print("Reached " + str(distance) + " m")
true
68017376126391b4e4a4dae814825fdc903209ad
nconstable2/constable_n_python
/conditions.py
800
4.34375
4
# print a message to the terminal window print("Rules that govern the state of water") # set up a variable to hold the temp we input current_temp = False while current_temp is False: # MAKE THIS A NUMBER!! x = current_temp current_temp = x # see what current temp is print("you input:", x) # if the current temp is at freezing or below, water is solid if (int(x) < 0 or (int(x) == 0)): print("water is a solid! cuz it be all froze and shit") x = False # else check another condition, if it's not freezing, is it below boiling? elif (int(x) < 100): print ("water is a liquid, cuz it ain't freezing or boiling") x = False elif (int(x) > 100 or (int(x) == 100)): print("water is a gas, cuz it be hot") x = False
true
32560b22b72e04fd4c5d74538331c5101701df96
sridhar29k/interview-task
/Task_2_virtusa.py
706
4.15625
4
##Seating Arrangement. You have n students and n chairs in an exam hall. n/3 students are writing ##Maths, n/3 are writing physics and n/3 are writing chemistry. The n chairs are arranged in two ##rows, with n/2 in each row. Write an algorithm to make sure no two maths students sit either ##next/in front/behind of another maths students. import os import sys a=['M','P','C'] n=18 #you can give n value row=n/2 if __name__=="__main__": for i in range(0,2): # 2 rows for j in range (i,row+i): # n/2 rows for each person j=j%3 # n/3 writing Maths, n/3 are writing physics and n/3 are writing chemistry. print a[j], print "\n"
true
0ac4c535cf8c69463dcb5527747842510ae2318e
emerick23/python-control-flow-lab
/exercise-6.py
1,536
4.53125
5
# exercise-06 What's the Season? # Write the code that: # 1. Prompts the user to enter the month (as three characters): # Enter the month of the season (Jan - Dec): # 2. Then propts the user to enter the day of the month: # Enter the day of the month: # 3. Calculate what season it is based upon this chart: # Dec 21 - Mar 19: Winter # Mar 20 - Jun 20: Spring # Jun 21 - Sep 21: Summer # Sep 22 - Dec 20: Fall # 4. Print the result as follows: # <Mmm> <dd> is in <season> # Hints: # Consider using the in operator to check if a string is in a particular list/tuple like this: # if input_month in ('Jan', 'Feb', 'Mar'): # # After setting the likely season, you can use another if...elif...else statement to "adjust" if # the day number falls within a certain range. month = input('Enter the month of the season (Jan - Dec): ') day = input('Enter the day of the month: ') day_int = int(day) if (month == 'Dec' and day_int >= 21) or (month == 'Mar' and day_int <= 19) or month in ('Jan', 'Feb'): print(f'{month} {day_int} is in Winter') elif (month == 'Mar' and day_int >= 20) or (month == 'Jun' and day_int <= 20) or month in ('Apr', 'May'): print(f'{month} {day_int} is in Spring') elif (month == 'Jun' and day_int >= 21) or (month == 'Sep' and day_int <= 21) or month in ('Jul', 'Aug'): print(f'{month} {day_int} is in Summer') elif (month == 'Sep' and day_int >= 22) or (month == 'Dec' and day_int <= 20) or month in ('Oct', 'Nov'): print(f'{month} {day_int} is in Fall')
true
9fe75a4cd0e11f1266cb257deaf339ac3575e24a
Sam40901/Variables
/assignment development exercise 1.py
556
4.25
4
print("hello, this program will ask you for two numbers, divide one by the other, give you the integer and the variable.") number_1 = int(input("please enter your first number: ")) number_2 = int(input("please enter your second number: ")) number_integer = number_1 // number_2 number_remainder = number_1 % number_2 print("your answer is *drumroll please*") print("the integer of your equation equals {0}".format(number_integer)) print("the remainder of your equation equals {0}".format(number_remainder)) print("thanks for using!")
true
61d764d8419883b424ddedacee128a00621d22cf
pamelot/poem-word-count
/calculator.py
1,461
4.375
4
""" calculator.py Using our arithmetic.py file from Exercise02, create the calculator program yourself in this file. """ from arithmetic import * def main(): # This is where the user can input the calculation. # This will be a series of if statements for determining which function to call. cond = True while cond: input = raw_input("> ") numbers = input.split(' ') if numbers[0] == "+": addition = add(int(numbers[1]), int(numbers[2])) print addition elif numbers[0] == "-": subtraction = subtract(int(numbers[1]), int(numbers[2])) print subtraction elif numbers[0] == "*": multiplication = multiply(int(numbers[1]), int(numbers[2])) print multiplication elif numbers[0] == "/": division = divide(float(numbers[1]), float(numbers[2])) print division elif numbers[0] == "square": squaring = square(int(numbers[1])) print squaring elif numbers[0] == "cube": cubed = cube(int(numbers[1])) print cubed elif numbers[0] == "pow": powered = power(int(numbers[1]), int(numbers[2])) print powered elif numbers[0] == "mod": module = mod(int(numbers[1]), int(numbers[2])) print module elif numbers[0] == "q": break if __name__ == '__main__': main()
true
5d1f55b305b0929036b1baf302bd6195eac2beb7
AdriAriasAlonso/Python
/Practica6/E3P6.py
502
4.15625
4
#Ejercicio 3 Practica 6: Adrián Arias """Escribe un programa que pida notas y los guarde en una lista. Para terminar de introducir notas, escribe una nota que no esté entre 0 y 10. El programa termina escribiendo la lista de notas.""" notas=[] entrada=float(input("Escribe un número\n")) while entrada>=0 and entrada<=10: notas.append(float(entrada)) entrada=float(input("Dame otra nota o escribe un numero mayor a 10 o menor a 0 para salir\n")) print("Las notas que has introducido son", notas)
false
9cf59ca6e5ef627197a86a2bb92140e88d0242ff
derekforesman/CMPSC-131
/Python/apr_calculator.py
630
4.1875
4
#!/usr/bin/env python3 deposit = float(input("What is the amount you will be depositing?\n")) # get the amount to be deposited apr = float(input("Please enter the APR for the account. For example (2) will be read as 2% or 0.02\n")) # get the percent APR years = int(input("How many years will it gain interest?\n")) # get the number of years interest = ((apr / 100) + 1) # calculate the interest. Will always be 1.XX unless interest is over 100% total = (interest** years) * deposit # calculate the final amount in the account final = round(total, 2) print("Your final amount will be: $",final) # print the amount to the console
true
45120d9c4d2adcbe72d170ec14a1908e512cd132
aallooss/CSquared-2021
/2_Whats_your_name.py
217
4.125
4
# authored by >Haden Sangree< for >Coding with Character Camp< # Lesson 2 # CHALLENGE: Try changing the question and what your print. name = input("Whats your name? ") print("Your name is " + name) #challenge
true
22d44e8410c0f7f7cc3696f2ae60b39c43bddccb
hudaquresh/pythonDSRune
/sortingAndSearching/sorting/insertion.py
461
4.1875
4
'''Implementing an insertion sort algorithm.''' def insertionSort(aList): # insertion sort for index in range(1, len(aList)): currentValue = aList[index] position = index while position > 0 and aList[position-1] > currentValue: aList[position] = aList[position-1] position = position-1 aList[position] = currentValue return aList def main(): aList = [4, 5, 1, 2, 6, 3, 4, 2, 4, 2, 8, 7, 6, 5] print insertionSort(aList) main()
true
9f4225b7fbaf84b3d97360f38a12d72fb4c1d4b2
arleybri18/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
607
4.125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) if number < 0: print("Last digit of {0} is {1} and is less than 6 and not 0".format (number, -(-number % 10))) else: if (number % 10) > 5: print("Last digit of {0} is {1} and is greater than 5".format (number, (number % 10))) elif (number % 10) == 0: print("Last digit of {0} is {1} and is 0".format (number, (number % 10))) elif (number % 10) < 6: print("Last digit of {0} is {1} and is less than 6 and not 0".format (number, (number % 10)))
true
9808fd61460fd7caf2657561f8b172590def8396
arleybri18/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,357
4.4375
4
#!/usr/bin/python3 class Square: """Class with a instance private attribute, with optional value 0 validate type and value > to 0, send a message Error using raised and define a method to calculate area of square """ def __init__(self, size=0): """init method Args: size (int): Size of the square object """ self.__size = size def area(self): """Method to calculate area Returns: Return self.__size**2 """ return self.__size**2 def my_print(self): """Method to print the square Returns: nothing, print the square """ if self.__size == 0: print() else: for i in range(self.__size): print("#" * self.__size) @property def size(self): """Method to get the size Args: size (int): Size of the square object """ return self.__size @size.setter def size(self, value): """Method to set the size Args: size (int): Size of the square object """ if type(value) is not int: raise TypeError("size must be an integer") elif value < 0: raise ValueError("size must be >= 0") else: self.__size = value
true
35e4f85e35f97e1427b77f5c57632cc425eb18ac
IonesioJunior/Data-Structures
/Python/LinkedList/SingleLinkedList/RecursiveSingleLinkedList.py
2,998
4.25
4
#coding: utf-8 __author__ = "Ionesio Junior" class RecursiveLinkedList(object): ''' Single Linked List in recursive implementation Attributes: data(optional) : data stored in this object nextNode(RecursiveLinkedList) : next Recursive Node ''' __data = None; __nextNode = None; def __init__(self,data=None,nextNode=None): ''' Constructor of Recursive Linked List class, initialize attributes. Args: data(optional) : data to be stored in this object nextNode(RecursiveLinkedList) : next recursive object after this ''' self.__data = data self._nextNode = nextNode def isEmpty(self): ''' Return true if linked list is empty or false,otherwise. Complexity: O(1) Returns: boolean ''' return (self.__data == None) def size(self): ''' Return size of linked list. Complexity: O(n) Returns: size(int) : how many elements have in linked list ''' if(self.isEmpty()): return 0; else: return 1 + self.__nextNode.size() def search(self,element): ''' Search an specific element in linked list and return if found it.(Return None if can't found element) Complexity: O(n) Args: element (optional) : element to be searched Returns: foundElement (optional) : found element / None. ''' if(self.isEmpty() or element == None): return None else: if(self.__data == element): return self.__data else: return self.__nextNode.search(element) def insert(self,element): ''' Insert new element in last position of linked list (None elements aren't allowed). Complexity: O(n) Args: element(optional) : element to be inserted ''' if(element != None): if(self.isEmpty()): self.__data = element self.__nextNode = RecursiveLinkedList() else: self.__nextNode.insert(element) def remove(self,element): ''' Remove an specific element in linked list. Complexity: O(n) Args: element (optional) : element to be removed ''' if(not(self.isEmpty())): if(self.__data == element): self.__data = self.__nextNode.getData() self.__nextNode = self.__nextNode.getNext() else: self.__nextNode.remove(element) def toArray(self): ''' Return an list of all linked list elements Complexity: O(n) Returns: List[elements] ; all linked list elements. ''' result = [] if(self.size() > 0): self.__getList(result) return result def __getList(self,array): ''' Recursive Method to fill list Args: array[elements] : array with linked list elements. ''' if(self.__data != None): array.append(self.__data) self.__nextNode.__getList(array) def getNext(self): ''' Return next node Args: nextNode(RecursiveLinkedList) : next linked list node. ''' return self.__nextNode def getData(self): ''' Return data value of this node Returns: data(optional) : value of data ''' return self.__data
true
f2fa0f0eb5bfcfbff341ee268ed6652d1f589ee7
IonesioJunior/Data-Structures
/Python/Stack/Stack.py
2,027
4.125
4
#coding:utf-8 __author__ = "Ionésio Junior" class Stack(): """ Stack Structure Implementation Attributes: stackList[] = list of elements in stack size(int) = size of stack top(int) = index of top """ __stackList = None; __size = None; __top = None; def __init__(self,size = 10): '''' Stack Constructor. Initialize attributes with default value. ''' self.__stackList = [] self.__size = size self.__top = -1 def push(self,element): ''' Insert new element in the top of the stack or raise an exception if stack is full Complexity: O(1) Args: element(optional) : element to be inserted Raises: Exception : When stack is full ''' if(element != None and not(self.isFull())): self.__top = self.__top + 1 self.__stackList.insert(self.__top,element) elif element == None: return; else: raise Exception("Stack is Full!!") def pop(self): ''' Remove element in top of the stack or raise an exception if stack is empty Complexity: O(1) Returns: removedElement(optional) : element removed Raises: Exception: When stack is empty ''' if(not(self.isEmpty())): removedElement = self.__stackList[self.__top] del self.__stackList[self.__top] self.__top = self.__top - 1 return removedElement else: raise Exception("Stack is empty!!") def top(self): ''' Return element in top of the stack without remove it, or return None if stack is empty Complexity : O(1) Returns: element(optional) : element in top of the stack / None ''' if(not(self.isEmpty())): return self.__stackList[self.__top] else: return None def isEmpty(self): ''' Return true if stack is empty or false,otherwise. Complexity: O(1) Returns: boolean ''' return (self.__top < 0) def isFull(self): ''' Return true if stack is full or false,otherwise Complexity: O(1) Returns: boolean ''' return (self.__size - 1 == self.__top)
true
020210178bbd278da6d41b09c26ea74d5bca0c84
IonesioJunior/Data-Structures
/Python/Queue/SimpleQueue.py
2,244
4.4375
4
#coding: utf-8 __author__ = "Ionésio Junior" class SimpleQueue(): ''' Implementation of simple queue data structure Attributes: queueList[] : list of elements in queue size(int) : size of list tail(int) : index of queue tail ''' def __init__(self,size = 10): ''' Constructor of Simple Queue initialie attributes using default values. Args: size(int) : capacity of queue, Default to 10. ''' self.__queueList = [] self.__size = size self.__tail = -1 def enqueue(self,element): ''' Insert new element in tail of the queue or raise and exception if queue is full (None elements aren't allowed). Complexity: O(1) Args: element(optional) : element to be inserted Raises: Exception: When queue is full ''' if(element == None): return; if(not(self.isFull())): self.__tail = self.__tail + 1 self.__queueList.insert(self.__tail,element) else: raise Exception("Queue is Full!!") def dequeue(self): ''' Remove and return element in head of the queue or raise and exception if queue is empty Complexity: O(n) Returns: element(optional) : removed element Raises: Exception : when queue is empty ''' if(not(self.isEmpty())): removedElement = self.__queueList[0] self.__shiftLeft() self.__tail = self.__tail - 1 return removedElement else: raise Exception("Queue is Empty!!") def __shiftLeft(self): ''' Move each of queue elements to previous position , after remove some node ''' for i in range(self.__tail): self.__queueList[i] = self.__queueList[i+1] def head(self): ''' Return the element of queue head without remove it. (If queue is Empty, return None). Complexity: O(1) Returns: element (optional): element in head position/None. ''' if(not(self.isEmpty())): return self.__queueList[0] else: return None def isEmpty(self): ''' Return true if queue is empty or false,otherwise. Complexity: O(1) Returns: boolean ''' return (self.__tail < 0) def isFull(self): '''Return true if queue is full or false,otherwise. Complexity: O(1) Returns: boolean ''' return (self.__tail == self.__size - 1)
true
d3659a72ef9816bee8d3c05c1c15f73fb2fb89e8
khemasree/CSEE5590_Lab
/Lab1/Source/Lab1/lab2a.py
994
4.21875
4
input = input("Please enter the sentence") # Initialize all the variables with default values individualwords=input.split() wordset=individualwords longestword = '' reversesen = '' print(wordset) # For even number of words print the middle two words if len(wordset) % 2 == 0 : print("Middle Words are: ["+individualwords[int(len(wordset)/2 - 1)]+","+individualwords[int(len(wordset)/2)]+"]") # And for odd, Print the middle word else: middleword=int(len(wordset)/2) print("Middle Word is: ["+individualwords[middleword]+"]") # Reverse individual words in a sentence and append that to the variable created for storing the reversed sentence for i in wordset: reverse = i[::-1] reversesen = reversesen+' '+ reverse # If the new word is greater than the longest word then reassign longest word to the new word if len(i) > len(longestword): longestword = i print("The longest word is: " + longestword) print("Sentence with reverse words is: " + reversesen)
true
5677689f850e6b426c4a88976b4bd1e9e6c07aa2
SillAndrey/training
/next_factorial.py
876
4.25
4
def next_factorial(n): ''' find all Prime Factors (if there are any) and display them. program find prime numbers until the user chooses to stop asking for the next one. ''' Ans = [] d = 2 while d * d <= n: if n % d == 0: Ans.append(d) n //= d else: d += 1 if n > 1: Ans.append(n) return Ans if __name__ == "__main__": n = int(input('Please, enter factorial: ')) result = next_factorial(n) iterable_obj = iter(result) while True: select = input('\nEnter \'next\', for next prime number, or \'stop\' for exit: ') if select == 'next': try: print(iterable_obj.__next__()) except StopIteration: print('iteration is over') break elif select == 'stop': break
true
6ffe61b87d42a3734848c0cf33a315be33da25d4
jan-nemec/ATBSWP
/03_exception_zero_divide.py
1,008
4.28125
4
# Errors can be handled with try and except statements. # The code that could potentially have an error is put in a try clause. # The program execution moves to the start of a following except clause if an error happens. # You can put the previous divide-by-zero code in a try clause # and have an except clause contain code to handle what happens when this error occurs. # def spam(divideBy): # return 42 / divideBy # When code in a try clause causes an error, # the program execution immediately moves to the code in the except clause. # After running that code, the execution continues as normal. def spam(divideBy): try: return 42 / divideBy except ZeroDivisionError: print('Error: Invalid argument.') print(spam(2)) print(spam(12)) print(spam(0)) print(spam(1)) # The reason print(spam(1)) is never executed is because once the execution jumps to the code in the except clause, # it does not return to the try clause. Instead, it just continues moving down as normal.
true
9a97f2525c57bb9d575b24669f5686b4c78cf198
Zahidsqldba07/competitive-programming-1
/Leetcode/Problems/p987.py
2,364
4.125
4
# 987. Vertical Order Traversal of a Binary Tree ''' Print a Binary Tree in Vertical Order Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Return a list of lists of the elements in each vertical level, from left to right and top to bottom in each list. 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 The node with value 5 and the node with value 6 have the same position according to the given scheme. However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6. The output of print this tree vertically will be: 4 2 1 5 6 3 8 7 9 pseudocode: --> some traversal of tree (bfs) --> map node_value -> position tuple(x,y) --> for all same y's --> sort node_values first by x_value, tiebreak by node_value --> return list[list] format ''' class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: # def verticalOrder(root: TreeNode) -> list(list(int)): q = [(root, (0, 0,))] node_position_map = {} while q: node, position = q.pop(0) node_position_map[root.val] = position x_map[position[0]].append(root.val) if node.left: q.append((node.left, (position[0] - 1, position[1] - 1))) # node_position_map[root.left.val] if node.right: q.append((node.right, (position[0] + 1, position[1] - 1))) x_mapping = {} # x_value:[(node_val,y_value)] x_vals = [] # {0: [1,5,6,], ....} for node_value, pos in node_position_map: x, y = pos if x not in x_value: x_vals.append(x) x_mapping[x] = [(node_value, y)] else: x_mapping[x].append((node_value, y)) x_vals.sort() res = [] for x in x_vals: vals = [i[0] for i in x_mapping[x]] vals.sort(key=lambda x: (1 / node_position_map[x][1], x)) res.append(vals) return res
true
41731edbe4168ead2b1a686ada6cc9bdde370677
Zahidsqldba07/competitive-programming-1
/Leetcode/June Leetcooding Challenge/sort_colors.py
1,322
4.3125
4
# Sort Colors ''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. ''' class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ # freq = {0:0, 1:0, 2:0} # for i in nums: # freq[i] += 1 # print(nums) # nums = [0] * freq[0] + [1] * freq[1] + [2] * freq[2] # nums = [0 for _ in range(freq[0])] + [1 for _ in range(freq[1])] + [2 for _ in range(freq[2])] # print(nums) # i = 0 # j = 0 # k = 0 # for i in range(freq[0]): # nums[i] = 0 # # start = # for j in range(i+1, i + freq[1]+1): # nums[j] = 1 # for k in range(j+1, j + freq[2]+1): # nums[k] = 2 # for i in range(len(nums)): for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): if nums[j] < nums[i]: nums[i], nums[j] = nums[j], nums[i]
true
018d052ffdbc192e36c18097ecee981143d66a21
aviidlee/backend-coding-challenge
/tools/scoringmethods/scoringmethod.py
967
4.28125
4
from abc import abstractmethod class ScoringMethod(object): ''' Abstract base class for a scoring method and its associated parameters. Given two strings, return a number in range [0, 1] representing how closely the strings match, where the higher the number, the closer the match. Methods: score -- returns a score between 0 and 1 inclusive, indicating how closely two strings match ''' def __init__(self, params): ''' Constructor ''' @abstractmethod def score(self, query, text): '''Text-based only match score between query and text. Returns: A score in range [0, 1] where 1 indicates the best possible match between query and text, and 0 indicates no match. ''' pass @abstractmethod def name(self): '''Returns name of this scoring algorithm. '''
true
c13891e853f055cae779f3dea7a797090595f7f4
vijaycs20/Python_Projects
/Vote age.py
371
4.25
4
# -*- coding: utf-8 -*- month=int(input("Enter your month of birth : ")) year=int(input("Enter your year of birth : ")) age=2020-year mon=9-month vote="You are eligible for voting! Just use your power!" if age>=18 else "you are just ",age,"years And",mon,"months Old!.\n S0 you're not eligible for voting.\n S0, just calm down and wait until 18 to vote." print(vote)
true
86006b7f09c6ed179b076b85e9052a265e969d77
zaliubovskiy/webacademy
/HomeWork_06/03_Sort_array_by_element_frequency.py
678
4.375
4
# Sort the given iterable so that its elements end up in the decreasing frequency order, that is, the number # of times they appear in elements. If two elements have the same frequency, they should end up in the same # order as the first appearance in the iterable. def frequency_sort(items): # Sorting by index first: sorted_by_index = sorted(items, key=lambda i: items.index(i)) # Sorting by frequency (descending): sorted_by_frequency = sorted(sorted_by_index, key=lambda i: sorted_by_index.count(i), reverse=True) return sorted_by_frequency print(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
true
fd8e289bd82fcc379ee150f9f7a10eea70296385
EradicDagger/Coding-Questions
/Python/Task1.py
1,209
4.25
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ # Get unique telephone numbers for both receving and sending columns in texts and calls texts_sending_telephone_set = set([text[0] for text in texts]) texts_receiving_telephone_set = set([text[1] for text in texts]) calls_calling_telephone_set = set([call[0] for call in calls]) calls_receiving_telephone_set = set([call[1] for call in calls]) # Getting union of all the sets unique_telephone_number_set = set(texts_sending_telephone_set .union(texts_receiving_telephone_set) .union(calls_calling_telephone_set) .union(calls_receiving_telephone_set)) print("There are " + str(len(unique_telephone_number_set)) +" different telephone numbers in the records.")
true
856b9487bd2e8cdeda776566d80d8a4e5f10aac9
kewy76/ICP4
/One.py
2,237
4.1875
4
# Kate Williams # 6/14/2018 class Employee: # Employee class """A class representing an employee""" empNum = 2 def increment(self): self.__class__.empNum += 1 def __init__(self, n, f, s, d): self.name = n self.family = f self.salary = s self.dept = d def get_name(self): print("The employee's name is " + self.name) return def get_family(self): print("The employee's family name is " + self.family) return def get_salary(self): print("The employee's salary is " + str(self.salary)) return def get_salary_value(self): # Second salary function; only returns number return self.salary def get_dept(self): print("The employee's department is " + self.dept) return def get_emp_num(self): print("The number of employees is " + str(self.empNum)) return class FullTimeEmployee(Employee): """A class representing a full time employee Class inherits from employee""" def __init__(self, n, f, s, d, h): Employee.__init__(self, n, f, s, d) self.hours = h def get_hours(self): # New type of data for new class; not inherited print("The employee works " + self.hours + " hours") def avg_salary(): # Definition to average salary x = 0 # Define counter variable total = 0 # Define final answer variable while x < len(eArray): # While the counter is in the # of employees total += eArray[x].get_salary_value() # Add salary to total x += 1 # Iterate total = total / x # Divide total salaries by # of employees print("The average salary is $" + str(total)) # Make some employees and call functions Emp1 = Employee("Diana", "Prince", 4000, "Management") Emp2 = FullTimeEmployee("Natasha", "Romanov", 3000, "Sales", "20") eArray = [Emp1, Emp2] print("For employee 1: ") Emp1.get_name() Emp1.get_family() Emp1.get_salary() Emp1.get_dept() print("\n") print("For employee 2: ") Emp2.get_name() Emp2.get_family() Emp2.get_salary() Emp2.get_dept() Emp2.get_hours() print("\n") Emp1.get_emp_num() avg_salary()
false
0115be8b2cb5a2fad67d50f042fe3dcf2d7661ab
Igor-Suchilin/Python
/LESSON1/lesson1.6.py
758
4.125
4
def choose_plural(num, choice): if (num // 10) % 10 == 1 or num % 10 == 0: return str(num) + ' ' + choice[2] elif num % 10 == 1: return str(num) + ' ' + choice[0] elif num % 10 <= 4: return str(num) + ' ' + choice[1] else: return str(num) + ' ' + choice[2] choice = 'день дня дней'.split() a = int(input('Сколько киллометров пробежали в первый день?')) b = int(input('Сколько киллометров хотите пробежать')) days = 12 if a >= b: print("Нужно хотеть больше!") while a <= b: a += (a/10) days += 1 print('Через', choose_plural(days, choice), 'вы пробежите сколько хотите')
false
d67807edc76b47cfcf8aaed6ed71d9e8c33b4752
alamine42/coursera_computing_spec
/coursera-computing-01/Week2/user40_1Frzg4VuPq_5.py
2,375
4.21875
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, random, math secret_number = 1000 secret_range = 100 remaining_guesses = 1 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global secret_number global secret_range global remaining_guesses print '' print 'New game with range [0, ' + str(secret_range) +')' # Compute the max number of allowed guesses remaining_guesses = int(math.ceil(math.log(secret_range, 2))) print 'You are allowed ' + str(remaining_guesses) + ' guesses.' secret_number = random.randint(0, secret_range - 1) # define event handlers for control panel def range100(): # button that changes the range to [0,100) and starts a new game global secret_range secret_range = 100 new_game() def range1000(): # button that changes the range to [0,1000) and starts a new game global secret_range secret_range = 1000 new_game() def decrement_guesses(): global remaining_guesses remaining_guesses -= 1 if remaining_guesses > 0: print 'You have ' + str(remaining_guesses) + ' guesses remaining.' else: print 'You have 0 guesses remaining. You lost.' def input_guess(guess): # main game logic goes here print '' print 'Guess was ' + guess guess_num = int(guess) if remaining_guesses > 0: if guess_num < secret_number: print 'Higher' decrement_guesses() elif guess_num > secret_number: print 'Lower' decrement_guesses() else: print 'Correct' new_game() else: print 'You are not allowed any more guesses!' print 'Please start a new game.' # create frame frame = simplegui.create_frame("Guess the number", 300, 300) # register event handlers for control elements and start frame inp_guess = frame.add_input('Guess', input_guess, 50) button_100 = frame.add_button('Range [0, 100)', range100, 100) button_1000 = frame.add_button('Range [0, 1000)', range1000, 100) frame.start() # call new_game new_game() # always remember to check your completed program against the grading rubric
true
1da645660ab64d0951d894634b5d143e16d2ab77
smiledt/Full-Stack-Web-Developer-Bootcamp
/python_lesson1/dictionaries.py
256
4.375
4
# Dictionary examples my_dict = {"key1": 123, "key2": "value2", 'key3': {"123": [1, 2, 'grabme']}} print(my_dict['key3']['123'][2].upper()) dict2 = {'lunch': 'pizza', 'bfast': 'eggs'} print(dict2['lunch']) dict2['lunch'] = 'burger' print(dict2['lunch'])
false
9a8d5de84f8877cf39d1bd52027f157c432bbee2
ikaros274556330/my_code
/python_1000phone/语言基础/day16-面向对象2/code/03-getter和setter.py
2,224
4.15625
4
"""__author__=吴佩隆""" import time """ 时间戳:当前时间距离1970年1月1日0时0分0秒的时间差,单位是秒 """ print(time.time()) # 获取当前时间的时间戳 time1 = time.time() # localtime(时间戳) - 将时间戳转化为当地时间 time2 = time.localtime(time1) print(time2) '2019-11-26 14:15:00' # 1.getter 和 setter """ 1)什么时候用 如果希望在对象属性赋值前做点别的什么事情就给这个属性添加setter 如果希望在获取属性值之前做点别的什么事情就给这个属性添加getter 2)怎么用 getter a.将需要添加getter的属性名前加_ b.声明函数:声明前加@property 函数名必须是属性名不带_ 函数需要一个返回值,返回值就是获取属性得到的值 c.在外部使用属性的时候不带_ setter: 注意:如果想要给属性添加setter必须先添加getter a.声明函数:声明前加@getter名.setter; 函数名不带_的属性名; 函数不需要返回值,但是需要一个参数,这个参数就是给属性赋的值 b.在外面给属性赋值的时候不带下划线 """ class Person: def __init__(self, age: int): self._age = age self._time = 1574749600.202029 @property def time(self): t_time = time.localtime(self._time) return time.strftime("%Y--%m--%d %H:%M:%S", t_time) @property def age(self): return self._age @age.setter def age(self, value): print('value:', value) if isinstance(value, int): if 0 <= value <= 200: self._age = value else: raise ValueError else: raise ValueError # p1 = Person(18) # p1.age = 18 # p1.age = 'abc' print('===========================================') # print(p1.time) class Circle: pi = 3.141592653 def __init__(self, r): self.r = r self._area = 0 @property def area(self): return Circle.pi * self.r ** 2 @area.setter def area(self,value): print('给area属性赋值:', value) raise ValueError c1 = Circle(1) print(c1.area) c1.r = 10 print(c1.area) c1.area = 3.14 c1.area = 1000
false
7a1ddb808e3b92d08f8a86db50680e0a09fc4957
ikaros274556330/my_code
/python_1000phone/语言基础-老师代码/day4-分支和循环/day4-分支和循环/02-分支结构.py
1,629
4.3125
4
"""__author__=余婷""" # 1. if-elif-else结构 """ 1)语法: if 条件语句1: 代码段1 elif 条件语句2: 代码段2 elif 条件语句3: 代码段3 ... else: 代码段N 其他语句 2) 执行过程: 先判断条件语句1是否为True,为True就执行代码段1,然后整个if-elif-else结构结束; 如果为False,就判断条件语句2是否为True, 为True就执行代码段2,然后整个if-elif-else结构结束; 如果是False,就判断条件语句3是否为True, 为True就执行代码段3,然后整个if-elif-else结构结束; 以此类推 如果所有的条件语句都不成立,执行else后面的代码段 """ # 根据年龄范围打印: 少年(14以下)、青年(14~25)、壮年(26~35)、中年(36 ~ 50)、老年(50以上) age = 30 if age < 14: print('少年') elif age <= 25: print('青年') elif age <= 35: print('壮年') elif age <= 50: print('中年') else: print('老年') # 2.if嵌套 """ if结构中的代码块中可以再出现其他的if语句 """ # 判断一个数是否是偶数,并且再判断这个数是否是4的倍数;并打印出结论 num = 13 # 方法一: if num & 1 == 0: print('偶数') else: print('奇数') if num % 4 == 0: print('是4的倍数!') # 方法二: print('====================') if num & 1 == 0: print('偶数') if num % 4 == 0: print('是4的倍数!') print('++++') else: print('奇数') if num % 10 == 3: print('个位数是3') # if age < 14: # print('少年') # # if 14 <= age <= 25: # print('青年') # # if 25 < age <= 35: # print('壮年')
false
7737ac629d4f74c7b3bd8194a59bbbd2e2965496
ikaros274556330/my_code
/python_1000phone/语言基础-老师代码/day6-列表元组和数字/code/05-元组.py
1,856
4.25
4
"""__author__=余婷""" # 1.什么是元祖(tuple) """ 元组就是不可变的列表 元组是容器型数据类型,将()作为容器的标志,里面多个元素用逗号隔开: (元素1,元素2,元素3,...) 元祖不可变(不支持增删改操作), 有序(支持下标操作) 元素可以是任何类型的数据 """ tuple1 = (1, 2, 3) print(type(tuple1)) # 2.和列表一样的操作 # 1)获取元素 # 列表获取元素的操作元组都支持 tuple2 = (10, 30, 21, 70) print(tuple2[-1]) print(tuple2[1]) print(tuple2[2:]) # (21, 70) # 2)相关运算: +, *, ==, !=, is, in, not in, len, max, min, sum,sorted print((1, 2, 3) + ('abc', 'hello')) print((1, 2, 3) * 3) # tuple(数据) - 将数据转换成元祖(数据必须是序列) print(tuple('hello')) # ('h', 'e', 'l', 'l', 'o') # 3.元组特有或者使用频率偏高的操作 # 1)单个元素的元组: (元素,) # list1 = [10] # print(list1, type(list1)) tuple3 = (10,) print(tuple3, type(tuple3)) # 2)单独使用的元组的值,()可以省略 -> 直接多个数据用逗号隔开表示的还是一个元组 tuple4 = 10, 20, 30 print(tuple4, type(tuple4)) # 3)可以通过让变量的个数和元组中元素的个数保持一致来分别获取元组中的元素 # 变量1, 变量2, 变量3, ... = 元祖 tuple5 = (10, 20) x, y = tuple5 print(x, y) # x, y = (10, 20) -> x, y = 10, 20 # 4)同时声明多个变量获取元组中的元素,变量的个数可以比元组中元素的个数少,但是这个时候 # 多个变量中的某一个变量的前面必须加*;带*的变量可以获取不带*的变量获取完剩下的部分 tuple5 = (10, 20, 299, 19, 230) *x1, x2, x3 = tuple5 print(x2, x3, x1) # 19 230 [10, 20, 299] x1, *x2, x3 = tuple5 print(x1, x2, x3) # 10 [20, 299, 19] 230 x1, x2, *x3, x4 = tuple5 print(x1, x2, x3, x4) # 10 20 [299, 19] 230
false
03552a1e563ac606495fb7e9c767697919f944b9
ikaros274556330/my_code
/python_1000phone/语言基础-老师代码/day15-面向对象1/06-类中的属性.py
1,834
4.5
4
"""__author__=余婷""" # 1.类中的属性 - 就是类中保存数据的变量 """ 类中的属性分为2种:字段、对象属性 """ # 2.字段 """ 1)怎么声明: 直接声明在类里面函数外面的变量就是字段 2)怎么使用: 通过类使用; 以'类.字段'的形式去使用 3)什么时候用:不会因为对象不同而不一样的属性就声明成对象属性 """ # 3.对象属性 """ 1)怎么声明:声明在__init__方法中;以'self.属性名=值'的形式来声明 2)怎么使用: 通过对象来使用; 以'对象.属性'的形式来使用 3)什么时候用: 会因为对象不同而不一样的属性就声明成对象属性 """ class Person: # a就是字段 a = 10 # name和age就是对象属性 def __init__(self): self.name = '小明' self.age = 18 # print(a) # NameError: name 'a' is not defined print(Person.a) p1 = Person() print(p1.name, p1.age) p2 = Person() print(p2.name, p2.age) p2.name = '小花' class Student: def __init__(self, n, s=0): self.name = n self.age = 18 self.score = s stu1 = Student('小明') print(stu1.name, stu1.age, stu1.score) stu2 = Student('小花', 60) print(stu2.name, stu2.age, stu2.score) # 声明一个狗类,拥有属性:品种、名字、颜色、年龄、性别; 功能: 吃(xxx吃xxx) class Dog: def __init__(self, name, bread='土狗', color='黄色', age=1, gender='公狗'): self.breed = bread self.name = name self.color = color self.age = age self.gender = gender def eat(self, food: str): # self=dog1; food='肉' print('%s在吃%s' % (self.name, food)) # self.name->dog1.name dog1 = Dog('大黄') dog2 = Dog('财财', color='黑色') dog1.eat('肉') dog2.eat('骨头')
false
e923a39be0eeda5287d947d85f1c06ea88afbae3
reyesmi/Automate-the-Boring-Stuff-Codes
/2_guessTheNumber.py
1,236
4.3125
4
# This is a guess the number game. import random # imports random module secretNumber = random.randint(1,20) #sets a variable named secretNumber, which is equal to a random number generated between 1 to 20. print("I am thinking of a number between 1 and 20.") # informs user of the range of numbers. # Ask the player to guess 6 times. for guessesTaken in range (1,7): # for loop is used. user has 6 chances to guess print("Take a guess.") # prints "Take a guess." guess = int(input()) # user's input is stored in variable named guess. if guess < secretNumber: # sets condition. if guess is less than secretNumber, then next line is executed. print("Your guess is too low.") elif guess > secretNumber: # sets condition. if guess is greater than secretNumber, then next line is executed. print("Your guess is too high.") else: break # This condition is the correct guess! if guess == secretNumber: # this is a new block. Next line is executed if user correctly guesses the number. print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!') else: # Next line is executed if user did not guess. print("Nope. The number I was thinking of was " + str(secretNumber))
true
35cef219cf6ae91d509d6fad385e59d03447f138
hzuluag56268/pycharm
/PycharmProjects/DeepLearning/Introduction to Deep Learning with PyTorch.py
1,567
4.5
4
'''1 Introduction to PyTorch ''' ......Introduction to PyTorch import torch # Create random tensor of size 3 by 3 your_first_tensor = torch.rand(3, 3) # Create a matrix of ones with shape 3 by 3 tensor_of_ones = torch.ones(3, 3) # Create an identity matrix with shape 3 by 3 identity_tensor = torch.eye(3) # Do a matrix multiplication of tensor_of_ones with identity_tensor matrices_multiplied = torch.matmul(tensor_of_ones, identity_tensor) .......Backpropagation by auto-differentiation # Initialize x, y and z to values 4, -3 and 5 x = torch.tensor(4., requires_grad=True) y = torch.tensor(-3., requires_grad=True) z = torch.tensor(5., requires_grad=True) # Set q to sum of x and y, set f to product of q with z q = x + y f = q * z # Compute the derivatives f.backward() # Print the gradients print("Gradient of x is: " + str(x.grad)) print("Gradient of y is: " + str(y.grad)) print("Gradient of z is: " + str(z.grad)) # Multiply tensors x and y q = x * y # Elementwise multiply tensors z with q f = q * z mean_f = torch.mean(f) # Calculate the gradients mean_f.backward() ......Introduction to Neural Networks class Net(nn.Module): def __init__(self): super(Net, self).__init__() # Instantiate all 2 linear layers self.fc1 = nn.Linear(784, 200) self.fc2 = nn.Linear(200, 10) def forward(self, x): # Use the instantiated layers and return x x = self.fc1(x) x = self.fc2(x) return x '''2 Artificial Neural Networks''' ..........Activation functions
true
c59edea7dbf2eebdb2d1e7c12241915eb2ab4bb1
apbaca06/Python_100Days
/day-27/main.py
816
4.15625
4
from tkinter import * # document: http://tcl.tk/man/tcl8.6/TkCmd/entry.html window = Tk() window.title("GUI Program") window.minsize(500, 600) window.config(padx=100,pady=200) my_label = Label(text="I'm a label.", font=("Arial", 24, "italic")) # Pack the label on to the screen my_label.pack(side="top") my_label.pack(expand=False) my_label.grid(column=0, row=0) my_label["text"] = "New Text" my_label.config(text="New Text") def button_clicked(): new_text = input.get() my_label.config(text=new_text) print("I got clicked") my_button = Button(text="Click Me", command=button_clicked) my_button.grid(column=1, row=1) input = Entry(width=10) input.grid(column=3, row=2) new_button = Button(text="New Button") new_button.grid(column=2, row=0) # Keep the window on the screen window.mainloop()
true
b87072210ca5537a154dd3852a508cf374652bcd
ostapalfavitskyi/Lv-609.PythonCore
/HW5/Anton/1.py
247
4.21875
4
even = [] odd = [] not_div = [] for i in range(1,11): if i%2 == 0 : even.append(i) elif i%2 and i%3 != 0: not_div.append(i) else: odd.append(i) print(f'\nEven: {even}\nOdd: {odd}\nNot divisible: {not_div}\n')
false
ee171bbf10d81ee2bca71d7e354cc47614530dff
cesarschool/cesar-school-fp-2018-2-lista1-EduardoBBGusmao
/questoes/questao_1.py
904
4.125
4
## QUESTÃO 1 ## # Faça um programa que calcule o aumento de um salário. Ele deve solicitar o # valor do salário e a porcentagem do aumento. Exiba o valor do aumento e do # novo salário. ## ## # A sua resposta da questão deve ser desenvolvida dentro da função main()!!! # Deve-se substituir o comado print existente pelo código da solução. # Para a correta execução do programa, a estrutura atual deve ser mantida, # substituindo apenas o comando print(questão...) existente. ## def main(): print("questao 1") opcao = 'sim' while opcao == 'sim' or opcao == 'Sim': salario = float(input("Digite o salário atual?\n")) aumento = float(input("Digite a porcentagem do aumento\n")) salario = salario*(100+aumento)/100 print("Esse é o novo salário", salario) opcao = input("Deseja continuar? (Sim/Nao)\n") if __name__ == '__main__': main()
false
b874e8fbf6c9bd36ecff0b75e4780133517d1971
sapphire008/Python
/python_tutorials/ThinkPython/practice_notes_2.py
2,403
4.28125
4
# Python 3.3.0 Practice Notes # Day 2: November 24, 2012 import math; # Conditional statements x=1; y=2; z=3; if x<y and z<y: #again, don't forget the colon print("Y is teh biggest!"); elif x<y or z<y: print("Let's do nothing!"); else: print("Okay, I am wrong"); #again, additional empty line for ending this stub # Recursion: a recursive function is a function that calls itself def countdown(n): if n<=0: print("Balst Off!"); else: print(n); countdown(n-1); countdown(3) #The function itself is like a while loop: #As long as the else statement is executed (by calling itself), #the loop continues until that the function no longer calls itself #The output looks like this: #>>>3 #>>>2 #>>>1 #>>>Blast Off! # User Prompt ask_question = input("Do you like Python? [Y/N]:\n");#asking user to type in something, str, int, float, etc... if ask_question=="Y": print("Me, too"); else: ask_another_question = input("Why not?\n"); print("Oh, okay, I see."); #Note: % or some other symbol in the Python Shell prompts user input # Non-void functions abs(-3.323);#returns the absolute value of the input number # Iteration #for loop for i in range(0,4,1): print("Hello, World!"); #range(start, stop, step), default_start=0, default_step=1 #all number must be integers #the first number of the array built by range will be start #the last number of the array built by range will be (stop-step) #The following example iss from: http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python_3/For_Loops demolist = ['life',42,'the universe',6,'and',7,'everthing']; for item in demolist: print("The Current item is:",item); #The output is like this: #The Current item is: life #The Current item is: 42 #The Current item is: the universe #The Current item is: 6 #The Current item is: and #The Current item is: 7 #The Current item is: everything #while loop def sequence(n): while n!=1: #while n is NOT equal to 1 if n>1000: print("This number is too large"); break; #terminate the execution of the function elif n%2 == 0: print(n); n = n//2; else: print(n); n = n*3+1; # This concludes today's study.
true
1fca96cffc6a1fe5e1dfd942f592e900fddc39e0
sapphire008/Python
/PySynapse/archive/flow_chart_basic.py
2,642
4.28125
4
# -*- coding: utf-8 -*- """ This example demonstrates a very basic use of flowcharts: filter data, displaying both the input and output of the filter. The behavior of he filter can be reprogrammed by the user. Basic steps are: - create a flowchart and two plots - input noisy data to the flowchart - flowchart connects data to the first plot, where it is displayed - add a gaussian filter to lowpass the data, then display it in the second plot. """ # import initExample ## Add path to library (just for examples; you do not need this) from pyqtgraph.flowchart import Flowchart from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np import pyqtgraph.metaarray as metaarray app = QtGui.QApplication([]) ## Create main window with grid layout win = QtGui.QMainWindow() win.setWindowTitle('pyqtgraph example: Flowchart') cw = QtGui.QWidget() win.setCentralWidget(cw) layout = QtGui.QGridLayout() cw.setLayout(layout) ## Create flowchart, define input/output terminals fc = Flowchart(terminals={ 'dataIn': {'io': 'in'}, 'dataOut': {'io': 'out'} }) w = fc.widget() ## Add flowchart control panel to the main window layout.addWidget(fc.widget(), 0, 0, 2, 1) ## Add two plot widgets pw1 = pg.PlotWidget() pw2 = pg.PlotWidget() layout.addWidget(pw1, 0, 1) layout.addWidget(pw2, 1, 1) win.show() ## generate signal data to pass through the flowchart data = np.random.normal(size=1000) data[200:300] += 1 data += np.sin(np.linspace(0, 100, 1000)) data = metaarray.MetaArray(data, info=[{'name': 'Time', 'values': np.linspace(0, 1.0, len(data))}, {}]) ## Feed data into the input terminal of the flowchart fc.setInput(dataIn=data) ## populate the flowchart with a basic set of processing nodes. ## (usually we let the user do this) plotList = {'Top Plot': pw1, 'Bottom Plot': pw2} pw1Node = fc.createNode('PlotWidget', pos=(0, -150)) pw1Node.setPlotList(plotList) pw1Node.setPlot(pw1) pw2Node = fc.createNode('PlotWidget', pos=(150, -150)) pw2Node.setPlot(pw2) pw2Node.setPlotList(plotList) fNode = fc.createNode('GaussianFilter', pos=(0, 0)) fNode.ctrls['sigma'].setValue(5) fc.connectTerminals(fc['dataIn'], fNode['In']) fc.connectTerminals(fc['dataIn'], pw1Node['In']) fc.connectTerminals(fNode['Out'], pw2Node['In']) fc.connectTerminals(fNode['Out'], fc['dataOut']) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
true
9adee9b38a36060bc32fb1ab396ecb4304fc66fa
albertkowalski/100-days-of-code
/day_7/day-7.py
1,013
4.125
4
# Hangman Game # Made using strings instead of lists import random import hangman_words import art print(art.logo) word = random.choice(hangman_words.word_list) word_underscored = "" for letter in word: word_underscored += "_" print(f"Hidden word is: {word}") print(word_underscored) lives = 6 game_won = False while lives > 0: guess = input("Guess a letter: ").lower() if guess in word_underscored: print("You already guessed this letter") else: for index in range(len(word)): if guess == word[index]: word_underscored = word_underscored[:index] + word[index] + word_underscored[index+1:] if word == word_underscored: game_won = True break if guess not in word: print(f"There is no {guess} in the word. You lose a life") lives -= 1 print(f"{word_underscored} \n {art.stages[lives]}") if game_won: print("Congratulation, You won!") else: print("Game Over. You lost!")
true
19b203d6daeb61c8ba6dc64c0a778c868659e06c
redline-collab/Python-Basic-Programs
/Prime_interval.py
400
4.25
4
# Made by Vinay on 08 Sept 2021 print("Enter Range in Which you want to Find Prime Numbers!") start = int(input("Start:")) end = int(input("End:")) print("Prime Numbers in Given Range are:") for num in range(start, end+1): # as 1 is neither prime or composite if num > 1: for d in range(2,num): if (num % d)==0: break else: print(num)
true
fb28c4236c8fdd8df0ec9acaca71b6e294ed13b7
pcaa3000/CodingChallenge
/6_calculadora.py
1,142
4.125
4
def sum(val1,val2): return val1+val2 def substraccion(val1,val2): return val1-val2 def multiplication (val1,val2): return val1*val2 def division (val1,val2): return val1/val2 operators={ '/': division, '*': multiplication, '-': substraccion, '+': sum } def math_operation(operator, val1,val2): operation=operators.get(operator,"nothing") return operation(val1,val2) print('Calculadora\n') print(f'Ingrese su operación Mátemática Ej. \n\t10\n\t +\n\t2\n{"_"*20}\n') try: value=float(input('\t')) operator=input('\t ') while(operators.get(operator,"Invalid")!="Invalid"): try: value2=float(input('\t')) value=math_operation(operator,value,value2) print(f'\t{"_"*5}') print(f'\n\t{value}\n') operator=input('\t ') except ValueError as e: print(e) break except ValueError as e: print(e) # result=input('Ingrese su operación Mátemática Ej. 10+2\n\t') # try: # result=eval(result) # print(f'\t= {result}\n') # except ValueError as e: # print(e)
false