blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4ba3b805b355b6dc78930dca04365338186e398a
xb45666/python-exercise
/4.py
270
4.3125
4
def maxsum(a,b,c=2): """ return the biggest sum between any 2 numbers among a,b,c. >>> maxsum(1,2,3) 5 """ sum1=a+b sum2=b+c sum3=a+c return max(sum1,sum2,sum3) print(maxsum(1,2,3),1,2,3,sep='\n') negativesum = lambda a,b : -(a+b) print(negativesum(2,3))
true
c983ce31a63668e0efbb2cb7d28d26a8b7547636
kumar-abhishek/interview-questions-1
/2014-2015/Shape Onsite/bstCheck.py
2,147
4.3125
4
# Write a function to verify if you have a binary search tree """ BST Node Class """ class Node: def __init__(self, val): self.value = val self.left = None self.right = None def __repr__(self): return "NODE: val = "+str(self.value)+"\nLEFT: "+str(self.left)+"\nRIGHT: "+str(self.right) class BST: def __init__(self): self.root = None def add(self, value): newNode = Node(value) if self.root == None: self.root = newNode return cur = self.root parent = None left = False while (cur != None): parent = cur if value < cur.value: cur = cur.left left = True else: cur = cur.right left = False if left: parent.left = newNode else: parent.right = newNode """ Method: isBST -------------------------- Parameters: root - the root of the specified BST represented as a BST node Returns: True or False depending on whether the specified BST is valid or not -------------------------- """ def isBST(root): def recurse(cur, low, high): if cur == None: return True left = False right = False if cur.value > low and cur.value < high: left = recurse(cur.left, low, cur.value) right = recurse(cur.right, cur.value, high) return (left and right) else: return False return recurse(root, float("-inf"), float("inf")) """ Method: printTree A rudimentary method of printing the tree level by level -------------------------- Parameters: root - the root of the specified BST represented as a BST node Returns: N/A -------------------------- """ def printTree(root): thislevel = [root] while thislevel: nextlevel = list() for n in thislevel: print n.value, if n.left: nextlevel.append(n.left) if n.right: nextlevel.append(n.right) print thislevel = nextlevel """ Simple testing framework to create a tree and then test its validity """ tree = BST() tree.add(5) tree.add(8) tree.add(6) tree.add(1) tree.add(9) tree.add(10) tree.add(-2) tree.add(12) tree.add(7) # make tree invalid tree.root.right.right.value = -2 print isBST(tree.root)
true
81cb7cbf13e1782b65545aed5c5696b55fdd01fe
LOKESH538/Python
/Assignment-1/AddInteger.py
279
4.15625
4
""" Write a program that reads an integer between 100 and 1000 and adds all the digits in the integer. ( ex: input 745 # output =16 (7+4+5) ) """ num=(input("Enter an integer between 100 and 1000 :")) sum=0 for digit in num: sum = sum + int(digit) print(int(sum))
true
a84ccb1ec357cee8a23b6041170a1e9ed7d3c471
LadyBankhead/gitlab-gitrepo1
/class Customer.py
1,900
4.34375
4
class Customer " Contains properties for first name, last name and email address." def __init__(self, first_name, last_name, cust_email): self.first_name = first_name self.last_name = last_name self.cust_email = cust_email first_name = input('Please enter your first name: ') last_name = input('Please enter your last name: ') cust_email = input('Please enter your email: ') print(f' {first_name}{last_name}, (email)') class OrderLineItem "Contains properties for number, unit cost, and unit_quantity" def __init__(self, part_number, unit_cost, quantity): self.part_number = part_number self.unit_cost = unit_cost self.unit_quantity = unit_quantity part_number = def get_part_number(): """Part numbers available.""" list_of_part_numbers = ['screwdriver':001, 'hammer':002, 'nails':003 ] class ItemToPurchase: def __init__(self, name, price, quantity): self.item_name = name self.item_price = price self.item_quantity = quantity def get_item_cost(self): return self.item_price * self.item_quantity def add_items(self, ItemToPurchase): self.shopping_cart.append(ItemToPurchase) def remove_items(self, name): for i in self.shopping_cart: if (i.item_name == name): self.shopping_cart.remove(i) return True return False def checkOut(self): print("Customer Name: " + self.get_customer_name()) print("Shopping Date: " + self.get_shopping_date()) totalAmount = 0 for i in self.shopping_cart: print(str(i.item_quantity) + ' ' + i.item_name + ' @ '+ str(i.item_price)) totalAmount = totalAmount + i.get_item_cost() print('Total Amount: ' + str(totalAmount))
true
be64aa29052953b4554ad39bfdc0e4d3fe92eed2
GouriPan-Git/DataScience
/UtilityCode/LearnPythonLoopsBranching.py
1,411
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 21 18:53:27 2021 @author: gouri """ #Conditions and Branching # Write an if statement to determine if an album had a rating greater than 8. #Test it using the rating for the album “Back in Black” that had a rating of 8.5. #If the statement is true print "This album is Amazing!" album_rating=8.5 if album_rating>8: print("This album is Amazing") #Write an if-else statement that performs the following. #If the rating is larger then eight print “this album is amazing”. #If the rating is less than or equal to 8 print “this album is ok”. album_rating=8 if album_rating>8: print("This album is Amazing") else: print("This album is Ok") # Write an if statement to determine if an album came out before 1980 # or in the years: 1991 or 1993. If the condition is true # print out the year the album came out. album_release_year = 1991 if(album_release_year<1980) or (album_release_year==1991) or (album_release_year==1993): print("The album was released in the year ", album_release_year) #Loops For and while # For loop example dates = [1982,1980,1973] N = len(dates) for i in range(N): print(dates[i]) # Example of for loop for i in range(0, 8): print(i) dates = [1982,1980,1973] for year in dates: print(year)
true
45b31e7ade44e06f5f38b895d80a8eeb64091049
nannanitinkumar/Project1
/hackerrankList2.py
1,589
4.125
4
def insert_list(base_list,dest_list): base_list.insert(int(dest_list[1]),int(dest_list[2])) return base_list def append_list(base_list,dest_list): base_list.append(int(dest_list[1])) return base_list def extend_list(base_list,dest_list): dest_list = dest_list[1:] for i in dest_list: base_list.extend(int(i)) return base_list def remove_list(base_list,dest_list): base_list.remove(int(dest_list[1])) return base_list def pop_list(base_list): base_list.pop() return base_list def sort_list(base_list): base_list.sort() return base_list def reverse_list(base_list): base_list.reverse() return base_list def print_list(base_list): print base_list return base_list N = input() base_list = [] for i in range(0,N): dest_list = raw_input() dest_list = dest_list.split() if dest_list[0] == "insert": base_list = insert_list(base_list,dest_list) elif dest_list[0] == "append": base_list = append_list(base_list,dest_list) elif dest_list[0] == "extend": base_list = extend_list(base_list,dest_list) elif dest_list[0] == "remove": base_list = remove_list(base_list,dest_list) elif dest_list[0] == "pop": base_list = pop_list(base_list) elif dest_list[0] == "sort": base_list = sort_list(base_list) elif dest_list[0] == "reverse": base_list = reverse_list(base_list) elif dest_list[0] == "print": base_list = print_list(base_list) else: pass
false
8a75a1b08f91d5ae6ff86b45c63a21996f394fb4
2dam-spopov/di
/P5_Sergey/P5_Sergey-6.py
1,401
4.34375
4
#!/usr/bin/python3 # Escriba​ ​un​ ​programa​ ​que​ ​permita​ ​crear​ ​una​ ​lista​ ​de​ ​palabras​ ​y​ ​que,​ ​ # a​ ​continuación,​ ​cree​ ​una segunda​ ​lista​ ​igual​ ​a​ ​la​ ​primera,​ ​pero​ ​al​ ​ # revés​ ​(no​ ​se​ ​trata​ ​de​ ​escribir​ ​la​ ​lista​ ​al​ ​revés,​ ​sino​ ​de crear​ ​una​ ​ # lista​ ​distinta). # 1-Inicialización de variables. # 2-Pregunta e introducción de número de palabras en la lista. # Se usa control de error de excepción, si no se entroduce un # número entero mayor que 0 el programa sigue preguntando. # 3-Creación de la lista con valores introducidos. # 4-Inversión de la lista y guardada en lista 2. #1# lista = [] #2# while True: try: numPalabras = int(input("Dime cuántas palabras tiene la lista: ")) if numPalabras == 0 or numPalabras < 0: print("Debes introducir un número mayor que 0") continue break except ValueError: print("Debes introducir un número entero") #3# if numPalabras > 0: for i in range(0, numPalabras): palabra = input("Dígame la palabra " + str(i+1) + ": ") lista.append(palabra) print("La lista creada es: ", lista) #4# lista2 = lista[::-1] print("La lista inversa es:", lista2)
false
5bd577375967644d72823776de1cf804efa9f61d
2dam-spopov/di
/CURSO PYTHON-PÍLDORAS/practicaListas.py
694
4.25
4
miLista=["juan", "Jose", "Maria", "Antonio"] #Anade al final miLista.append("Sandra") #Inserta en la posicion deseada miLista.insert(2,"Julia") #Anade varios al final miLista.extend(["Ana", "Carlos"]) #Imprime toda la lista print(miLista[:]) #Borra la poscion deseada miLista.remove(miLista[2]) #Borra el ultimo miLista.pop() print(miLista[:]) #Muestra la posicion de un elemento print(miLista.index("Maria")) #Confirma si esta o no en la lista print("Antonio" in miLista) miLista2=["Kento","Marhuenda"] miLista3=miLista+miLista2 print(miLista3[:]) #Cuenta las veces que esta lo que buscamos print(miLista.count("Maria")) #Dice cuantos elementos hay en la lista print(len(miLista3))
false
64433b1424725fe533a496fcff8834185e2248ea
downtown12/mywaytogetajob
/leetcode/valid-sudoku.py
1,219
4.21875
4
''' The uses of Hashmap in this problem are: Maps the status of whether a number has occured or not to boolean list. I create three lists to record the true-or-false status of a number has occured in a line, a row, or a 3*3-grid. Each list of the three has 9 element. A number in the sudoku table maps to the index that equals to number's value -1 of the list. So it is an index-to-value map. ''' class Solution: # @param {character[][]} board # @return {boolean} def isValidSudoku(self, board): num_row = [[False] * 9 for i in range(9)] num_col = [[False] * 9 for i in range(9)] num_grid = [[False] * 9 for i in range(9)] for i in range(9): for j in range(9): if board[i][j] == '.': continue cur = int(board[i][j]) #already occurs if num_row[i][cur-1] or num_col[j][cur-1] or num_grid[(i/3)*3+j/3][cur-1]: return False num_row[i][cur-1] = True num_col[j][cur-1] = True num_grid[(i/3)*3+j/3][cur-1] = True return True
true
169bb44aa8bc275d21f0eafc53537153a72c97c2
elliele/data-structures_and_algorithms
/ch_03/disjoint.py
1,221
4.28125
4
# Created by Ellie Le at 4/13/2021 """ Suppose we are given three sequences of numbers, A, B, and C. We will assume that no individual sequence contains duplicate values, but that there may be some numbers that are in two or three of the sequences. The three-way set disjointness problem is to determine if the intersection of the three sequences is empty, namely, that there is no element x such that x ∈ A, x ∈ B, and x ∈ C. """ def disjoint1(A, B, C): """Return True if there is no element common to all three lists.""" for a in A: for b in B: for c in C: if a == b == c: return False # we found a common value return True # if we reach this, sets are disjoint def disjoint2(A, B, C): """Return True if there is no element common to all three lists.""" for a in A: for b in B: if a == b: for c in C: # only check C if we found match from A and B if a == c: # (and thus a == b == c) return False # we found a common value return True # if we reach this, sets are disjoint
true
eb11a69f40c7cd77804e70f54d8ff77281e56939
aniketambasta/Docker_project
/docker_python_project.py
2,510
4.1875
4
import os print("hello and welcome to my world") print("enter your name:") name = input() print("""welcome {} choose an option below""" .format(name)) while True: print("""press 1 for see the live date and time press 2 to see the desired year of calendar press 3 to add anew user in your os press 4 to add any two no. press 5 to subtract any two no. press 6 to multiply any two no. press 7 to divide any two no. press 8 to check whether the no. is armstrong no. or not press 9 to exit""") inp = input() if int(inp) ==1: print ("hey") x=os.system('date') print (x) elif int(inp) == 2: print ("enter the month and year to see the calendar") month = input("month") year = input("year") cal = "cal {0} {1}".format(month,year) os.system(cal) elif int(inp) == 3: print ("enter the name you want to create a new user") user_name = input("user name") new_user = "useradd {}".format(user_name) os.system(new_user) elif int(inp) == 4: print("enter the two numbers to be added") no_1 = input("enter the no. 1-:") no_2 = input("enter the no. 2-:") sum = float(no_1) + float(no_2) print("addition of{0} & {1} is {2}".format(no_1,no_2,sum)) elif int(inp) ==5: print("enter the numbers to subtract-:") s1 = input("enter no.1-:") s2 = input("enter no.2-:") subtract = float(s1) - float(s2) print("subtraction of {0} & {1} is {2}-:".format(s1,s2,subtract)) elif int(inp) == 6: print("enter the numbers to multiply-:") m1 = input("enter the no.1-:") m2 = input("enter the no.2-:") product = float(m1) * float(m2) print("product of {0} & {1} is {2}-:".format(m1,m2,product)) elif int(inp) == 7: print("enter the numbers to divide-:") d1 = input("enter the no.1-:") d2 = input("enter the no.2-:") divide = float(d1) / float(d2) print("{0} / {1} is {2}-:".format(d1,d2,divide)) elif int(inp) == 8: print("enter the no. to check") num = int(input("no.=")) su = 0 temp = num while temp > 0: digit = temp % 10 su += digit ** 3 temp //= 10 if num==su: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") else : break
true
5cadc21f0ce45b88182a601c3a6bdb481b70833e
javajael/guessing-game
/game.py
1,852
4.15625
4
"""A number-guessing game.""" import random def get_valid_user_input(message): guess = None try: guess = int(input(message)) except ValueError: print("Not a number, silly!") return guess print("Howdy, what's your name?") user_name = input("(type in your name) ") print(f"{user_name} I'm thinking of a number between 1 and 100.") print("Try to guess my number.") rand_num = random.randrange(101) guess = get_valid_user_input("Your guess? ") guess_count = 1 while guess is None: guess = get_valid_user_input("Please enter a real number: ") guess_count += 1 while guess < 1 or guess > 100: print("That's not between 1 and 100 silly!") guess = get_valid_user_input( f"Please enter a valid number between 1 and 100: ") guess_count += 1 while True: if guess is None: guess = get_valid_user_input("Please enter a real number: ") if guess < 1 or guess > 100: print("That's not between 1 and 100 silly!") guess = get_valid_user_input( f"Please enter a valid number between 1" f"and 100: ") if guess == rand_num: print( f"Well done, {user_name}!" f" You found my number in {guess_count} tries!" ) break if guess < rand_num: print("Your guess is too low, try again.") elif guess > rand_num: print("Your guess is too high, try again.") guess = get_valid_user_input("Your guess? ") guess_count += 1 while guess is None: guess = get_valid_user_input("Please enter a real number: ") guess_count += 1 while guess < 1 or guess > 100: print("That's not between 1 and 100 silly!") guess = get_valid_user_input( f"Please enter a valid number " f"between 1 and 100: ") guess_count += 1
true
e0d06eea58f82f5e56708922051bfe88a7467224
XelaNosnibor/CeasarCipherEncryptDecrypt
/CeasarCipherEncryptDecrypt.py
1,203
4.625
5
# Caesar Cipher Encrypt / Decrypt #sets mode to either encryption or decryption of the ceasar cipher mode = input("Enter 'encrypt' for encryption or enter 'decrypt' for decryption mode: ") #key - set to '13' for ceasar cipher key = 13 #ciphertext or plaintext to be used message = input("Enter text: ") #Symbols/letters that can be used in the cipher SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' #store the encrypted/decrypted form of the message translated = '' for symbol in message: if symbol in SYMBOLS: symbolIndex = SYMBOLS.find(symbol) #Perform encryption or decryption if mode == 'encrypt' or 'Encrypt' or 'e' or 'E': translatedIndex = symbolIndex + key elif mode == 'decrypt' or 'Decrypt' or 'd' or 'D': translatedIndex = symbolIndex - key if translatedIndex >= len(SYMBOLS): translatedIndex = translatedIndex - len(SYMBOLS) elif translatedIndex < 0: translatedIndex = translatedIndex + len(SYMBOLS) translated = translated + SYMBOLS[translatedIndex] else: translated = translated + symbol #output result of decryption or encryption print(translated)
true
8f3c4f32742f4310769bfae79d8cdfcb5a5f58d5
jbial/daily-coding
/dailycoding037.py
1,356
4.375
4
""" This problem was asked by Google. The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. solution: Use a divide and conquer approach by recusively including all subsets missing one element from the original set, e.g. {1,2,3} -> {2,3} -> {2}, {3} {1,3} -> {1}, {3} {1,2} -> {1}, {2} To avoid adding duplicates to power set, use the powerset as a memoization table, passing it along every recursion and only adding to it if a subset is not already in it. Runs in O(2^N) time since that is the cardinality of the power set """ def subset(nums, k, size): return [nums[i] for i in range(size) if i != k] def powerset_rec(nums, pset): if set(nums) in pset: return pset.append(set(nums)) for i in range(len(nums)): s = subset(nums, i, len(nums)) powerset_rec(s, pset) def powerset(nums): pset = [] powerset_rec(list(nums), pset) return pset def main(): tests = ( (set(), [set()]), ({1,2,3}, [set(),{1},{2},{3},{1,2},{2,3},{1,3},{1,2,3}]), ({1}, [set(), {1}]), ({1,2}, [set(), {1,2}, {1}, {2}]) ) if all([s in t[1] for s in powerset(t[0])] for t in tests): print("Passed") else: print("Failed") if __name__ == '__main__': main()
true
f8c594319fb5c1c62549e019586ede35145e1e4b
jbial/daily-coding
/dailycoding047.py
1,336
4.1875
4
""" This problem was asked by Facebook. Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it. For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars. solution: If plotted as a time series, the maximum profit corresponds to the difference between the lowest valley and the highest peak. So we can keep track of the min price and max difference as variables and find the max profit in one pass. """ def maximum_profit(index): """Finds the maximum profit in one pass """ if not index or len(index) < 2: return min_price = index[0] max_diff = -1e99 for price in index[1:]: if price - min_price > max_diff: max_diff = price - min_price if price < min_price: min_price = price return max_diff def main(): tests = { 5: [9,11,8,5,7,10], 4: [1,2,3,4,5], 0: [1,1,1], 1: [1,1,2,1], -1: [5,4] } if all(maximum_profit(tests[k]) == k for k in tests): print("Passed") else: print("Failed") if __name__ == '__main__': main()
true
d8963f4b65420f5e6e89bbf4833a3f9aad133aa9
jbial/daily-coding
/dailycoding065.py
2,047
4.53125
5
""" This problem was asked by Amazon. Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. For example, given the following matrix: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] You should print out the following: 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 Solution: Print each row/col in a clockwise manner, decrementing/incrementing the row/col index to print until """ def print_spiral(arr): # indices of the row and columns to begin printing from last_row, last_col = len(arr), len(arr[0]) first_row = first_col = 0 while first_row < last_row and first_col < last_col: # print left to right row for j in range(last_col): print(arr[first_row][j], end=" ") first_row += 1 # print top to bottom col for i in range(first_row, last_row): print(arr[i][last_col - 1], end=" ") last_col -= 1 # print right to left row if first_row < last_row: for j in range(last_col - 1, first_col - 1, -1): print(arr[last_row - 1][j], end=" ") last_row -= 1 # print bottom to top col if first_col < last_col: for i in range(last_row - 1, first_row, -1): print(arr[i][first_col], end=" ") first_col += 1 # print empty line print() def main(): test1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] test2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] def print_arr(arr): for row in arr: print(row) print() print("Test 1: ") print_arr(test1) print("Spiral Test 1: ") print_spiral(test1) print() print("Test 2: ") print_arr(test2) print("Spiral Test 2: ") print_spiral(test2) print("\nPassed") if __name__ == '__main__': main()
true
73f8efc7c54bdd5898e667ffaaaf5f5da3a79b49
songkane/leetcode
/191.py
337
4.21875
4
#-*- coding: utf-8 -*- ''' Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. ''' n=1 i=0 while n: i = i + n%2 n=n>>1 print i
true
c0cb949f8a202973a2d2976fc3fe540e1d271134
mickiyas123/Python-100-Exercise-Challenge
/80_Advancde_Password_Checker.py
886
4.21875
4
#Create a script that lets the user submit a password until they have satisfied three conditions: #1. Password contains atleast one number #2. Contains one uppercase letter #3. It is at least 5 chars long # Give the exact reason why the user has not created a correct password while True: notes = [] passwd = input("Enter new password: ") if not any(char.isdigit() for char in passwd): notes.append("You need at least one number") if not any(char.isupper() for char in passwd): notes.append("You need at least one uppercase letter") if len(passwd) < 5: notes.append("You need at least 5 characters") if len(notes) == 0: print("password is fine") break else: print("Password check the following:") for index,vlaue in enumerate(notes): print(str(index + 1) , vlaue)
true
c7e5593464895f2778b0137c258b2f5ec9d8c41e
MaxSaunders/1aDay
/rotateLeft3.py
399
4.3125
4
""" Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] """ def rotate_left3(nums): temp = nums[0] for i in range (len(nums) - 1): nums[i] = nums[i + 1] nums[len(nums) - 1] = temp return nums
true
450471ab8d681a408981cef4802218e60a551ab5
samdeanefox/hackerrank
/trees/is_bst.py
2,350
4.21875
4
""" Check out the resources on the page's right side to learn more about binary search trees. The video tutorial is by Gayle Laakmann McDowell, author of the best-selling interview book Cracking the Coding Interview. For the purposes of this challenge, we define a binary search tree to be a binary tree with the following properties: The value of every node in a node's left subtree is less than the data value of that node. The value of every node in a node's right subtree is greater than the data value of that node. The value of every node is distinct. For example, the image on the left below is a valid BST. The one on the right fails on several counts: - All of the numbers on the right branch from the root are not larger than the root. - All of the numbers on the right branch from node 5 are not larger than 5. - All of the numbers on the left branch from node 5 are not smaller than 5. - The data value 1 is repeated. Given the root node of a binary tree, determine if it is a binary search tree. Function Description Complete the function checkBST in the editor below. It must return a boolean denoting whether or not the binary tree is a binary search tree. checkBST has the following parameter(s): root: a reference to the root node of a tree to test Input Format You are not responsible for reading any input from stdin. Hidden code stubs will assemble a binary tree and pass its root node to your function as an argument. Constraints Output Format Your function must return a boolean true if the tree is a binary search tree. Otherwise, it must return false. Sample Input image Sample Output Yes Explanation The tree in the diagram satisfies the ordering property for a Binary Search Tree, so we print Yes. """ # Enter your code here. Read input from STDIN. Print output to STDOUT class Node: def __init__(self,info): self.info = info self.left = None self.right = None """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def checkBST(root, min=0, max=10000): if not root: return True if root.data > min and root.data < max and checkBST(root.left,min,root.data) and checkBST(root.right,root.data,max): return True else: return False
true
36ae2ff44135f4eaa4059b867e2e8bc2be0e636e
PrabhatiG/Python
/Activity10.py
310
4.25
4
# Given tuple #num_tuple=(10,20,33,46,55) num_tuple=tuple(input("Enter a list of comma seperated values: ").split(",")) print("Given list is:",num_tuple) # Print elements that are divisible by 5 print("Elements that are divisible by 5:") for num in num_tuple: if(num%5==0): print(num)
true
7f7057188dac48410059397acfaae589a90af639
PrabhatiG/Python
/Activity14.py
330
4.3125
4
def fibonacci(number): if number<=1: return number else: return(fibonacci(number-1)+fibonacci(number-2)) nterms=int(input("Enter a number: ")) if nterms<=0: print("Enter a positive number") else: print("Fibonacci Sequence: ") for i in range(nterms): print(fibonacci(i))
false
989c8fe086d1aa8d6784a8a3980d66077136217f
santiago0072002/Python_stuff
/SLLNodeexample.py
1,208
4.3125
4
#https://www.linkedin.com/learning/python-data-structures-linked-lists/coding-the-singly-linked-list-node-class class SLLNode: def __init__(self, data): self.data = data self.next = None def __repr__(self): return "SLLNode object: data={}".format(self.data) def get_data(self): """return self.data attribute""" return self.data def set_data(self, new_data): """Replaced the existing value of the self.data attribute with the new data parameter""" self.data = new_data def get_next(self): """ Return the self.next attribute""" return self.next def set_next(self, new_next): """Replaced the existing value of the self.next attribute with the new_next parameter""" self.next = new_next """ I want to highlight the fact that linked lists don't contain nodes. Instead, they have a head attribute that points to the first node of the linked list if one exists. Otherwise, the head attribute points to none. We'll need to keep this in mind as we code our link list Data Structure""" node = SLLNode("Apple") print(node.get_data()) node.set_data(7) print(node.get_data()) node2 = SLLNode("APPLE") node.set_next(node2) print(node.get_next())
true
2f7569dab12281a5fd9c3147fde4fff637fd8b17
santiago0072002/Python_stuff
/RockPaperSyGame.py
1,980
4.25
4
import random, sys print("ROCK, PAPER, SCISSORS") # variables to keep track of win, lose, or ties wins = 0 losses = 0 ties = 0 while True: print(f"wins {wins}, losses {losses}, ties{ties}") while True: print("enter your move : r for rock, p for paper, s for sissors or q to quit") player_move = input() if player_move == "q": sys.exit() if player_move == "r" or player_move == "s" or player_move == "p": break if player_move == "r": print("rock vs...") elif player_move == "p": print("paper vs...") elif player_move == "s": print("scissors vs ...") # this is what the computer picked randomNumber = random.randint(1, 3) if randomNumber == 1: computer_move = "r" print("ROCK!") elif randomNumber == 2: computer_move = "p" print("PAPER!") elif randomNumber == 3: computer_move = "s" print("SCISSORS!") if player_move == computer_move: print("it is a TIE!") ties += 1 elif player_move == "r" and computer_move == "s": print("You Win!") wins += 1 elif player_move == "p" and computer_move == "r": print("You Win!") wins += 1 elif player_move == "s" and computer_move == "p": print("You Win!") wins += 1 elif player_move == "r" and computer_move == "p": print("Computer Win!") losses+= 1 elif player_move == "p" and computer_move == "s": print("Computer Win!") losses+= 1 elif player_move == "s" and computer_move == "r": print("Computer Win!") losses+= 1 if wins == 3 or losses == 3: print("You scored!", wins, "the computer scored!", losses) if wins > losses: print("You Win!") else: print("The Computer won!") sys.exit()
false
4bd893ed1053830449b3b4335c5d15ee1b42257f
itayspay2/Python-Crossy_RPG_Game
/Crossy_RPG_Game/Basics/Objects_and_classes_Text.py
1,882
4.125
4
# Python language basics 7 # classes and objects # Class fields, methods, and constractors # Object instatiation # A class is just a blueprint that defines an objects attributes and behaviours class GameCharacter: # A field or a global variable (assinged this value when class is instantiated) speed = 5 # Constructor creates a new class instance and sets up the defined fields def __init__(self, name, width, height, x_pos, y_pos): self.name = name self.width = width self.height = height self.x_pos = x_pos self.y_pos = y_pos # A methos is just a function that typically modifies the classes fields def move(self, by_x_amount, by_y_amount): self.x_pos += by_x_amount self.y_pos += by_y_amount # charcter_0 is a new instance of the GameCharacter class character_0 = GameCharacter('char_0', 50, 100, 100, 100) ## this is an object! character_0.name # 'char_0' character_0.name = 'char_1' character_0.name # 'char_1' character_0.move(50,100) character_0.x_pos # 150 character_0.y_pos # 200 # Python language basics 8 # subclasses, superclasses, and inheritance # Player character is a subclass of GameCharacter # Player character has access to everything defined in GameCharacter class PlayerCharacter(GameCharacter): speed = 10 # Should still provide a constructor/initializer def __init__(self, name, x_pos, y_pos): super().__init__(name, 100, 100, x_pos, y_pos) def move(self, by_y_amount): super().move(0,by_y_amount) # player_character is a new instance of the PlayerCharacter Sub-class player_character = PlayerCharacter('P_character',500, 500) player_character.name # 'P_character' player_character.move(100) print(player_character.x_pos) #600 print(player_character.y_pos) #600
true
a9e80f004ca76dedc792d4a5a1e9651e4245a872
tatebury/w3d4hw
/exercises.py
1,857
4.125
4
# Exercise #1 # Reverse the list below in-place using an in-place algorithm. # For extra credit: Reverse the strings at the same time. words = ['this' , 'is', 'a', 'sentence', '.'] def rev_list(words): words.reverse() count = 0 for word in words: word_rev = word [::-1] words[count] = word_rev count += 1 return words # print(rev_list(words)) # Exercise #2 # Create a function that counts how many distinct words are in the string below, then outputs a dictionary with the words as the key and the value as the amount of times that word appears in the string. # Should output: # {'a': 5, # 'abstract': 1, # 'an': 3, # 'array': 2, ... etc... a_text = 'In computing, a hash table hash map is a data structure which implements an associative array abstract data type, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots from which the desired value can be found' def count_word_occurances(a_text): hist = {} for word in a_text.split(): word = word.strip(",.").lower() if word not in hist.keys(): hist[word] = 1 else: hist[word] += 1 return hist # print(count_word_occurances(a_text)) # Exercise #3 # Write a program to implement a Linear Search Algorithm. Also in a comment, write the Time Complexity of the following algorithm. # Hint: Linear Searching will require searching a list for a given number. list_to_search = [1,5,2,7,4,8,3,9,5,44,55,2,444,7,443,72,48,94] def linear_search(input_list, target): count = 0 for item in input_list: if item == target: return f"{target} is at index {count}." count += 1 return f"{target} is not in the list." # print(linear_search(list_to_search, 94)) #Time Complexity is O(n).
true
f74358ed2198122f910a6e48f4ee29fc66c9072d
swordinhand/learn_python
/checkio/scientific-expedition/triangle_angles.py
999
4.125
4
''' https://py.checkio.org/mission/triangle-angles/ 这题没什么难度,就是余弦定理和python一些math函数 cosA=(b^2+c^2-a^2)/2bc; cosB=(a^2+c^2-b^2)/2ac; cosC=(a^2+b^2-c^2)/2ab math.acos, math.degrees, round ''' def checkio(a, b, c): import math #replace this for solution if a + b <= c or a + c <= b or b + c= < a: return [0, 0, 0] cosa = (b*b + c*c - a*a)/(2*b*c) cosb = (a*a + c*c - b*b)/(2*a*c) cosc = (a*a + b*b - c*c)/(2*a*b) anglea = round(math.degrees(math.acos(cosa))) angleb = round(math.degrees(math.acos(cosb))) anglec = round(math.degrees(math.acos(cosc))) return sorted([anglea, angleb, anglec]) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio(4, 4, 4) == [60, 60, 60], "All sides are equal" assert checkio(3, 4, 5) == [37, 53, 90], "Egyptian triangle" assert checkio(2, 2, 5) == [0, 0, 0], "It's can not be a triangle"
true
7774a7d9f73bed06d6d9a90fc5c45ebd1becc187
jlevey3/CS112-Spring2012
/classcode/day06--code_formating/broken1.py
458
4.21875
4
#!/usr/bin/env python #edited variables for better names #define variables sum=0 input_list=[] input_number=None #while loop gets inputs and appends them to list of nums while input_number != "": input_number = raw_input() if input_number.isdigit(): input_list.append(float(input_number)) #adds inputted numbers to sum for num in input_list: sum+=num #divides sum by number of numbers in list == average of list print sum/len(input_list)
true
89f7d9f85ab844d0f3c0ce4bc3cf831daead0652
jlevey3/CS112-Spring2012
/hw10/rects.py
1,514
4.1875
4
#!/usr/bin/env python """ rects.py Pygame Rectangles ========================================================= The following section will test your knowledge of how to use pygame Rect, arguably pygame's best feature. Define the following functions and test to make sure they work with `python run_tests.py` Make sure to use the documentation http://www.pygame.org/docs/ref/rect.html Terms: --------------------------------------------------------- Point: an x,y value ex: pt = 3,4 Polygon: a shape defined by a list of points ex: poly = [ (1,2), (4,8), (0,3) ] Rectangle: pygame.Rect """ from pygame import Rect # 1. poly_in_rect # Check to see if the polygon is completely within a given # rectangle. # # returns: True or False def poly_in_rect(poly, rect): "check if polygon is within rectangle" inside = False for (x,y) in poly: if rect.collidepoint((x,y)): inside = True else: inside = False return inside # 2. surround_poly # Create a rectangle which contains the given polygon. # It should return the smallest possible rectangle # where poly_in_rect returns True. # # returns: pygame.Rect def surround_poly(poly): "create a rectangle which surrounds a polygon" xmin, ymin = xmax, ymax = poly[0] for point in poly: x,y = point if x<=xmin: x=xmin if x>=xmax: x=xmax if y<=ymin: y=ymin if y>=ymax: y=ymax return Rect(xmin,ymin,(xmax-xmin+1),(ymax-ymin+1))
true
ce2a2633cc920e19833593e9a3d362325386f8c5
JDB0rg/Sorting
/src/recursive_sorting/recursive_sorting.py
1,613
4.28125
4
# 1. While your data set contains more than one item, split it in half # 2. Once you have gotten down to a single element, you have also *sorted* that element # (a single element cannot be "out of order") # 3. Start merging your single lists of one element together into larger, sorted sets # 4. Repeat step 3 until the entire data set has been reassembled # TO-DO: complete the helper function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [0] * elements # TO-DO i = 0 j = 0 for i in range(elements): if arrA[i] < arrB[j]: merged_arr.append(arrA[i]) i += 1 elif arrA[i] >= arrB[j]: merged_arr.append(arrB[j]) j += 1 elif i >= len(arrA): merged_arr.append(arrB[j]) j += 1 else: merged_arr.append(arrA[i]) i += 1 print("M", merged_arr) return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO if len(arr) > 1: low = merge_sort(arr[0: len(arr) / 2]) high = merge_sort(arr[len(arr) / 2: ]) arr = merge(low, high) return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr
true
da791dc9445930d27c31a8a9ff59288d9b2bcaca
kaistreet/python-practice-problems
/practicepython.org-problems/6_string_lists.py
684
4.46875
4
#Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) def palindrome_checker(): ask_user_word = str(input("Choose your word to check if it's a palindrome or not: ")) if ask_user_word == ask_user_word[::-1]: print('this is a palindrome') else: print("this isn't a palindrome") palindrome_checker() play_again = str(input('would you like to check again? [enter y or n]')) y = 'y' while play_again == y: palindrome_checker() play_again = str(input('would you like to check again? [enter y or n]: ')) y = 'y' else: print('have a good day!')
true
b82eefdab80d97411a3d783a6fef243efc6107dd
kaistreet/python-practice-problems
/edabit/area_of_triangle.py
306
4.15625
4
#Write a function that takes the base and height of a triangle and return its area. def area_of_triangle(): base = int(input('Enter base of triangle: ')) height = int(input('Enter height of triangle: ')) area = 0.5*base*height print('Area of triangle is '+str(area)+'.') area_of_triangle()
true
10c6e26d78b3ee960c0a14657afc6c661a173fbc
mnpitts/Python
/python_intro.py
1,976
4.5625
5
# python_intro.py """Python Essentials: Introduction to Python. <McKenna Pitts> <Math 345 Section 2> <September 4, 2018> """ pi = 3.14159 def sphere_volume(r): """Return the volume of a sphere for a determined radius""" return 4/3 * pi * r**3 def isolate(a, b, c, d, e): """Return five spaces between the first three numbers and one space between the last two""" print(a, b, sep = " ", end = " ") print (c, d, e, sep = " ") def first_half(str): """Return the first half of a string. Does not include the middle character there are an odd number of characters""" return str[:(len(str)//2)] def backward(str): """Return the string written backwards""" return str[::-1] def list_ops(): """Modifies a given list""" my_list = ["bear", "ant", "cat", "dog"] my_list.append("eagle") my_list[2] = "fox" my_list.pop(1) my_list.sort() my_list = my_list[::-1] my_list[my_list.index("eagle")] = "hawk" my_list[-1] = my_list[-1] + "hunter" return my_list def pig_latin(word): """Changes a word into pig latin""" if word[0] in "aeiou": return word + "hay" else: return word[1:] + word[0] + "ay" def palindrome(): """"Finds and returns the largest palindromic number made from the product of two 3-digit numbers""" m = 0 for i in range(999,1,-1): for j in range(999,1,-1): x = i * j y = str(x) if y == y[::-1]: if x > m: m = x return m def alt_harmonic(n): """Returns sum of alternating harmonic series""" return sum([1/n * (-1)**(n+1) for n in range(1, n + 1)]) if __name__ == "__main__": print("Hello, world!") print(sphere_volume(4)) isolate(1, 2, 3, 4, 5) print(first_half("Hello, world!")) print(backward("Hello")) print(list_ops()) print(pig_latin('racecar')) print(palindrome()) print(alt_harmonic(500000))
true
e23e8ff0260659cc528e6a8a4d568e3151673a0b
AnhquanNguyenn/PythonPracticeScripts
/Maximum Sum of Any Contiugous Subarray /maximum.py
785
4.34375
4
def maximum(numbers): # if the maximum number in the list is less than 0, then we simply # output a zero, or if we have an empty list as well if not numbers or max(numbers) < 0: return 0 # Setting temporary max values, and change them as we progress # through the array currentMax = numbers[0] overallMax = numbers[0] # iterating through the list, to find the current and overall max as # we add numbers to the current max, and compare it to the overall max for num in numbers[1:]: currentMax = max(num, currentMax + num) overallMax = max(overallMax, currentMax) return overallMax numbers = [34, -50, 42, 14, -5, 86] print(maximum(numbers)) numbers = [-5, -1, -8, -9] print(maximum(numbers))
true
5def1164c44cbbbc40e1173c3ed71a2c646e9320
AnhquanNguyenn/PythonPracticeScripts
/Longest Palindromic Contiguous Substring/longestPalindrome.py
597
4.21875
4
def isPalindrome(word): if word == word[::-1]: return True else: return False def longestPalindrome(word): if not word or isPalindrome(word): return word # After the first letter, and before the last letters substring1 = longestPalindrome(word[1:]) substring2 = longestPalindrome(word[:-1]) # find the longer of the substrings if len(substring1) > len(substring2): return substring1 else: return substring2 word = "aabcdcb" print(longestPalindrome(word)) word = "bananas" print(longestPalindrome(word))
true
416d89710b5b9c1832e50a9cbeee5c8ab34016b0
AnhquanNguyenn/PythonPracticeScripts
/Reverse Words in a String/reverse.py
590
4.28125
4
def reverse(sentence): # Keep a variable for storing the reversed words in each strign reversedString = "" # splitting the sentence into individual words words = sentence.split(' ') # Iterating through each loop and joining the reversed version of each word to the # reversedString along with a space to separate each word. for word in words: reversedString += ("".join(reversed(word))) reversedString += ("".join(" ")) return reversedString sentence = "The cat in the hat" print(sentence) print(reverse(sentence))
true
4b584c1ab47c557f0ed400c563d31a2425132a21
AnhquanNguyenn/PythonPracticeScripts
/Symmetric K-ary Tree/symmetric.py
1,461
4.28125
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None # to be symmetric, they must have the same values in each subtree but a mirror image # of one another def isSymmetric(root): return isMirror(root, root) def isMirror(root1, root2): # Empty trees are symmetric if root1 is None and root2 is None: return True if root1 is not None and root2 is not None: if root1.value == root2.value: return (isMirror(root1.left, root2.right) and isMirror(root1.right, root2.left)) return False root = Node(1) root.left = Node(2) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(4) root.right.left = Node(4) root.right.right = Node(3) if isSymmetric(root) == True: print("The Tree is Symmetric") else: print("The Tree is not Symmetric") root = Node(4) root.left = Node(3) root.right = Node(3) root.left.left = Node(9) root.left.right = Node(1) root.right.left = Node(1) root.right.right = Node(9) if isSymmetric(root) == True: print("The Tree is Symmetric") else: print("The Tree is not Symmetric") root = Node(None) if isSymmetric(root) == True: print("The Tree is Symmetric") else: print("The Tree is not Symmetric") root = Node(1) root.left = Node(2) root.right = Node(3) if isSymmetric(root) == True: print("The Tree is Symmetric") else: print("The Tree is not Symmetric")
true
72dad272f5042901380289f71aaaf863ee497840
AnhquanNguyenn/PythonPracticeScripts
/Letter Swapping and Reordering/reordering.py
1,436
4.25
4
# Standard swapping mechanism within arrays, having a temporary variable to hold the # the results of the swapping def swapping(array, startIndex, endIndex): temp = array[startIndex] array[startIndex] = array[endIndex] array[endIndex] = temp # Returns the last letter index once all the letters of a specific character are found def pullToTheFront(array, startIndex, endIndex, letter): lastLetterIndex = -1 while startIndex < endIndex: # we have found the letter, update start index and last letter indexes if array[startIndex] == letter: lastLetterIndex = startIndex startIndex += 1 # Just increment through to find letters that we need elif array[endIndex] != letter: endIndex -= 1 # Swapping the letters once they have been organized properly else: lastLetterIndex = startIndex swapping(array, startIndex, endIndex) return lastLetterIndex # This method pulls to the front Rs, then Gs, and the remaining will be Bs def reorder(array): # Rs will be pulled first lastIndex = pullToTheFront(array, 0, len(array) - 1, 'R') # Gs will be next, but the starting point is the last index of all the Rs pullToTheFront(array, lastIndex + 1, len(array) - 1, 'G') return array array = ['G', 'B', 'R', 'R', 'B', 'R', 'G'] print(array) print(reorder(array))
true
38a331e8ae098fb97df1bd30cb36ed84a973158f
robytoby154/PythonProjects
/caesar_shift_encryption.py
1,086
4.375
4
from string import * #Loading the string module def process_shift(text = '', shift = 0): #Defining the process_shift function for reusability try: shift = int(shift) #Making sure that an integer was input for the shift value text = str(text) #Making sure that a string was input for the text to encode except: return result = '' letters = ascii_lowercase + ' ' for x in range(len(text)): tempshift = letters.find(text[x].lower()) + shift while tempshift < 0 or tempshift >= len(letters): if tempshift < 0: tempshift += len(letters) else: tempshift -= len(letters) result += letters[tempshift] return result def section_separator(): return '~~~~~~~~~~~~~~~~~~~' while(1): print(section_separator()) text = input('Message to shift: ') shift = input('Factor to shift by (integer): ') result = process_shift(text, shift) if result != None: print('Result: ' + result) continue print('Invalid input, please try again')
true
8435c54f79ac69801097557070cfb5528c7f7bf2
cjolson1/googlefoobar
/PeculiarBalance.py
1,675
4.34375
4
""" Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit population is at stake, so Beta reads the challenge: There is a scale with an object on the left-hand side, whose mass is given in some number of units. Predictably, the task is to balance the two sides. But there is a catch: You only have this peculiar weight set, having masses 1, 3, 9, 27, ... units. That is, one for each power of 3. Being a brilliant mathematician, Beta Rabbit quickly discovers that any number of units of mass can be balanced exactly using this set. To help Beta get into the room, write a method called answer(x), which outputs a list of strings representing where the weights should be placed, in order for the two sides to be balanced, assuming that weight on the left has mass x units. The first element of the output list should correspond to the 1-unit weight, the second element to the 3-unit weight, and so on. Each string is one of: "L" : put weight on left-hand side "R" : put weight on right-hand side "-" : do not use weight To ensure that the output is the smallest possible, the last element of the list must not be "-". x will always be a positive integer, no larger than 1000000000. """ from math import log def answer(x): order = [] step = int(log(x * 2, 3)) + 1 for n in range(step): y = round(float(x / (3.0 ** n))) % 3 if y == 1: order.append("R") elif y == 2: order.append("L") else: order.append("-") return order
true
16fadea06d89c7bd664d61fd2a3be95d130532d1
mazhou/python
/my_extendsClass.py
2,451
4.125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- class Parent: # 定义父类 parentAttr = 100 def __init__(self): print "调用父类构造函数" def parentMethod(self): print '调用父类方法' def myMethod(self): print '调用父类方法' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "父类属性 :", Parent.parentAttr class Child(Parent): # 定义子类 def __init__(self): print "调用子类构造方法" def childMethod(self): print '调用子类方法 child method' class Child(Parent): # 定义子类 def myMethod(self): print '调用子类方法' c = Child() # 实例化子类 c.myMethod() # 子类调用重写方法 c.childMethod() # 调用子类的方法 c.parentMethod() # 调用父类方法 c.setAttr(200) # 再次调用父类的方法 c.getAttr() # 再次调用父类的方法 #__repr__( self ) 转化为供解释器读取的形式 #__str__( self ) 用于将值转化为适于人阅读的形式 #__cmp__ ( self, x ) 对象比较 class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2 #__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs #__private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.publicCount #print counter.__secretCount # 报错,实例不能访问私有变量 #__foo__: 定义的是特列方法,类似 __init__() 之类的。 #_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import * #__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
false
6a3e68a638a7671885d969f63205892a4846450c
ankita2002/College-Python-codes
/Experiment 3/String Sorting.py
355
4.125
4
print("*************String Sorting*****************") n = int(input("Enter the length of Array: ")) print("Enter ",n,"elements in the array: ") strs = ["" for _ in range(n)] x =[] for i in range(0,n): x.append(input("Enter String Value: ")) print("Input Array: ",x) x.sort() for i in range(0,n): strs[i]=x[i] print("Array after sorting: ", strs)
true
21cda891f9ab38ada0f0be1897adc7e44101e9f4
sagarwagh1/Simple_Chatty_Bot
/Problems/Half-life/task.py
1,237
4.1875
4
""" In nuclear physics, the half-life is used to describe the rate with which elements undergo radioactive decay. More precisely, it is the time required for an element to reduce in half. Let's take an isotope of Radium (Ra) called radium-223. Say, its half-life is about 12 days. This means that every 12 days the number of atoms reduces in half. Write a program that calculates how many full half-life periods (in days) it would take for a certain amount of radium-223 to reduce to a specific value. The input format: The first line with the starting amount of atoms N (from 2 to 1,000,000), the second line with the resulting quantity R. The output format: The number of full half-life periods (in days) T it would take for radium-223 to reduce from N to R. Assume that any change would take at least 1 half-life period. Suppose, the initial number of atoms is 4 and the resulting quantity equals to 3. In 12 days, the number will reduce to 2 atoms. Since we are counting full half-life periods, you should write 12 and so on. Sample Input: 4 3 Sample Output: 12 Sample Input: 835950 139505 Sample Output: 36 """ # put your python code here N = int(input()) R = int(input()) T = 0 while N > R: T += 12 N = N // 2 print(T)
true
34392e88d4a47288d518f742683746af9ba07963
wahyutirta/Artificial-Neural-Network-Numpy
/Activation_ReLu.py
1,044
4.21875
4
import numpy as np # ReLU activation class Activation_ReLu: # Forward pass def forward(self, inputs): # Remember input values self.inputs = inputs # Calculate output values from inputs # relu will return non negative input as output, other wise will return 0 as output self.output = np.maximum(0, inputs) # Backward pass def backward(self, dvalues): # dvalue is derivatve value from next layer # Since we need to modify original variable, # let's make a copy of values first self.dinputs = dvalues.copy() # Zero gradient where input values were negative # we just copy value from next layer because # derivative of relu if z > 0 = 1, else 0 # in chain rule we will multiply dvalue by one # we dont have to do the multiply, just copy the dvalue # so we just have to make sure to change negative value to 0 # drelu_dz = dvalue * (1. if z > 0 else 0.) self.dinputs[self.inputs <= 0] = 0
true
d363423537279e37289215474e49b09e56d1edd5
xia0m/LPTHW
/ex16/ex16.py
1,510
4.6875
5
from sys import argv script, filename = argv print(f"We're going to erase {filename}") print("If you don't wnt that, hit CTRL -C") print("if you do want that, hit RETURN") input("?") print("Opening the file...") target = open(filename,'w') print("Truncating the file. Goodbye!") target.truncate() print("Now I'm going to aks you for three lines.") line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") print("I'm going to write ehse to the file.") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") target.close() # STUDY DRILLS # 1. If you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand or at least let you know what you need to research more. # 2. Write a script similar to the last exercise that uses read and argv to read the file you just created. # 3. There’s too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of six. # 4. Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file. # 5. If you open the file with 'w' mode, then do you really need the target.truncate()? Read the documentation for Python’s open function and see if that’s true.
true
5ada1e91a951c8add96493d971ffd7bbd9ba66b7
xia0m/LPTHW
/ex8.py
1,145
4.59375
5
formatter = "{} {} {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("one","two", "three", "four")) print(formatter.format(True, False, False, True)) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "It was down that road he brought me, still", "in the trunk of his car. I won’t say it felt right", "but it did feel expected. The way you know", "your blood can spring like a hydrant." )) # In this exercise I’m using something called a function to turn the formatter variable into other strings. When you see me write formatter.format(...) I’m telling python to do the following: # 1. Take the formatter string defined on line 1. # 2. Call its format function, which is similar to telling it to do a command line command named format. # 3. Pass to format four arguments, which match up with the four {}s in the formatter variable. This is like passing arguments to the command line command format. # 4. The result of calling format on formatter is a new string that has the {} replaced with the four variables. This is what print is now printing out.
true
4a8d10410c76ba505fd9e922069f30b285a190ab
t-kostin/python
/lesson-3/lesson3_task3.py
390
4.1875
4
# Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func(a, b, c): if a > b: if b < c: return a + c elif a < c: return b + c return a + b x = my_func(1, 1, 2) print(x)
false
20c390a203009bd790e0429adb5734fc90cb2250
lktolon/Ejercicios-Esctructuras-Repetitivas-Python
/ejercicio5.py
445
4.125
4
while True: caracter=input("Inserta una letra:") if len(caracter) == 1: break while car !=" ": if caracter() == "a" or caracter() == "e" or cararacter() == "i" or caracter() == "o" or caractrer() == "u": print("Es Vocal") else: print("No es Vocal") while True: caracter=input("Inserta una letra:") if len(caracter) == 1: break
false
c9638128c8357bdff5afe6660001c65ab993b451
Rajeshkumar-sivaprakasam/python-projects
/Right angle triangle app.py
454
4.25
4
import math print("Welcome to Right angle triangle app") print() a = float(input("What is the first leg of the triangle:")) b = float(input("What is the second leg of the triangle:")) print() hypotenuse = math.sqrt(a **2 + b **2) area = (a * b) / 2 hypotenuse = round(hypotenuse,3) area = round(area,1) print(f"for triangle with legs of {a} and {b} the hypotenuse is {hypotenuse}") print(f"for triangle with legs of {a} and {b} the area is {area}")
true
3c7a4b2c4f50f4f0f2fd7bd5bfb349a327bdb751
woodardj3383/portfolio2
/intro_to_bootstrap/chap5_lists_ranges.py
2,357
4.34375
4
suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books'] beginning = suitcase[0:4] print(beginning) middle = suitcase[2:4] # this followoing code is menat to demonstrate list slicing suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books'] start = suitcase[:3] end = suitcase[4:] votes = ['Jake', 'Jake', 'Laurie', 'Laurie', 'Laurie', 'Jake', 'Jake', 'Jake', 'Laurie', 'Cassie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie'] jake_votes = votes.count('Jake') print(jake_votes) #preceding code shows how to count the number of items in a list ### Exercise 1 & 2 ### addresses = ['221 B Baker St.', '42 Wallaby Way', '12 Grimmauld Place', '742 Evergreen Terrace', '1600 Pennsylvania Ave', '10 Downing St.'] addresses.sort() print(addresses) # Sort addresses here: ### Exercise 3 ### names = ['Ron', 'Hermione', 'Harry', 'Albus', 'Sirius'] names.sort() print(names) ### Exercise 4 ### cities = ['London', 'Paris', 'Rome', 'Los Angeles', 'New York'] sorted_cities = cities.sort() print(sorted_cities) #preceding code demonstrates the use of sort, but remember # sort() does not return anything, it sorts whatever the list is, #one way around this is to save an original of a list as list() # But aonther way is sorted()- it creates a new sorted list and leaves the original intact inventory = ['twin bed', 'twin bed', 'headboard', 'queen bed', 'king bed', 'dresser', 'dresser', 'table', 'table', 'nightstand', 'nightstand', 'king bed', 'king bed', 'twin bed', 'twin bed', 'sheets', 'sheets', 'pillow', 'pillow'] inventory_len = len(inventory) first = inventory[0] last = inventory[-1] inventory_2_6 = inventory[2:6] first_3 = inventory[0:3] twin_beds = inventory.count('twin bed') inventory.sort() # here are all the functions of this chpter except for sorted toppings = ['pepperoni', 'pineapple', ' cheese', 'sausage', 'olives',' anchovies', 'mushrooms'] prices = [2, 6, 1, 3, 2, 7, 2] num_pieces = len(toppings) print('We sell ' + str(num_pieces) + ' different kinds of pizza!') pizzas = list(zip(prices, toppings)) print(pizzas) pizzas.sort() cheapest_pizzas = pizzas[0] print(cheapest_pizzas) priciest_pizzas = pizzas[-1] print(priciest_pizzas) three_cheapest = pizzas[0:3] print(three_cheapest) num_two_dollar_slices = prices.count(2) print(num_two_dollar_slices)
true
abefa3a0d86991308b6183c105a389848a3a44d9
zh805/PythonCookbook_Codes
/Chapter_1_数据结构与算法/1.11命名切片.py
1,901
4.125
4
''' @Time : 2020/04/20 12:25:03 @Author : Zhang Hui ''' # 问题:代码中出现许多硬编码的切片下标,可读性很差,我们想把它们清除 if __name__ == "__main__": # print(help(slice)) # 从一个记录字符串的几个固定位置提取出特定的数据字段(比如文件或类似格斯) record = '....................100........513.25..........' print(record[20:23]) cost = int(record[20:23]) * float(record[31:37]) print(cost) # 更好的写法,使用sliceb避免大量无法理解的硬编码下标 SHARES = slice(20, 23) PRICE = slice(31, 37) cost_slice = int(record[SHARES]) * float(record[PRICE]) print(cost_slice) # 内置的slice()函数创建一个切片对象,can be used anywhere a slice is allowed items = [i for i in range(7)] print(items) a = slice(2, 4) if items[2:4] == items[a]: print('items[2:4] == items[a] , items[a] is:', items[a]) items[a] = [10, 11] print(items) del items[a] print(items) # print(help(slice.indices)) ''' indices(...) S.indices(len) -> (start, stop, stride) Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by S. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. ''' # 通过调用切片的indices(size)方法把它映射到一个确定大小的序列上,这个方法返回一个三元组(start, stop, step), # 所有值都会被合适地缩小以满足边界限制,避免IndexError异常 s = slice(5, 50, 2) print('s.start is {}, s.stop is {}, s.step is {}'.format( s.start, s.stop, s.step)) # 把s映射到str1上 str1 = 'HelloWorld' print(s.indices(len(str1))) for i in range(*s.indices(len(str1))): print(str1[i])
false
79bdc5fca6883856d793a4f397d06082f5415fa3
omonimus1/chicken_wings_and_PYTHON
/GroceryList/groceryList.py
1,405
4.125
4
# Author: Davide Pollicino # Date: 08/12/2019 import os def print_menu(): print("Type '/' to know how to use this grocery list") command = input("Command: ") print(command) if command == '/': print_commands() elif command == '/list': print_list() elif command == '/delete': delete_list() elif command == '/add': add_element() elif command == '/stop': exit(0) else: print("Wrong command") # Print list of commands def print_commands(): print('/-> Show the list of commands') print('/delete -> Delete the list') print('/add -> Add an element in the list') print('/list -> Show the list') print('/stop') # Add a new element in the list def add_element(): f = open("list.txt", "a+") newElement = input("New element of the list: ") f.write(newElement) f.write('\n') f.close() # Print all the elements off the list def print_list(): f = open("list.txt", "r") if os.stat("list.txt").st_size == 0: print("List already empty") else: for line in f: print(line) f.close() # Delete all the content fo the list def delete_list(): if os.stat("list.txt").st_size == 0: print("List already empty") else: f = open("list.txt", "w") f.truncate(0) print('List removed') f.close() while 1: print_menu()
true
63f10447fd867fcc780712366c138c403e1a31a3
benkeanna/pyladies-homeworks
/09/robots.py
1,652
4.15625
4
from random import randrange class Robot(): max_damage = 5 def __init__(self, lifes): self.lifes = lifes def _make_damage(self, target_robot): """Generates random damage and forces the other robot to defend.""" damage = randrange(0, self.max_damage) target_robot.defend(damage) def _take_damage(self, damage): """Sets new number of lifes when not already 0.""" if self.lifes - damage <0: self.lifes = 0 else: self.lifes -= damage def is_alive(self): """Returns True if robot has any lifes left.""" return self.lifes > 0 def defend(self, damage): """Default defend. Simply takes damage.""" self._take_damage(damage) def attack(self, target_robot): """Default attack. Simply makes damage.""" self._make_damage(target_robot) class Aggressive(Robot): max_damage = 7 def attack(self, target_robot): """Makes damage to the other robot twice. Special for aggresive robot.""" self._make_damage(target_robot) self._make_damage(target_robot) class Defensive(Robot): max_damage = 3 def defend(self, damage): """Special for deffensive robot, takes only half damage.""" self._take_damage(damage // 2) aggr = Aggressive(10) deff = Defensive(50) while True: aggr.attack(deff) print('Deff: {}'.format(deff.lifes)) if not deff.is_alive(): print('Aggr won') break deff.attack(aggr) print('Aggr: {}'.format(aggr.lifes)) if not aggr.is_alive(): print('Deff won') break
true
9b9100644cc08f4676357ada7ebececcf52bbcfc
Ricky-Hu5918/Python-Lab
/1295_Find_Even_Number.py
2,177
4.21875
4
""" Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits).  345 contains 3 digits (odd number of digits).  2 contains 1 digit (odd number of digits).  6 contains 1 digit (odd number of digits).  7896 contains 4 digits (even number of digits).  Therefore only 12 and 7896 contain an even number of digits. Example 2: Input: nums = [555,901,482,1771] Output: 1 Explanation: Only 1771 contains an even number of digits.   Constraints: 1 <= nums.length <= 500 1 <= nums[i] <= 10^5 """ '''#1: low level solution.''' def findEvenNumbers1(nums): cts = 0 for each in nums: if (each >= 10) and (each <= 99): cts += 1 elif (each >= 1000) and (each <= 9999): cts += 1 return cts '''#2: same as #1, not very good.''' def findEvenNumbers2(nums): cts = 0 for each in nums: if (each//10 >= 1) and (each//10 <= 9): cts += 1 elif (each//1000 >=1) and (each//1000 <=9): cts += 1 return cts '''#3: just so so.''' def findEvenNumbers3(nums): cts = 0 for each in nums: tmp = 0 while (each != 0): each = each // 10 tmp += 1 if (tmp%2 == 0): cts += 1 return cts '''#4: 将整数转成字符串,计算字符串中字符的长度个数即可。''' def findEvenNumbers4(nums): return sum(1 for item in nums if (len(str(item)) % 2 == 0)) '''#5: 思路一样,都是转成字符串,但是效率比#4高一些''' def findEvenNumbers5(nums): odd_count = 0 for item in nums: odd_count += len(str(item))%2 return len(nums)-odd_count '''#6: 装逼的境界,一行代码搞定!''' def findEvenNumbers6(nums): return (len(nums)-sum(len(str(item))%2 for item in nums)) '''#7: one-line code 合集''' def findEvenNumbers7(nums): return sum([not len(str(item))%2 for item in nums]) def findEvenNumbers8(nums): return sum(1 for item in nums if not len(str(item))%2) nums = [12, 345, 2, 6, 7896] #2 print(findEvenNumbers8(nums))
true
a96c25458be140c49deeb30101b1d0a7ebc2d267
Ricky-Hu5918/Python-Lab
/125_Valid_Palindrome.py
2,157
4.21875
4
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true """ '''#1: 常规方法,效率一般''' def isPalindrome(s): if not s: return True list_s = list(s.lower()) str_s = '' for i in range(len(list_s)): if (list_s[i].isalpha() or list_s[i].isnumeric()): str_s += list_s[i] return True if (str_s == str_s[::-1]) else False '''#2: 尽可能少的使用系统自带函数''' def isPalindrome2(s): if not s: return True str_s = '' for i in range(len(s)): if (97 <= ord(s[i]) <= 122) or (48 <= ord(s[i]) <= 57): str_s += s[i] elif (65 <= ord(s[i]) <= 90): str_s += chr(ord(s[i])+32) for i in range(len(str_s)//2): if (str_s[i] != str_s[len(str_s)-i-1]): return False return True ''' #自己的处理方法,比较弱鸡,上面是肖哥的处理方法,值得学习! idx_start, idx_end = 0, len(str_s)-1 while (idx_end != idx_start if len(str_s)%2 else idx_end > idx_start): if (str_s[idx_start] != str_s[idx_end]): return False else: idx_end -= 1 idx_start += 1 ''' '''#3: xk's solution.''' def isPalindrome3(chars): if len(chars) == 1 or len(chars) == 0: return True alpha_numeric_removed_chars = filter(lambda x: (ord(x) in range(65, 91)) or (ord(x) in range(48, 58)) or (ord(x) in range(97, 123)), chars) print(alpha_numeric_removed_chars) processed_chars = list(map(lambda x: chr(ord(x) - 32) if ord(x) in range(97, 123) else x, alpha_numeric_removed_chars)) print(processed_chars) # print(processed_chars) for i in range(len(processed_chars)//2): #值得学习!!! if processed_chars[i] != processed_chars[len(processed_chars)-i-1]: return False return True s = "A man, a plan, a canal: Panama" s1 = "race a car" s2 = 'amanaplanacanalpanama' s3 = "a." print(isPalindrome2(s3))
true
f425b9ba617ff2b7b2f57d6def7f8e45a89ab962
Ricky-Hu5918/Python-Lab
/53_Maximum_Subarray.py
1,711
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. ''' '''#1: 贪心算法''' def maxSubArray1(nums): cur_sum, max_sum = nums[0], nums[0] for each in nums[1:]: cur_sum = max(each, cur_sum + each) max_sum = max(cur_sum, max_sum) return max_sum '''#2: 动态规划''' def maxSubArray2(nums): max_sum = nums[0] for i in range(1, len(nums)): if (nums[i-1] > 0): nums[i] += nums[i-1] max_sum = max(nums[i], max_sum) return max_sum '''#2: 更容易理解的动态规划''' ''' 动态规划的是首先对数组进行遍历,当前最大连续子序列和为 cur_sum,结果为 max_sum 如果 cur_sum > 0,则说明 cur_sum 对结果有增益效果,则 cur_sum 保留并加上当前遍历数字 如果 cur_sum <= 0,则说明 cur_sum 对结果无增益效果,需要舍弃,则 cur_sum 直接更新为当前遍历数字 每次比较 cur_sum 和 max_sum,max_sum,遍历结束返回结果 时间复杂度:O(n) ''' def maxSubArray3(nums): max_sum = nums[0] cur_sum = 0 for each in nums: if (cur_sum > 0): cur_sum += each else: cur_sum = each print(cur_sum) max_sum = max(max_sum, cur_sum) return max_sum nums = [-2,1,-3,4,-1,2,1,-5,4] #6 # print(maxSubArray1(nums)) # print(maxSubArray2(nums)) print(maxSubArray3(nums))
false
ca3f7960d0b91cbb5a3b4b6ec23899a56d58c195
Ricky-Hu5918/Python-Lab
/326_Power_of_Three.py
1,131
4.53125
5
''' 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? ''' '''#1: recursion version''' def isPowerOfThree1(n): if (n==0): return False elif (n==1): return True else: return isPowerOfThree1(n/3) '''#2: iterate version''' def isPowerOfThree2(n): while (n>2): n /= 3 return True if n==1 else False '''#3: one-line code''' def isPowerOfThree3(n): return True if n in list(map(lambda x:3**x, [x for x in range(20)])) else False '''#4: a better version''' def isPowerOfThree4(n): if (n<=0): return False else: return ((3**100)%n == 0) '''#5: xk's better version''' import math def isPowerOfThree5(n): if (n<=0): return False res = (math.log10(n) / math.log10(3)) return (math.floor(res) == math.ceil(res)) n1 = 27 n2 = 45 print(isPowerOfThree1(n1)) print(isPowerOfThree2(n1)) print(isPowerOfThree5(n2))
true
497db265378fbc31f65d52875e9a4fd326e177a4
Ricky-Hu5918/Python-Lab
/844_Backspace_String_Compare.py
1,303
4.15625
4
''' Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c". Example 4: Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b". Note: 1 <= S.length <= 200 1 <= T.length <= 200 S and T only contain lowercase letters and '#' characters. Follow up: Can you solve it in O(N) time and O(1) space? ''' class Solution: def backspaceCompare1(self, S: str, T: str) -> bool: #1: using stack tmp_s, tmp_t = [], [] for s in S: if s != '#': tmp_s.append(s) else: if tmp_s: tmp_s.pop() for t in T: if t != '#': tmp_t.append(t) else: if tmp_t: tmp_t.pop() return tmp_s == tmp_t test = Solution() S, T = "ab##", "c#d#" print(test.backspaceCompare1(S, T))
true
c57ef77579c1bf002dc5e0d1d73a6ff18a1f6ff8
Ricky-Hu5918/Python-Lab
/104_Maximum_Depth_of_Binary_Tree.py
1,686
4.15625
4
''' Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. ''' '''求二叉树深度的解法''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: '''# 3: DFS深度优先搜素,利用递归的栈,借助level标记当前层''' def maxDepth3(self, root: TreeNode) -> int: if not root: return 0 self.depth = 0 self._dfs(root, 0) return self.depth def _dfs(self, node, level): if not node: return if self.depth < level + 1: self.depth = level + 1 self._dfs(node.left, level + 1) self._dfs(node.right, level + 1) '''# 2: BFS广度优先搜索,使用双端队列deque''' def maxDepth2(self, root: TreeNode) -> int: if not root: return 0 queue = collections.deque() queue.append(root) depth = 0 while queue: depth += 1 for i in range(len(queue)): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) return depth '''# 1: DFS+分治''' def maxDepth1(self, root: TreeNode) -> int: return 0 if not root else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
true
4f20674486be5ebcf8072ef20c31d40017a121e7
Ricky-Hu5918/Python-Lab
/21_Merge_Two_Sorted_Lists.py
1,915
4.125
4
''' Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 ''' class ListNode: def __init__(self, x): self.val = x self.next = None def mergeTwoLists(l1, l2): if not l1 and l2: return l2 elif not l2 and l1: return l1 else: return l1 cur1, cur2 = l1, l2 if cur1.val < cur2.val: mergedlists = ListNode(cur1.val) cur1 = cur1.next else: mergedlists = ListNode(cur2.val) cur2 = cur2.next cur3 = mergedlists while (cur1 or cur2): if not cur1 and cur2: cur3.next = ListNode(cur2.val) cur2 = cur2.next elif not cur2 and cur1: cur3.next = ListNode(cur1.val) cur1 = cur1.next else: if cur1.val < cur2.val: cur3.next = ListNode(cur1.val) cur1 = cur1.next else: cur3.next = ListNode(cur2.val) cur2 = cur2.next cur3 = cur3.next return mergedlists '''#2: 迭代版本''' def mergeTwoLists2(l1, l2): if not l1: return l2 elif not l2: return l1 else: if l1.val < l2.val: l1.next = mergeTwoLists2(l1.next, l2) #self.mergeTwoLists2(l1.next, l2) return l1 else: l2.next = mergeTwoLists2(l2.next, l2) #self.mergeTwoLists2(l2.next, l2) return l2 '''#3: 递归版本''' def mergeTwoLists3(l1, l2): prehead = ListNode(-1) pre = prehead while (l1 and l2): if l1.val < l2.val: pre.next = l1 l1 = l1.next else: pre.next = l2 l2 = l2.next pre = pre.next pre.next = l1 if l1 is not None else l2 return prehead.next
true
36ed67054724afb9800228b47cfe4ca6e05e1a3b
Ricky-Hu5918/Python-Lab
/maxNumberOfBalloons.py
713
4.1875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #Leetcode.num = 1189 ''' Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example 1: Input: text = "nlaebolko" Output: 1 ''' ''' return the smallest number that every single character occurs. ''' def maxNumberOfBalloons(text): b, a, n, l, o = text.count("b"), text.count("a"), text.count("n"), text.count("l"), text.count("o") A = [b, a, n, int(l/2), int(o/2)] A.sort() return A[0] if __name__ == '__main__': text = "krhizmmgmcrecekgyljqkldocicziihtgpqwbticmvuyznragqoyrukzopfmjhjjxemsxmrsxuqmnkrzhgvtgdgtykhcglurvppvcwhrhrjoislonvvglhdciilduvuiebmffaagxerjeewmtcwmhmtwlxtvlbocczlrppmpjbpnifqtlninyzjtmazxdbzwxthpvrfulvrspycqcghuopjirzoeuqhetnbrcdakilzmklxwudxxhwilasbjjhhfgghogqoofsufysmcqeilaivtmfziumjloewbkjvaahsaaggteppqyuoylgpbdwqubaalfwcqrjeycjbbpifjbpigjdnnswocusuprydgrtxuaojeriigwumlovafxnpibjopjfqzrwemoinmptxddgcszmfprdrichjeqcvikynzigleaajcysusqasqadjemgnyvmzmbcfrttrzonwafrnedglhpudovigwvpimttiketopkvqw" print(maxNumberOfBalloons(text))
false
07033b5c3bab86de5fc1f385dfc5bc242cbfee53
PyLov3r/Python-Beginner
/a)Basic_concepts.py
899
4.59375
5
""" Tema: 1.- Simple operations 2.- Data types 3.- Floats 4.- Exponentiation 5.- Quotient 6.- Remainder 7.- Flight time problem """ # Simple operations print(2+2) print(5+4*3) print(10/2) print(2*(3+4)) #Data types string = "This is a string" Integer = 5 Float = 5.0 #Floats print(2/8) print(6*7.0) print(4+1.65) #Exponentiation print(2**5) #Dos a la quinta potencia print(2**5**3) print(9**(1/2)) #Quotient print(20//6) #Resultado sin decimales #Remainder print(20 % 6) #Lo que sobra de dividir #Flight time problem """Flight Time You need to calculate the flight time of an upcoming trip. You are flying from LA to Sydney, covering a distance of 7425 miles, the plane flies at an average speed of 550 miles an hour. Calculate and output the total flight time in hours. Hint The result should be a float.""" print(7425/550) #Resultado
true
b803740dd7f529c8e128d070cb7ae5a8a43cf3ab
glaubersabino/python-cursoemvideo
/world-03/exercice-099.py
655
4.28125
4
# Exercício 099 # Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. # Seu programa tem que analisar todos os valores e dizer qual deles é o maior. from time import sleep def maior(* num): print('ANALISANDO OS VALORES INFORMADOS...') print(f'FORAM INFORMADOS {len(num)} VALORES AO TODO.') for c in num: print(c, end=' ') sleep(1) print() if len(num) > 0: print(f'=> O MAIOR NÚMERO INFORMADO FOI {max(num)}.') else: print('=> O MAIOR NÚMERO INFORMADO FOI 0.') maior(1, 8, 3, 4) maior(1, 8, 3, 4, 9, 14, 2, 1) maior(1, 1, 3) maior()
false
df82ff8159d9afdf6e09551efa1f150ddb322691
glaubersabino/python-cursoemvideo
/world-01/exercice-026.py
554
4.21875
4
# Exercício 026 # Faça um programa que leia uma frase pelo teclado e mostre: # 1 - Quantas vezes aparece a letra "A". # 2 - Em que posição ela aparece a primeira vez. # 3 - Em qual posição ela aparece a última vez. frase = str(input('Digite uma frase: ')) q1 = frase.upper().count('A') q2 = frase.upper().find('A') q3 = frase.upper().rfind('A') print('Quantas vezes aparece a letra "A"? \n{}'.format(q1)) print('Em que posição ela aparece a primeira vez? \n{}'.format(q2)) print('Em qual posição ela aparece a última vez? \n{}'.format(q3))
false
3448ad0c5772d708ad080dabf8b05bad77efad03
glaubersabino/python-cursoemvideo
/world-01/exercice-005.py
282
4.21875
4
# Exercício 05 # Faça um programa que leia um número inteiro e mostre na tela # o seu sucessor e seu antecessor. num = int(input('Informe um número inteiro: ')) print('O número informado foi {}.\nO seu sucessor é {}.\nO seu antecessor é {}.'.format(num, num + 1, num - 1))
false
4dccb99bed224533d2f903882c146d1459c1aa14
setyo-dwi-pratama/python-basics
/13.oper_logika.py
1,319
4.34375
4
# OPERATOR LOGIKA print("===============OPERATOR LOGIKA===============") # Operator Logika adalah operator yang digunakan untuk membuat suatu kesimpulan logis dari 2 kondisi boolean (True atau False). python memiliki 3 operator logika yaitu and, or dan not print('Hasil dari True and True :', True and True) print('Hasil dari True and False :', True and False) print('Hasil dari False and True :', False and True) print('Hasil dari False and False :', False and False) print('\n') print('Hasil dari True or True :', True or True) print('Hasil dari True or False :', True or False) print('Hasil dari False or True :', False or True) print('Hasil dari False or False :', False or False) print('\n') print('Hasil dari not True :', not True) print('Hasil dari not False :', not False) print('\n') # operator logika juga dapat dilakukan dalam berbagai kondisi untuk menghasilkan kesimpulan logis hasil = (5 > 6) and (10 <= 8) print(hasil) hasil = ('python' == 'python') or (10 <= 8) print(hasil) hasil = not (10 < 10) print(hasil) hasil = ('duniailkom' == 'duniailkom') and (10 <= 8) or (1 != 1) print(hasil) # operasi yang akan dijalankan dimulai dari kiri terlebih dahulu, kita juga bisa menggunakan () untuk memprioritaskan apa yang harus dijalankan terlebih dahulu
false
419dd80980999d489c3b92b03831e7322302543b
Glitching-out-of-the-universe/Calculator
/calculator.py
1,045
4.25
4
# adds two numbers def add(x, y): return x + y #subtracts two numbers def subtract(x, y): return x - y # multiplies two numbers def multiply(x, y): return x * y #this divides two numbers def divide(x, y): return x / y # Select operation print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") #if operation chosen is correct then while True: choice = input("Enter your choice(1/2/3/4): ") if choice in ('1', '2', '3', '4'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) break # if operation is not correct else: print("Invalid")
true
b772fbd4dd6e77c0dcfb77abf1c245fd207812b4
here0009/PythonScript
/FileManipulation/CopyFiletoRootFolder.py
712
4.15625
4
""" It was used to change the file name to the folder name + file name, then copy the file to the rootfolder, delete the original file. the path is a parameter in sys[1] """ import os import sys path = '.' for root, dirs, files in os.walk(path, topdown=False): for name in files: if root != path: #not in the root dir old_file_path = os.path.join(root, name) new_name = root[2:] + name #root was like '.\\1\\2\\3', remove the first 2 characters: '.\' new_file_path = os.path.join(path, new_name) print('{} have been replaced by {}'.format(old_file_path, new_file_path)) os.rename(old_file_path, new_file_path) os.rmdir(root)
true
7c8f1d6bf3d78c3869e07725c75581a83f7b71a0
DimaZadorozhnyy/Hillel_HomeWorks
/HM7/Dima_Zadorozhnyy7.py
2,472
4.21875
4
from math import sqrt '''' 1. Написать функцию season, принимающую 1 аргумент — номер месяца (от 1 до 12), и возвращающую время года, которому этот месяц принадлежит (зима, весна, лето или осень). ''' def get_season(number): if number in [1, 2, 12]: return f"{number}-й месяц это зима" elif number in range(3, 6): return f"{number}-й месяц это весна" elif number in range(6, 9): return f"{number}-й месяц это лето" elif number in range(9, 12): return f"{number}-й месяц это осень" number = input("Введите номер месяца от 1 до 12:\n") while not number.isdigit() or number not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']: print("Некоректный ввод, повторите попытку") number = input("Введите номер месяца от 1 до 12:\n ") number = int(number) print(get_season(number)) """ 2. Реализовать функцию, которая принимает строку и расделитель и возвращает словарь {слово: количество повторений} """ def converter(string, separate): string = string.split(separate) my_dict = {} my_string = my_dict.fromkeys(string, 0) for i in string: my_string[i] += 1 return my_string delimiter = input("delimiter:\n") my_str = input('String:\n') print(converter(my_str, delimiter)) ''' 3. Написать функцию square, принимающую 1 аргумент — сторону квадрата, и возвращающую 3 значения: периметр квадрата, площадь квадрата и диагональ квадрата. ''' def get_rectangle_data(a): perimeter = a * 4 area = a**2 diagonal = a * sqrt(2) return f" Периметр квадрата равен {perimeter}\n Площадь квадрата равна {area}\n Диагональ квадрата равна {diagonal}" a = input("Введите длинну стороны а: \n") while not a.isdigit(): print("Некоректный ввод, повторите попытку !") a = input("Введите длинну стороны а: \n") a = int(a) print(get_rectangle_data(a))
false
1ecca25e868d1a902d9c5ea573a05c700d65db35
chiranshu11/Python
/Strings & Strings Manipulation/String_find_function.py
1,351
4.40625
4
# This segment is just a chance for you to play around with # finding strings within strings. print ("Example 1: Finding substrings in a string") print ("test".find("te")) print ("test".find("st")) print ("test".find("t")) #it will start counting from very first position and when the expression is found first it will return the position print ("test"[2:]) #after counting t at first,now finding second time t print ("test".find("t",1)) #find("expression",nth time expression is occuring) print ("testttt".find("t",2)) print ("testttt".find("t",6)) #it will return -1 as 5th time no t is present in the string print ("Example 2: Finding substrings in a string which is stored as a variable") my_string = "test" print (my_string.find("te")) print (my_string.find("st")) print (my_string[2:]) print ("Example 3: Printing out everything after a certain substring") my_string = "My favorite color: blue" color_start_location = my_string.find("color:") favorite_color = my_string[color_start_location:] print (favorite_color) # oops, this line prints out 'color: ' as well... print (favorite_color[7:]) # this fixes it! print ("Example 4: Other interesting things about string.find()...") print( "text".find("text")) # prints 0 print( "text".find("Text")) # prints -1 print( "text".find("")) # prints 0 print ("text".find(" ")) # prints -1
true
0b467a2f0990f2c658ad8e35334108ac2d803c78
chiranshu11/Python
/if_else/bIggestno_among3.py
414
4.21875
4
# Defining a procedure, biggest, that takes three # numbers as inputs and returns the largest of # those three numbers. def biggest(a, b, c): largest=a if(largest<b): largest=b if(largest<c): largest=c return largest print biggest(3, 6, 9) #>>> 9 print biggest(6, 9, 3) #>>> 9 print biggest(9, 3, 6) #>>> 9 print biggest(3, 3, 9) #>>> 9 print biggest(9, 3, 9) #>>> 9
true
1a1a7a977b1dc22bd461587ce451644605ab97a3
Sakthimadhu/phython
/large.py
271
4.25
4
num1=10 num2=8 num3=5 num=float(input("enter the frst num:")) num=float(input("enter the secod num:")) num=float(input("enter the third num:")) if num1>=num2 or num1>=num3 print("num1 largest") if num2>=num1 or num2>=num3 print("num2 largest") else print("numj3 largest)
false
41bbe7491808efb2a7cb05408a4eb2af70769a08
akhilpgvr/Python
/strong_number.py
491
4.375
4
#This is the code for finding strong number using recursion def fact(n): if(n == 1): return 1 else: return n*fact(n-1) n=int(input("enter a number")) copy=n sum=0 while(n>0): k=n%10 #Taking each digit of number using modulus operator sum=sum+fact(k) #Adding sum of factorial of each digit up to number>0 n=int(n/10) if(copy == sum): print("strong number") else: print("not a strong number")
true
a925f9132f6d0e7cbf837c968294b7213d6593fa
thelmuth/cs101-fall-2020
/Class03/turtle_right_triangle.py
1,501
4.40625
4
from turtle import * import math def main(): april = Turtle() april.width(3) pedro = 37 # Variable is on the left, and the expression is on the right side1 = int(input("Enter the length of a side of a triangle: ")) side2 = side1 # We can use variables in other expressions hypotenuse = math.sqrt((side1 * side1) + (side2 * side2)) print("The hypotenuse is", hypotenuse, ". There you have it!") # Draw a triangle april.fillcolor("darkorchid") april.begin_fill() april.forward(side1) april.left(90) april.forward(side2) april.left(135) april.forward(hypotenuse) april.left(135) april.end_fill() # Draw a second triangle # First, move the turtle somewhere else april.up() april.goto(-200, 100) # This tells the turtle to go to a specific location april.down() april.left(72) # Now, draw a 30-60-90 triangle side1 = 78 hypotenuse = side1 * 2 # Calculate the length of side2 side2 = math.sqrt(hypotenuse * hypotenuse - side1 * side1) april.fillcolor("limegreen") april.begin_fill() april.pencolor("red") april.forward(side1) april.left(180 - 60) april.forward(hypotenuse) april.left(180 - 30) april.forward(side2) april.left(90) april.end_fill() # These two lines of code should appear at the bottom in all your programs if __name__ == "__main__": main()
true
763c11d83fcf226bff336d8d2da2942d576f0879
thelmuth/cs101-fall-2020
/Class09/more_for_loops.py
1,291
4.34375
4
### We often want to accumulate a value in a variable each time ### through a loop. ### Need a variable with a starting value ### We call this variable the _accumulator_ # numbers = [16, 2999, 308, 0, 10000] # the_sum = 0 # This is the accumulator # # for num in numbers: # print(the_sum) # the_sum = the_sum + num # # print("The numbers in", numbers, "add up to", the_sum) # colors = ["red", "blue", "yellow"] # for color in colors: # mo.pencolor(color) # mo.forward(100) ## Sum all of the numbers between 0 and 1 million # the_sum = 0 # for num in range(1000000): # the_sum = the_sum + num # print("The sum of all ints between 0 and 1 million is", the_sum) # the_sum = 0 # for num in range(1000000): # the_sum += num # print("The sum of all ints between 0 and 1 million is", the_sum) # product = 1 # for number in range(1, 21): # actually multiplies up to 20 # product *= number # print(product) ### Want to find a list of each of these numbers squared # numbers = [16, 2999, 308, 0, 10000] # squares = [] # for num in numbers: # squares.append(num * num) # print(squares) ### Accumulate over a string city = "NYC" new_string = "" for char in city: #new_string = new_string + char + "." new_string += char + "." print(new_string)
true
216090b2db66accf6a786f77d5408232278b7224
thelmuth/cs101-fall-2020
/Class19/into_nltk.py
1,468
4.28125
4
import nltk NOUNS = ["dog", "person", "octopus", "platypus", "monkey", "computer", "chair", "cat", "juice", "book", "TV", "bacon", "egg", "Abraham Lincoln", "bagel"] movie = "I like the movie Mr. & Mrs. Smith! Brad Pitt, Angelina Jolie, etc. are in it." buses = "I will book the bus ticket while I bus the table and read a book." def main(): # sents = naive_sentence_tokenizer(movie) # for sent in sents: # print(sent) ### NLTK's version of sentence tokenizing # sents = nltk.sent_tokenize(movie) # for sent in sents: # print(sent) ### NLTK's version of words tokenizing # words = nltk.word_tokenize(movie) # print(words) ### Get the parts of speach of a list of words words2 = nltk.word_tokenize(buses) pos = nltk.pos_tag(words2) for word, word_pos in pos: print("The part of speech for", word, "is", word_pos) ### We can display all of the parts of speech abreviations using this # nltk.help.upenn_tagset() ### We can look up a specific tag # nltk.help.upenn_tagset("DT") def naive_sentence_tokenizer(text): """This will return the sentences in text as a list.""" sentences = [] current_sentence = "" for char in text: current_sentence += char if char in ".?!": sentences.append(current_sentence) current_sentence = "" return sentences if __name__ == "__main__": main()
false
f28a58aa0612763c3f8c7f08faf3928126ddfee7
aryamane/codingbat-python
/warmup-1/monkey_trouble.py
632
4.1875
4
def monkey_trouble(a_smile, b_smile): if a_smile and b_smile: return True elif not a_smile and not b_smile: return True else: return False print(monkey_trouble(True,False)) ## The above can be shortened to: ## return ((a_smile and b_smile) or (not a_smile and not b_smile)) ## Or this very short version (think about how this is the same as the above) ## return (a_smile == b_smile) # We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. # We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
true
51a88e3eaca393334523478fd1b78546d1818203
aluoch-dev/MorningAlgorithms
/Iterations/for/Example_Questions/printing_triangle_arterisks.py
482
4.1875
4
__author__ = "Laurine" # Question # Let’s print a triangle made of asterisks (‘*’) separated by spaces. The triangle # should consist of n rows, where n is a given positive integer, and consecutive rows should # contain 1, 2, . . . , n asterisks. For example, for n = 4 the triangle should appear as follows: # Specify the number of rows rows = 5 for i in range(1, rows+1): # for every row, print an arterisk and a space multiplied by the row number print("* " *i)
true
0b83458b29063670c9cc86a3a000ec69c9db950c
mingyyy/onsite
/week_03/09_generators/00_generators.py
276
4.15625
4
''' Demonstrate how to create a generator object. Print the object to the console to see what you get. Then iterate over the generator object and print out each item. ''' my_num = [1, 34, 545, 3, 13, 34] gen = (x**(1/2) for x in my_num) print(gen) for i in gen: print(i)
true
91fbea5734951de4b1d97dae6c69808ed4f14fe7
mingyyy/onsite
/week_02/10_classes_objects_methods/02_points.py
2,893
4.4375
4
''' Work through the chapter "Classes and Objects" in Think Python 2e: http://greenteapress.com/thinkpython2/html/thinkpython2016.html and build out the Point class example. ''' class Point: """Represents a point in 2-D space, an ordinate system defines x as the variable in x-axis y as the variable in y-axis """ def __init__(self, x, y): self.x = x self.y = y def __str__(self): if (self.x, self.y) == (0,0): return "A point in origin." elif self.x > 0 and self.y > 0: return f"A point in quadrant 1, with the coordinate ({self.x}, {self.y})." elif self.x > 0 > self.y: return f"A point in quadrant 4, with the coordinate ({self.x}, {self.y})." elif self.x < 0 < self.y: return f"A point in quadrant 2, with the coordinate ({self.x}, {self.y})." elif self.x < 0 and self.y < 0: return f"A point in quadrant 3, with the coordinate ({self.x}, {self.y})." def __lt__(self, other): return (self.x, self.y) < (other.x, other.y) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __ne__(self, other): return not (self == other) def __le__(self, other): return (self.x, self.y) <= (other.x, other.y) def distance(self, other): return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5 def line(self, other): if self.x == other.x: s = "vertical line" elif self.y == other.x: s = "horizontal line" elif (self.y < other.y and self.x < other.x) or (other.y < self.y and other.x < self.x): s = "0 - 90 degree line" else: s = "90 - 180 degree line" return s if __name__ == '__main__': # Point(x, y) p1 = Point(0, 0) p2 = Point(3, 4) p3 = Point(-1, -1) p4 = Point(-5, 6) print(p1, p2, p3) print(p1.distance(p2)) print(p1.distance(p3)) print(p2.distance(p2)) print(p3.distance(p2)) print(p1.line(p2)) print(p2.line(p4)) class Rectangle: ''' four corners of the rectangle are defined as c1, c2, c3, c4, where c1 = left down c2 = left up, c3 = right up, c4 = right down c is the center point ''' def __init__(self, width, length, leftdown=[0,0]): self.width = width self.length = length self.leftdown = leftdown def area(self): return self.width * self.length def circumference(self): return 2*(self.width+self.length) def find_center(self, v_h = True): if v_h is False: x = Point(self.leftdown[0] + self.length/2, self.leftdown[1] + self.width/2) else: x = Point(self.leftdown[0] + self.width/2, self.leftdown[1] + self.length/2) return x r = Rectangle(2, 3, [0,0]) print(r.find_center())
true
1e83463d7c0f7f16914db86c1c012acf115292aa
mingyyy/onsite
/week_02/mini_projects/04_guess.py
616
4.3125
4
''' -------------------------------------------------------- GUESS THE RANDOM NUMBER -------------------------------------------------------- Build a Guess-the-number game that asks a player for an input until they pick the correct (randomly generated) number between 1 and 100. Tip: Use python's 'random' module. ''' import random flag = True guess = 100 while flag: user_input = input(f"Please guess a number between 1 and {guess}: ") ans = random.randint(1, guess) counter = 0 if int(user_input) == ans: print("You won!") flag = False else: continue
true
6dc78c2324fa2d819edd7265a67711d08b92ffc5
mingyyy/onsite
/week_02/08_dictionaries/09_03_count_cases.py
697
4.40625
4
''' Write a script that takes a sentence from the user and returns: - the number of lower case letters - the number of uppercase letters - the number of punctuations characters - the total number of characters Use a dictionary to store the count of each of the above. Note: ignore all spaces. Example input: I love to work with dictionaries! Example output: Upper case: 1 Lower case: 26 Punctuation: 1 ''' user = input("Please enter a string here: ") l = u = p = t = s = 0 for i in user: if i.islower() is True: l += 1 elif i.isupper() is True: u += 1 elif i == "!": p += 1 elif i == " ": s += 1 t += 1 print(l, u, p, t-s)
true
d5024cb84536cfdece9dc94de3c1e1d51365820b
mingyyy/onsite
/week_02/10_classes_objects_methods/01_try_methods.py
1,885
4.53125
5
''' We've learned about strings earlier. Looking at string methods from the perspective of "everything is an object in python" explains the syntax that we encountered there. Now take a second look at the documentation of the string methods at: http://docs.python.org/3/library/stdtypes.html#string-methods. Demonstrate 3 interesting string methods of your choice and explain why they are invoked like this: str.method() ''' # str.isalpha() # Return true if all characters in the string are alphabetic and there is at least one character, # false otherwise. a = "theing2343" b = " >*&*^" c = " htlk j ekje " d = "djkfjdk" print(a.isalpha()) print(b.isalpha()) print(c.isalpha()) print(d.isalpha()) # str.partition(sep) # Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, # the separator itself, and the part after the separator. # If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. a = "df dfjkdj &( > martin djfkdjskmmmormed " print(a.partition("martin")) print(a.partition("j")) # str.splitlines([keepends]) # Return a list of the lines in the string, breaking at line boundaries. # Line breaks are not included in the resulting list unless keepends is given and true. # # This method splits on the following line boundaries. In particular, # the boundaries are a superset of universal newlines. # # Representation Description # \n Line Feed # \r Carriage Return # \r\n Carriage Return + Line Feed # \v or \x0b Line Tabulation # \f or \x0c Form Feed # \x1c File Separator # \x1d Group Separator # \x1e Record Separator # \x85 Next Line (C1 Control Code) # \u2028 Line Separator # \u2029 Paragraph Separator # \v Vertical Tab, 0x0b # \f ASCII 0x0c, a.k.a. “new page” a = " 324\x859r\f3u\x1cjdjf\nttt\rsss\vyou\u2028thr" print(a) print(a.splitlines())
true
00a5c0eac11f3b7bad6ed864b1b492fed4bec32b
mwaiyusuf/game-
/turtle.py
694
4.25
4
from turtle import Turtle # importing from the class Turtle # we will create an object called laura laura = Turtle() # we will assign the object attribute laura.color('red') laura.shape('turtle') # we will have methods..which are the ones that tells the object what to do laura.penup() laura.goto(-160,100) laura.pendown() rik = Turtle() lauren = Turtle() carrieanne = Turtle() rik.color('green') rik.shape('turtle') rik.penup() rik.goto(-160,70) rik.pendown() lauren.color('blue') lauren.shape('turtle') lauren.penup() lauren.goto(-160,40) lauren.pendown() carrieanne.color('purple') carrieanne.shape('turtle') carrieanne.penup() carrieanne.goto(-160,10) carrieanne.pendown()
false
618c786aaa309fde2e674f84d2f7fa3657ddc41f
NaveenVupputuri/CMPS-Cryptography-Naveen
/Assignment-3.py
1,995
4.1875
4
#******************** Assignment-3 : Synthetic Division ****************** #Name : Naveen Sai Vupputuri #Program Description :This program takes the coefficients of the equation # and two points as inputs and verifies whether the points are on # the elliptical, curve if yes then finds out the point where the # line passing through the two points intersects the elliptical # curve. #************************************************************************* import math from fractions import Fraction def syntheticDivision(c1,c2,c3,c4,c,x1,y1,x2,y2): #slope of the line passing through the two points m=(y2-y1)/(x2-x1) #constant in the line 'cl' cl=y1-(m*x1) #synthetic division: #after substituting the line y=mx+cl in cure equation # (c2)x^3 + (c3-(c1*m*m))x^2 + (c4-(2*c1*cL))x + (c-(cL*cL*c1)) l1=c2 l2=(c3-(c1*m*m)) l3=(c4-(2*c1*cl*m)) l4=(c-(cl*cl*c1)) m1=l1 m2=l2+(x1*m1) m3=l3+(x1*m2) a=m1 b=m2+(x2*a) xCord=-(b/a) yCord=(m*xCord) + cl return xCord , yCord print ("Enter the coefficients and constant of the elliptical equation ") c1=int(input("coeff of y^2 :")) c2=int(input("coeff of x^3 :")) c3=int(input("coeff of x^2 :")) c4=int(input("coeff of x :")) c=int(input("Constant :")) print("Enter the coordinates of the two points x1, y1, x2, y2 :") x1=int(input("First X-coordinate :")) y1=int(input("First Y-coordinate :")) x2=int(input("Second X-coordinate :")) y2=int(input("Second Y-coordinate :")) #Verifying whether the points lie on the curve #For fist point leftVer1=c1*y1*y1 rightVer1=(c2*x1*x1*x1)+(c3*x1*x1)+(c4*x1)+c #For second point leftVer2=c1*y2*y2 rightVer2=(c2*x2*x2*x2)+(c3*x2*x2)+(c4*x2)+c if((leftVer1==rightVer1) and (leftVer2==rightVer2)): xcord,ycord=syntheticDivision(c1,c2,c3,c4,c,x1,y1,x2,y2) print("The intersecting coordinate is :") print(Fraction(xcord) , Fraction(ycord)) else: print("The points doesn't lie on the equation ")
true
1e5bcae3a4f7e78ca323e8f1e8b8e8422c64b2b8
sanaipey/Initials
/initials.py
506
4.15625
4
def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ capitalized_names = fullname.upper() name_list = capitalized_names.split() name_init = [] for i in name_list: name_init.append(i[0]) return ''.join(name_init) def main(): fullname = input("Please enter your name:") initials = get_initials(fullname) print("The initials of", fullname, "are", initials) if __name__ == "__main__": main()
true
abc13683a46e09876d1da8b11d5015ed9acc74dc
lo-ryder/basic_repo
/odd:even.py
959
4.21875
4
#prints a string to describe each number as odd or even # def oddANDeven(): # for num in range(1,2001): # if num%2 == 0: # des = 'even' # print 'Number is {}. This is an {} number.'.format(num, des) # else: # des = 'odd' # print 'Number is {}. This is an {} number.'.format(num, des) # oddANDeven() #this function multiplies the list by a submitted number # def multiplyList(bigList, multiplier): # for num in range(len(bigList)): # bigList[num] = bigList[num]* multiplier # return bigList # print multiplyList([2,4,10,16],5) #this function prints a list within a list set by input def multiplyList(bigList, multiplier): for num in range(len(bigList)): bigList[num] = bigList[num]* multiplier yo = bigList[num] x =[] for indx in range(yo): x.append(1) bigList[num]=x return bigList print multiplyList([2,1,3],2)
true
0f224294ce09b263f44c621057ce206814563196
abbwiljoh/Triangelmastaren
/Triangelmästaren/pythagorasTrig.py
2,560
4.25
4
#------------------------------------------------------------------------------------------------------------------- # Tool for calclating angles and lengths of 90 degree triangles using trigonometry and the pythagorean theorem. # (C) 2019 William Johansson, Västerås, Sweden # # email: william.johansson@abbindustrigymnasium.se #------------------------------------------------------------------------------------------------------------------- import math import trigwj as tr import pythagoras as pyt print('<---------------------------TRIANGELMÄSTAREN!--------------------------->') print('Välkommen till Triangelmästaren, där trianglarna är räta och svaren rätt!') print('') print('Vad vill du räkna med? Svara med motsvarande siffra.') calcvad= input('1= Pythagoras sats 2= Trigonometri 3= Vad är skillnaden? > ') if int(calcvad) == 1: print('') pyt.pythagoras() elif int(calcvad) == 2: print('') tr.trig() else: print('Har triangeln en rät vinkel?') osäkervad= input('1= Ja 2= Nej > ') if int(osäkervad) == 2: print('') print('Tyvärr kan det här programmet bara räkna med rätvinkliga trianglar. Lycka till ändå') else: print('Vad känner du till om triangeln?') PytOrTrig= input('1= Två längdmått 2= Ett längdmått, en vinkel 3= Bara att den är rätvinklig > ') if int(PytOrTrig) == 3: print('') print('Det finns inte mycket detta program kan göra för dig då, men vet bara att:') print('a^2 + b^2 = c^2') print('a och b är kateter och c är hypotenusan') print('') print('Lycka till ändå!') elif int(PytOrTrig) == 2: print('Då ska du använda trigonometri! Vill du använda det nu?') villanvända = input('1= Ja 2= Nej > ') if int(villanvända) == 1: print('') tr.trig() else: print('Okej, lycka till ändå!') else: print('Då kan du använda pythagoras sats! Vill du använda det nu?') villanvända2 = input('1= Ja 2= Nej > ') if int(villanvända2) == 1: print('') pyt.pythagoras() else: print('Okej, lycka till ändå!') print('') print('<---------------------------TRIANGELMÄSTAREN!--------------------------->') print('') print('Tack för att du använt Triangelmästaren! ') print('Av William Johansson 2019 med Python och modulen Python Math')
false
e2bdd194106558ee64aebcb4ca8c6618abb7a39b
gashanjakim/bioinformatics
/Biology Meets Programming - Bioinformatics for Beginners/FrequencyMap/FrequencyMap.py
698
4.125
4
def FrequencyMap(Text, k): #creates a dictionary to store pattern counts freq = {} n = len(Text) #ranges through each pattern and counts the number of k-mer for i in range(n-k+1): Pattern = Text[i:i+k] freq[Pattern] = 0 #the pattern is comparated with slices of sequences taken #from the sequence. if the slice and the pattern are #equal, then count increases at one. for j in range(0,len(Text) - len(Pattern) + 1): if text[j:(j+len(Pattern))] == Pattern: freq[Pattern] = freq[Pattern] + 1 return freq k = 3 text = "CGATATATCCATAG" freq = FrequencyMap(text, k) print(freq)
true
b4302eb0d54b4c861d0faaf8e2737f9bf3add44c
mddeloarhosen68/Array
/Quiz 2.py
458
4.1875
4
from array import * #Ex:1 a = array('i', [1, 2, 3]) for i in range(len(a)): b = array('i', [4, 5, 6]) print(a[i]+b[i],end='') #Ex:2 with function a = ([1,3,5,2]) a.sort() print(a[-1]) print(a) #Ex:3 without function list1 = [] num = int(input("Enter number of elements in list: ")) for i in range(1, num + 1): ele = int(input("Enter elements: ")) list1.append(ele) print("Largest element is:", max(list1))
true
0b335b53e1935e61f8efdcea1923e2827b495b55
Somi-Singh/python_loop_Questions
/guessing_game.py
298
4.1875
4
target_num=5 i=1 while i<=5: num=int(input("enter any num")) i+=1 if num==target_num: print("guess correct") break elif num>target_num: print("too high") elif num<target_num: print("too low") else: print("your program is finish")
false
3209d4971cd33e3129604775033a24f1ad1ed31f
eduardomarquesbh/Python
/lista.py
1,087
4.59375
5
print("Listas em Python") # uma lista começa com o indicie zero na primeira posição lista = ['Maria','João','José','Leda','Pedro','Tereza'] print('imprime toda lista') print(lista[:]) print('imprime elemento indice 3') print(lista[3]) print('imprime segundo elemento de trás para frente') print(lista[-2]) print('imprime um intervalo antes do elemento') print(lista[0:3]) print('imprime após um elemento') print(lista[2:]) print('imprime antes de um elemento') print(lista[:2]) print('adiciona um elemento') lista.append('Sandra') print(lista[:]) print('inserindo em uma determinada posição') lista.insert(2,'Sandra') print(lista[:]) print('adiciona uma nova lista a lista existente') lista.extend(['1','2']) print(lista[:]) print('procurando a posição de um elemento na lista') print(lista.index('Leda')) print('pesquisar se um elemento existe ou não em uma lista retorna true ou false') print('Pedro' in lista) print('cria uma lista com tipos diferentes') lista2 = ['Maria',2,2.3,True] print(lista2[:]) print('removendo um elemento') lista.remove('Maria') print(lista[:])
false
a7da427ebb9600e9f27e46c76f6abc3900fdbf5b
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-II/program-42.py
1,253
4.25
4
#!/usr/bin/env python3 ################################################################################### # # # Program purpose: Accepts six numbers as input and sorts them in ascending # # order. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 19, 2019 # # # ################################################################################### def read_numbers(size=0): valid = False int_list = [] while not valid: try: int_list = list(input("Enter six numbers: ").split(' ')) if len(int_list) != size: raise ValueError(f"invalid number of integers. Must be {size}") int_list = list(map(int, int_list)) valid = True except ValueError as ve: print(f"[ERROR]: {ve}") return sorted(int_list, reverse=True) if __name__ == "__main__": some_list = read_numbers(size=6) print(f"List of ints is: {some_list}")
true
41fb6a93f738c8354da277e41b165b08b92674d1
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/String/program-13.py
1,176
4.28125
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Gets user input and prints it back in upper and lower case. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : October 11, 2019 # # # ####################################################################################### def obtain_user_data(mess: str): is_valid = False data = '' while is_valid is False: try: data = input(mess) if len(data) == 0: raise ValueError('Please provide a string (or sentence)') is_valid = True except ValueError as ve: print(f'[ERROR]: {ve}') return data if __name__ == "__main__": user_data = obtain_user_data(mess='Enter a string: ') print(f'String in uppercase: {user_data.upper()}') print(f'String in lowercase: {user_data.lower()}')
true
f519b87a72e70af049b85450cf529db59473d1cf
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Array/program-9.py
1,188
4.5
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Appends item from a list to an array. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : January 20, 2019 # # # ############################################################################################ import array as arr from random import randint def random_list(low: int, high: int, size: int) -> list: if size < 0: raise ValueError(f"Invalid size '{size}' for new array") return [randint(low, high) for _ in range(size)] if __name__ == "__main__": rand_list = random_list(low=0, high=100, size=8) print(f"Random list: {rand_list}") array_nm = arr.array('i', []) print(f'Array before inclusion: {array_nm}') array_nm.fromlist(rand_list) print(f'Array after inserting list: {array_nm}')
true
ef11bf5e924c0cc2590cd973e815858e1d5727d2
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/List/program-70.py
934
4.28125
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Computes the depth of a dictionary. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : November 27, 2019 # # # ############################################################################################ def dict_depth(some_dict: dict) -> int: if isinstance(some_dict, dict): return 1 + (max(map(dict_depth, some_dict.values())) if some_dict else 0) return 0 if __name__ == "__main__": dic = {'a': 1, 'b': {'c': {'d': {}}}} print(dict_depth(some_dict=dic))
true
96ea576a9109a91dc1e23e43cac82490213ae3b3
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-II/program-56.py
1,565
4.1875
4
#!/usr/bin/env python3 #################################################################################### # # # Program purpose: Sums all numerical values (positive integers) embedded # # in a sentence. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 23, 2019 # # # #################################################################################### def read_data(mess: str): valid = False data = "" while not valid: try: data = str(input(mess).strip()) valid = True except ValueError as ve: print(f"[ERROR]: {ve}") return data def process_sum(data: str): data_tokens = data.split(" ") data_num = [] for x in range(len(data_tokens)): try: temp_int = float(data_tokens[x]) data_num.append(temp_int) except ValueError as ve: #print(f"[ERROR]: Not a number -> {data_tokens[x]}") 1 return {"sum": sum(data_num), "nums": data_num} if __name__ == "__main__": main_data = read_data(mess="Enter some text to process: ") dict_info = process_sum(data=main_data) print(f"List of numbers in text: {dict_info['nums']}") print(f" Sum of numbers in text: {dict_info['sum']}")
true
87db138ebadc7cdc8cd2655e8e2342ac7a77e8fb
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/String/program-11.py
1,430
4.21875
4
#!/usr/bin/env python3 ######################################################################################## # # # Program purpose: Removes the characters which have odd index values of a given # # string. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : October 11, 2019 # # # ######################################################################################## def obtain_user_data(mess: str): is_valid = False data = '' while is_valid is False: try: data = input(mess) if len(data) == 0: raise ValueError('Please provide some data') is_valid = True except ValueError as ve: print(f'[ERROR]: {ve}') return data def remove_odd_index_data(main_data: str): temp_data = '' for x in range(0, len(main_data), 2): temp_data += main_data[x] return temp_data if __name__ == "__main__": user_data = obtain_user_data(mess='Enter some string: ') new_data = remove_odd_index_data(main_data=user_data) print(f'After removing all odd index data: {new_data}')
true
e4a138045f3b7342b00479b36fb97472046bb611
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Dictionary/program-31.py
1,446
4.46875
4
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Prints the key, value and item in a dictionary. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : December 13, 2019 # # # ############################################################################################ import random def random_dict(low: int, high: int, size: int) -> dict: if low < 0: raise ValueError("Invalid value for low") if high < 0: raise ValueError("Invalid value for high") if size < 0: raise ValueError("Invalid value for the size") rand_keys = [random.randint(low, high) for _ in range(size)] rand_values = [random.randint(low, high) for _ in range(size)] return {k: v for (k, v) in zip(rand_keys, rand_values)} def do_display(main_dict: dict) -> None: print('key', 'value', 'count') for count, (key, value) in enumerate(main_dict.items(), 1): print(f'{key}\t{value}\t{count}') if __name__ == "__main__": new_dict = random_dict(low=0, high=20, size=15) print(f'New dictionary: {new_dict}') do_display(main_dict=new_dict)
true
b87b757a3f345d5e89f74d03993cfb21502e9a68
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-128.py
1,066
4.59375
5
# !/usr/bin/env python3 ####################################################################################### # # # Program purpose: Checks if there's a lowercase character in a string. # # Program Author : Happi Yvan <ivensteinpoker@gmail.com> # # Creation Date : September 2, 2019 # # # ####################################################################################### def is_lowercase_found(string=""): for x in string: if str.islower(x): return True return False if __name__ == "__main__": mainString = input("Enter some string: ") if is_lowercase_found(mainString): print(f"Lowercase character FOUND in string.") else: print("Lowercase character NOT FOUND in string.") # we could still have used. # print(any(c.islower() for c in mainString))
true