blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8c999f21b38fd1147e85a451ad278e2664a06a3b
midnightkali/w3resource.com-python-exercises
/Excercise Solutions/question-2.py
617
4.40625
4
''' 2. Write a Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number. Sample Output: Double the number of 15 = 30 Triple the number of 15 = 45 Quadruple the number of 15 = 60 Quintuple the number 15 = 75 ''' def compute(num): return lambda num2:num2 * num result = compute(2) print(f"Double the number of 15 = {result(15)}") result = compute(3) print(f"Triple the number of 15 = {result(15)}") result = compute(4) print(f"Quadruple the number of 15 = {result(15)}") result = compute(5) print(f"Quintuple the number of 15 = {result(15)}")
true
6787185c9fcaeacccc3cac1e620f4d64cfbe6927
wchamber01/Algorithms
/stock_prices/stock_prices.py
970
4.125
4
#!/usr/bin/python import argparse def find_max_profit(prices): #find highest_value in list highest_value = max(prices[1:]) # print(highest_value) #find lowest_value in list that occurs before the highest value for i in prices: temp_arr = prices.index(highest_value) # print(temp_arr) lowest_value = min(prices[:temp_arr]) # print(lowest_value) #max_profit = highest_value - lowest_value profit = highest_value - lowest_value # print(profit) return profit # find_max_profit(prices) if __name__ == '__main__': # This is just some code to accept inputs from the command line parser = argparse.ArgumentParser(description='Find max profit from prices.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price') args = parser.parse_args() print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers))
true
b2cf3c5d25e600356f1340baf4724f39bef92a8f
365cent/calculate_pi_with_turtle_py
/calculatePi.py
2,845
4.5625
5
""" References: https://stackoverflow.com/questions/37472761/filling-rectangles-with-colors-in-python-using-turtle https://www.blog.pythonlibrary.org/2012/08/06/python-using-turtles-for-drawing/ https://docs.python.org/3/library/turtle.html https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/ """ import random import math import time import turtle inside = 0 outside = 0 count = 0 iterations = 1000000 random.seed(int(round(time.time()*1000))) # INSERT CODE TO SEED THE RANDOM NUMBER GENERATOR HERE # Draw filled rectangle with turtle def rectangle(l, w): t.begin_fill() for i in range(2): t.right(90) t.forward(l) t.right(90) t.forward(w) t.end_fill() # Initial status widget def init(): t.setposition(150, 150) t.left(90) t.fillcolor("#eee") t.setposition(150, 150) for i in range(3): rectangle(300, 50) t.backward(100) t.right(90) # Display current status def display(): t.left(90) t.setposition(150, 150) t.fillcolor("#eee") t.pencolor("#" + time.strftime("%H%M%S")) # The color of time for i in range(3): rectangle(300, 50) move(150, -37.5) t.write(status[i], align="center", font=("Calibri", 16, "normal")) move(-150, -62.5) t.right(90) # Move turtle to relative location def move(x=None, y=None): t.setx(t.xcor() + x) t.sety(t.ycor() + y) # Set up turtle turtle.setup(1000, 600) turtle.delay(0) t = turtle.Turtle() t.speed(0) t.hideturtle() # Print status widget label = ["Total Number of points", "Points within circle", "Pi estimation"] t.penup() t.setposition(150, 150) t.right(90) for i in label: t.write(i, font=("Calibri", 12, "normal")) t.forward(100) t.left(90) init() # Draw circle t.setposition(-200, -200) t.pendown() t.circle(200) t.penup() # Draw square t.forward(200) t.pendown() for i in range(4): t.left(90) t.forward(400) t.penup() # Reset turtle speed #t.speed(6) # Estimation start for i in range(iterations): t.setposition(-400,-200) # select two random numbers between 0 and 1 x = random.random() y = random.random() move(x * 400, y * 400) d = t.distance(-200,0) # calculate distance from origin # increment the appropriate counter if d > 200: t.dot("#0a84ff") outside += 1 else: t.dot("#ff2d55") inside += 1 count += 1 pi = 4 * inside / count # calculate the value of Pi status = [count, inside, pi] display() print("Current status\> Total Number of points: {}, Points within circle: {}, Pi estimation: {}".format(count, inside, pi), end='\r') # Print current estimation status turtle.done() # Estimation End Print("The final result after {} times estimation is {}".format(iterations, pi)) # print result
true
f9f764c303cca5872cea4f868abcc073a979e9e5
tberhanu/all_trainings
/9_training/transpose*_matrix.py
1,502
4.75
5
""" Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] Note: 1 <= A.length <= 1000 1 <= A[0].length <= 1000 """ def transpose(matrix): """ Runtime: 64 ms, faster than 57.33% of Python3 online submissions for Transpose Matrix. The following line will zip the UNPACKED matrix which will return the transposed matrix but with each row as a tuple rather than as a list""" zipped = zip(* matrix) """ Remember 'list' is a function, so use 'map' to change all the tuples to list""" zipped = list(zipped) zipped = map(list, zipped) return list(zipped) def transpose2(matrix): """ Runtime: 64 ms, faster than 57.33% of Python3 online submissions for Transpose Matrix. """ matrix2 = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))] for i in range(len(matrix)): for j in range(len(matrix[0])): matrix2[j][i] = matrix[i][j] return matrix2 def transpose3(matrix): """Runtime: 64 ms, faster than 57.33% of Python3 online submissions for Transpose Matrix. """ return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] matrix = [[1, 2, 3], [3, 4, 5]] print(transpose(matrix)) print(transpose2(matrix)) print(transpose3(matrix))
true
d49312d3275d7af730b00dd4eff0844b9f8c9e7a
tberhanu/all_trainings
/revision_1_to_7/15_largest_prime_factor.py
358
4.125
4
""" 15. Given an int, what is the largest prime factor? """ def largest_prime_factor(num): i = 2 while i * i <= num: while num % i == 0: num = num // i i = i + 1 return max(2, num) print(largest_prime_factor(12)) print(largest_prime_factor(15)) print(largest_prime_factor(21)) print(largest_prime_factor(16))
false
d1ca4df1ebd74bf0e64444d1ede451425d783520
tberhanu/all_trainings
/9_training/921_add-parenthesis.py
1,607
4.34375
4
""" Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid. Example 1: Input: "())" Output: 1 Example 2: Input: "(((" Output: 3 Example 3: Input: "()" Output: 0 Example 4: Input: "()))((" Output: 4 Note: S.length <= 1000 S only consists of '(' and ')' characters. """ def minAddToMakeValid2(S): """Runtime: 44 ms, faster than 43.37% of Python3 online submissions for Minimum Add to Make Parentheses Valid. """ S = list(S) i = 1 while i < len(S): if i - 1 >= 0 and S[i-1] + S[i] == "()": del S[i] del S[i - 1] i = max(0, i - 2) else: i = i + 1 return len(S) def minAddToMakeValid(S): """Runtime: 40 ms, faster than 55.65% of Python3 online submissions for Minimum Add to Make Parentheses Valid. """ open, close = 0, 0 for s in S: if s == "(": open += 1 else: if open: open -= 1 else: close += 1 return open + close print(minAddToMakeValid("(()())((")) print(minAddToMakeValid("()))((")) print(minAddToMakeValid("(((")) print(minAddToMakeValid("("))
true
ccef15befdc8373f187d0be2b6fd3e205057e65b
tberhanu/all_trainings
/8_training/monotonic_array.py
1,193
4.1875
4
""" An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Output: true Example 2: Input: [6,5,4,4] Output: true Example 3: Input: [1,3,2] Output: false Example 4: Input: [1,2,4,5] Output: true Example 5: Input: [1,1,1] Output: true Note: 1 <= A.length <= 50000 -100000 <= A[i] <= 100000 """ def isMonotonic(A): """Runtime: 64 ms, faster than 90.07% of Python online submissions for Monotonic Array. """ status = 0 set = True for i in range(1, len(A)): diff = A[i] - A[i-1] if diff == 0: continue elif status == 0 and set: status = 1 if diff > 0 else -1 set = False if (diff > 0 and status < 0) or (diff < 0 and status > 0): return False return True print(isMonotonic([3,4,2,3])) print(isMonotonic([1,2,2,3])) print(isMonotonic([6,5,4,4])) print(isMonotonic([1,3,2])) print(isMonotonic([1,2,4,5])) print(isMonotonic([1,1,1]))
true
98976e9dbd53034092cdad20f46cec9573ed5769
tberhanu/all_trainings
/revision_1_to_7/13_array_flattening.py
352
4.1875
4
""" 13. Given a nested array, return a flattened version of it. Ex. [1, 2, [3, [4, 5], 6]] ---> [1, 2, 3, 4, 5, 6] """ from collections.abc import Iterable def flatten(arr): for a in arr: if isinstance(a, Iterable): yield from flatten(a) else: yield a print(list(flatten([1, 2, [3, [4, 5], 6]])))
true
1531e733cc5859b5be70b6b606c2c75488411c77
tberhanu/all_trainings
/9_training/73_set_matrix_zeroes.py
997
4.28125
4
""" Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] Follow up: A straight forward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution? """ def setZeroes(matrix): col, row = set(), set() for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: row.add(i) col.add(j) for i in row: for j in range(len(matrix[0])): matrix[i][j] = 0 for i in col: for j in range(len(matrix)): matrix[j][i] = 0 return matrix matrix = [ [1,1,1], [1,0,1], [1,1,1] ] setZeroes(matrix) print(matrix)
true
4ced710feb067c8c912875511f7af2294b529e03
tberhanu/all_trainings
/revision_1_to_7/8_reverse_array_inplace.py
294
4.15625
4
""" 8. Inplace reverse an array of characters """ def inplace_reverse(arr): i = 0 j = len(arr)-1 while i < j: arr[i], arr[j] = arr[j], arr[i] i = i + 1 j = j - 1 return arr print(inplace_reverse([1, 2, 3, 4])) print(inplace_reverse([1, 2, 3, 4, 5]))
false
7c6c0c78a813ec102b63072b31057cd5e909bbc6
tberhanu/all_trainings
/3_training/qn3_shortest_route.py
1,658
4.1875
4
#!/usr/bin/env python3 import networkx as nx import matplotlib.pyplot as plt def shortest_path(network, name1, name2): """shortest_path(network, name1, name2) --> a function taking a NETWORK and output and array of Strings as a shortest path from name1 to name2 --> Need to install networkx, and inbuilt python function --> Assuming the distance between adjancent names is constant for all cases so weight=1.0 assigned :param network: Dictionay of String as a KEY and a list of Strings as a VALUE :param name1: String :param name2: String :return: Array of Strings, as a shortest path from name1 to name2 """ graph = make_graph(network) path = nx.shortest_path(graph, source=name1, target=name2) return path def make_graph(network): graph = nx.Graph() for node, adjacents in network.items(): graph.add_node(node) for adj in adjacents: graph.add_edge(node, adj, weight=1.0) return graph if __name__ == "__main__": network = { 'Min': ['William', 'Jayden', 'Omar'], 'William': ['Min', 'Noam'], 'Jayden': ['Min', 'Amelia', 'Ren', 'Noam'], 'Ren': ['Jayden', 'Omar'], 'Amelia': ['Jayden', 'Adam', 'Miguel'], 'Adam': ['Amelia', 'Miguel', 'Sofia', 'Lucas'], 'Miguel': ['Amelia', 'Adam', 'Liam', 'Nathan'], 'Noam': ['Nathan', 'Jayden', 'William'], 'Omar': ['Ren', 'Min', 'Scott'] } print(shortest_path(network, "Jayden", "Adam")) print(shortest_path(network, "Adam", "Omar")) print(shortest_path(network, "Liam", "Nathan")) print(shortest_path(network, "Liam", "William"))
true
a42a1b8a508f5dad31c13eac7d6f4d605896155e
Marist-CMPT120-FA19/-Kathryn-McCullough--Project-10-
/censor.py
1,494
4.28125
4
#name: Kathryn McCullough #email: kathryn.mccullough1@marist.edu #description: This program references a file with words and a separate #file with a phrase and censors those words from the first into a third file. #goes through characters and replaces all letters with * #plus censores word with comma will still have comma def censor(word): for i in range(len(word)): if word[i].isalpha(): word=word[:i] + '*' + word [i+1:] return word def main(): file= input ("Enter the name of the file to censor: ") text= open(file, 'r') words_file= input ("Enter the name of the file containing the censord words: ") censored= open(words_file, 'r') censored_words= censored.read().split() censored_text= "" for line in text: words=line.split() #Checks if letters in one of the 'words' in line spells out censored word #If yes, replace with * for i in range(len(words)): word= "" for letter in words [i]: if letter.isalpha(): word+= letter if word in censored_words: words[i]= censor(words[i]) censored_text += " ".join(words) + '\n' #close files text.close() censored.close() #create and open final file to insert censoreed data and then close also newfile=open("censored:" + file, 'w') newfile.write(censored_text) newfile.close() main()
true
71a4d5d390639160838813bc0ff468853b248ddd
jjmaldonis/Data-Structures-Code
/pythoncrashcourse/intsertion.py
869
4.25
4
#if you import this module you can type help(insertion) and it will give you the help info below """ insertion sort script that demonstrates implementation of insertion sort. """ import random def insertion(l): """ implements insertion sort pass it a list, list will be modified in plase """ print ("in insertion function") for i in range(1,len(l)): for j in range(0,i): if l[i] < l[j]: tmp = l[i] l[i] = l[j] l[j] = tmp #l[j], l[i] = l[i], l[j] #this is the same thing in one line return l def main(): l = range(100) random.shuffle(l) #l = [6,7,24,1,18,23,4] #l = [9,7,4,2] print( "Before Sort: {0}".format(l) ) insertion(l) #you don't need l = print( "After Sort: {0}".format(l) ) if __name__ == "__main__": main()
true
8ff7e379b9a79d6c8094165e0ab6a9fb089d753a
jtwray/Intro-Python-I
/src/07_slices.py
1,789
4.625
5
""" Python exposes a terse and intuitive syntax for performing slicing on lists and strings. This makes it easy to reference only a portion of a list or string. This Stack Overflow answer provides a brief but thorough overview: https://stackoverflow.com/a/509295 Use Python's slice syntax to achieve the following: """ a = [2, 4, 1, 7, 9, 6] # Output the second element: 4: secondelement=a[slice(1,2)] print(secondelement) # print(a[1]) # Output the second-to-last element: 9 # print(a[-1]) # secondToLast=a[slice(4,5)] # print(secondToLast) # secondToLast=a[4:5] # print(secondToLast) # secondToLast=a[slice(-2,-3,-1)] # start from the 2nd to last, stop before the 3rd to last, go backwards i.e. right to left # print(secondToLast) # secondToLast=a[-2:-3:-1] # start from the 2nd to last, stop before the 3rd to last, go backwards i.e. right to left # print(secondToLast) # secondToLast=a[slice(4,-1)] # print(secondToLast) # secondToLast=a[4:-1] # print(secondToLast) # secondToLast=a[slice(-2,-1)]# start at the 2nd to last item: stop before the last item # print(secondToLast) secondToLast=a[-2:-1] # start at the 2nd to last item: stop before the last item print(secondToLast) # Output the last three elements in the array: [7, 9, 6] #slice(start,stop,step) lastThree= a[slice(3,6,1)] print(lastThree) lastThree= a[-3:] print(lastThree) # Output the two middle elements in the array: [1, 7] middle2=a[slice(2,4,1)] print(middle2) # Output every element except the first one: [4, 1, 7, 9, 6] notNum1=a[slice(1,6,1)] print(notNum1) # Output every element except the last one: [2, 4, 1, 7, 9] notLastNum=a[slice(0,-1,1)] print(notLastNum) # For string s... s = "Hello, world!" # Output just the 8th-12th characters: "world" werld=s[slice(7,12)] print(werld)
true
7a6b08c52a1f57f07dc3c6be620b3df74620fa64
wsullivan17/Cashier
/Cashier.py
1,678
4.125
4
#Automated cashier program #Willard Sullivan, 2020 #total cost of items total = 0 done = "" from users import users_dict, pwds_dict from items import items_dict, cost_dict print("Welcome to the Automated Cashier Program. ") go = input("Type the Enter key to continue. ") while go != "": go = input("Type the Enter key to continue. ") user = input("What is your User ID? ") #asks for user id, checks if user exists user_int = int(user) while user_int<0 or user_int>(len(users_dict)): print("That user does not exist. Please try again: ") user = input("What is your User ID? ") user_int = int(user) pwd = input("What is your password? ") #asks for password, allows user to continue with correct password while pwd != pwds_dict[user]: print("Incorrect password.") pwd = input("What is your password? ") print("Hello, " + users_dict[user] + ". Welcome to your shopping account. ") while done != "y" : #allows user to select items and how many. allows user to continue or quit using "y" item = input("Type the number corresponding to the item you would like to purchase. 1)Eggs 2)Milk 3)Bread ") item_int = int(item) while item_int<0 or item_int>(len(items_dict)): print("Sorry, that item does not exist.") item = input("Type the number corresponding to the item you would like to purchase. 1)Eggs 2)Milk 3)Bread ") item_int = int(item) amount = int(input("Type the amount of " + items_dict[item] + " you would like. ")) total = (total + ((cost_dict[item])*amount)) done = input("Type 'y' if you are done shopping. Otherwise, type any key. ") print("Your total is: $" + str(total)) #calculates total cost
true
1e2b7e6f44c7fba2e1aa916481a50a4dc86e5195
maianhtrnguyen/Assignment-2
/Assignment/PythonLearningProject1-master/helloWorld.py
1,675
4.1875
4
# Install the package Pillow: pip install pillow from PIL import Image # The documentation is here, # https://pillow.readthedocs.io/en/stable/reference/Image.html# # please just look at the Image Module and Image Class section # Read about this module/class and its relevant information, but dont worry about other classes/modules for now # (unless you have to) # Read an image using Pillow, using filename old_image = Image.open("./images/sample.jpg") # Open the old image old_image.show() # In the terminal, hit enter to continue input("HIT ENTER TO CONTINUE......") new_image = Image.new("RGB", old_image.size) # Loop over an image, pixel by pixel for x in range(old_image.width): for y in range(old_image.height): # Get the value of the current pixel in the old image, it will be a tuple in format (R,G,B) pixel_value = old_image.getpixel((x, y)) # Update the value of the new image with the value from the old image pixel, but using Red=255 new_image.putpixel((x,y), (255, pixel_value[1], pixel_value[2])) # Show the newly modified image, tada new_image.show() # ===================== ASSIGNMENT =========================== # Please create a Python module (.py file) contains AT LEAST 3 FUNCTIONS as follow: # 1. Apply a filter (like instagram filter) of your choice to a given image (input: filename) # 2. Rotate an image 90 degree (do not use the rotate function of PIL), using pixel modification (cpying and moving pixel around) (like above) (input: fileName). # 3. HARD: Given an image with white background, replace the background with a given background image (input: originalFileName, backgroundFileName)
true
21939208c9d75a5e10e77f874041e111051d7be2
AtieDag/Project-Euler
/Problem14.py
572
4.125
4
# The following iterative sequence is defined for the set of positive integers: from functools import lru_cache @lru_cache(maxsize=100) def collatz_sequence(n, terms=0): terms += 1 if n == 1: return terms # n is even if n % 2 == 0: return collatz_sequence(n / 2, terms) # n is odd return collatz_sequence(3 * n + 1, terms) if __name__ == '__main__': memo = {1: 1} steps = 1000000 for number in range(1, steps): count = collatz_sequence(number) memo[number] = count print(max(memo, key=memo.get))
true
18f31e559b7c838ff226b6dad3bc0f25665930cc
KostadinovShalon/curso-de-python-2020
/dia 1/ejercicios/ejercicio_15.py
683
4.1875
4
# 15. Pidele al usuario que ingrese una lista de palabras y le digas cual fue la mas larga. Recuerda que deben de ser # palabras, por lo que frases no cuentan! palabra_mas_larga = "" while True: palabra = input("Introduzca una palabra [O introduzca * para salir]: ") if palabra == "*": break palabra_valida = True for caracter in palabra: if caracter == ' ': palabra_valida = False print("No cuentan frases!! Intenta de nuevo") break if palabra_valida: if len(palabra) > len(palabra_mas_larga): palabra_mas_larga = palabra print(f"La palabra mas larga introducida fue {palabra_mas_larga}")
false
e2e3884345256a114aa8fe57fd10fd8ce388e679
RisingLight/Python_Practice
/Challenge questions/TejaSreeChand/wordscramb challenge3 .py
1,349
4.25
4
import random import os def shuf(string): ltemp=string[1:len(string)-1] # taking only the mid part { change it into string[0:len(string)] for a full words shuffle ltemp=list(ltemp) # convert the word into alphabet list eg: "hey" -> ["h","e","y"] random.shuffle(ltemp) # shuffles the alphabet ltemp="".join(ltemp) # join the alphabet back to a word ltemp=string[0]+ltemp+string[len(string)-1] # add the first and the end alphabet to the word return ltemp # returns the shuffled word def filewrite(stext): f=open("output.txt","w") f.write(stext) def wordscramble(): #f=open("word.txt","r") fn=input("Enter file name:") f=open(fn,"r") text=f.read() print("The text before scrambling:", text) text=text.split() # this splits words from string stext=[] #scramble list { empty } for i in range(len(text)): stext.append(shuf(text[i])) # shuffles the word mid part only , starting and ending alphabets are not touched stext=" ".join(stext) print("The text after scrambling:") # joins the words into a string again print(stext) filewrite(stext) wordscramble() # scramble's the file text
true
b4839a749136a1cace5be79885b0e72098fab39f
vansh1999/Python_core_and_advanced
/functions/decorators.py
2,034
4.59375
5
''' Decorators in Python A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. Functions in Python are first class citizens. This means that they support operations such as being passed as an argument, returned from a function, modified, and assigned to a variable. This is a fundamental concept to understand before we delve into creating Python decorators. 1. Assigning Functions to Variables 2. Defining Functions Inside other Functions 3. Passing Functions as Arguments to other Functions def plus_one(number): return number + 1 def function_call(function): number_to_add = 5 return function(number_to_add) function_call(plus_one) output - 6 4. Functions Returning other Functions 5. Nested Functions have access to the Enclosing Function's Variable Scope Python allows a nested function to access the outer scope of the enclosing function. This is a critical concept in decorators -- this pattern is known as a Closure. def print_message(message): "Enclosong Function" def message_sender(): "Nested Function" print(message) message_sender() print_message("Some random message") output -- Some random message ''' # Creating decorators ''' def upper_decor(function): def wrapper(): fun = function() make_uppercase = fun.upper() return make_uppercase return wrapper # ---------------------- # def say_hi(): # return "hello there!" # decorate = upper_decor(say_hi) # print(decorate()) # ---------------------------- # this can be -- @upper_decor def say_hi(): return "hello there!" print(say_hi()) ''' # def decorfun(fun): # def inner(n): # result = fun(n) # result += " how are yo ?" # return result # return inner # @decorfun # def hello(name): # return " hello " + name # print(hello("vansh "))
true
35435a318e2262d5b7fce50deae1fd3fa82aad48
vansh1999/Python_core_and_advanced
/sequencedatatype/tuples/tuple.py
715
4.125
4
# declare a tuple colors = ("r" , "b" , "g") print(colors) # tuple packaging - # Python Tuple packing is the term for packing a sequence of values into a tuple without using parentheses. crl = 1,2,3 print(crl) # tuble unpackaging - a,b,c = crl print(a,b,c) # Crete tuple with single elements tupl1 = ('n') #< -- output = a print(tupl1) tupl2 = ('n','m') # <-- output = ('n', 'm') print(tupl2) # to declare tuple with single item do use --> "," in the end tupl3 = ('n' , ) print(tupl3) # tupl3.remove('n') # print(tupl3) < - error # tupl3[0] = "m" # print(tupl3) < -- error # can be indexed bcz ordered print(tupl3[0]) # cannot use - > # append() , extends() , insert() , remove() , clear()
true
02f42d9c69c3ab2b7dec8c56333af234ae75da7a
chenPerach/Open-Vision
/libs/geometry/point.py
755
4.21875
4
import math class vector: """ a simple class representing a vector """ def __init__(self,x:float,y:float): self.x = x self.y = y def __add__(self,vec): return vector(self.x - vec.x,self.y - vec.y) def size(self): return math.sqrt(math.pow(self.x,2) + math.pow(self.y,2)) def normelize(self): angle = math.atan2(x=self.x,y=self.y) return vector(math.cos(angle),math.sin(angle)) def slope(self): return float(y/x) def __sub__(self,vec): return vector(self.x - vec.x,self.y - vec.y) def __truediv__(self,num): return vector(self.x/num,self.y/num) def __mul__(self,num): return vector(self.x*num,self.y*num)
false
8b22fc6b4b4f6b3cf28f7c2b3dfc1f03ac301fb4
evroandrew/python_tasks
/task8.py
2,322
4.21875
4
import argparse MSG_INFO = 'To output Fibonacci numbers within the specified range, enter range: ' MSG_ERROR = 'Use any numbers, instead of you entered.' MSG_FIRST_ELEMENT = 'Enter first argument of range: ' MSG_SECOND_ELEMENT = 'Enter second argument of range: ' ERRORS = (argparse.ArgumentError, TypeError, argparse.ArgumentTypeError) class RangeOfFibonacciNumbers: """ The main task of this class is to output Fibonacci numbers within the specified range. """ def __init__(self, a, b): self.a, self.b = sorted([a, b]) # modified str method to show a comma separated string of numbers def __repr__(self): return ', '.join(str(x) for x in self.numbers() if self.a < x) # generator that produces a number in a given range def numbers(self): result = [] first_number, second_number = 0, 1 while first_number < self.b: yield first_number first_number, second_number = second_number, first_number + second_number def main(): try: parser = argparse.ArgumentParser(description='Output Fibonacci numbers within the specified range', exit_on_error=True) parser.add_argument('a', nargs='?', type=float, help='argument a for specified range') parser.add_argument('b', nargs='?', type=float, help='argument b for specified range') args = parser.parse_args() if args.b is None: try: print(MSG_INFO) a = 'abs' while a == 'abs': try: a = float(input(MSG_FIRST_ELEMENT)) except ValueError as exc: print(f'{MSG_ERROR} {str(exc)}') b = 'abs' while b == 'abs': try: b = float(input(MSG_SECOND_ELEMENT)) except ValueError as exc: print(f'{MSG_ERROR} {str(exc)}') print(RangeOfFibonacciNumbers(a, b)) except ValueError as exc: print(f'{MSG_ERROR} {str(exc)}') else: print(RangeOfFibonacciNumbers(args.a, args.b)) except ERRORS as exc: print(f'{MSG_ERROR} {str(exc)}') if __name__ == '__main__': main()
true
9c9c562ac2a07f66c4d4202ea003f9ed308c0d5a
Praveen-Kumar-Bairagi/Python_Logical_Quetions
/ifelse_python/char.py
413
4.25
4
char=str(input("enter the char")) if char>="a" and char<="z" or char<"A" and char<="Z": print("it is char") number=float(input("enter the number")) if number>=0 and number<=200: print("it is digit") specialchar=input("enter the specialchar") if specialchar!=char and specialchar!=number: print("it is specialchar") else: print("it is not digit")
true
aad6088e046f4b4f333441f26ed6a65d50f260a3
Praveen-Kumar-Bairagi/Python_Logical_Quetions
/ifelse_python/prime.py
883
4.15625
4
# num=int(input("enter the num")) # if num==1: # print("it is not prime number") # if num%2!=0: # print("it is prime number") # if num%5!=0: # print("it is prime number") # else: # print("it is prime number") Sex = input("enter sex M\F") material_status = input("enter the metarial status Y or N") Age = input("enter a age") if Sex=="Female": if material_status=="y": print("she will job in urban area") else: print("she will not do job") elif Sex=="Male": if material_staus=="y": if age>20 and age<40: print("he can do work any where") elif age>40 and age<60: print("he will job in urban area") else: print("he will not do work") else: print("he can't") else: print("gender is not valid")
false
c0a95dfdf5d086724bbb96875598facac45618fd
eliseoarivera/cs50transfer
/intro-python/day-one/ageCheck.py
485
4.28125
4
age = input("How old are you?") """if age >= "18": print("You're old enough to vote!") else: print("You're not old enough to vote.")""" age = input("How old are you?") # Read this as "Set age equal to whatever string the user types." age = int(age) # We reassign the variable information here. # In essence, "Set age equal to an integer expression of whatever the user typed." if age >= 18: print("You're old enough to vote!") else: print("You're not old enough to vote.")
true
56bd713a364a7abd0657341e45f71b57e2a611ef
eliseoarivera/cs50transfer
/intro-python/day-one/functions.py
1,551
4.4375
4
"""def shout(name): name = name.upper() return "HELLO " + name + "!" print(shout("Britney"))""" """def costForDisney(adults, children, days): adult_cost = adults * 100 print("Calculated adult cost at " + str(adult_cost)) child_cost = children * 90 print("Calculated child cost at " + str(child_cost)) daily_cost = adult_cost + child_cost total_cost = daily_cost * days return total_cost print(costForDisney(3,5,10))""" """def num_of_letters(name): name = len(name) return name print(num_of_letters("Sandwich"))""" #Write a function that takes in three numbers and returns the product of all three """def productOf(num1, num2, num3): total_cost = num1 * num2 * num3 return total_cost print(productOf(4,5,6))""" #Write a function that takes in a user's name and then returns their name""" """def userName(name): name = input("What is your name?") return "Hello " + name + "!" print(userName("name"))""" # Define the function! """def personalized_age_check(name, age): if age >= 18: return "Congratulations " + name + "! You're old enough to vote." else: time_left = 18 - age return "Sorry, " + name + ". You can't vote for another " + str(time_left) + " years." # Call the function print(personalized_age_check("Jeff", 28)) print(personalized_age_check("Zara", 14))""" """def add(x, y): total = x + y return total # Call print(add(5, 22))""" # Defenition def add(x, y): print("Adding your numbers") total = x + y return str(total) + "\nFinished adding." # Call print(add(5, 22))
true
a8803c9a755d33efa0a111eae2b80cc2573803de
tcraven96/Cracking-the-Coding-Interview
/Cracking the Coding Interview/Question1-1.py
798
4.1875
4
# Implement an algorithm to determine if each string has all unique characters. # What if you cannot use additional data structures? import unittest # Goes through string, replaces element found once with "" so that duplicates are not replaced. # Will return if duplicate characters are found in the string. def unique(s): for elem in s: s = s.replace(elem, "", 1) if elem in s: return False return True # Unit Testing class UniqueTestCase(unittest.TestCase): """Tests for `primes.py`.""" def test_is_dog_unique(self): """Is dog successfully determined to be unique?""" self.assertTrue(unique("dog")) def test_is_doggo_not_unique(self): """Is doggo correctly determined not to be prime?""" self.assertFalse(unique("doggo"), msg='Doggo is not unique!')
true
7d9982d39a2f8a6937dfded0ddc2a03f00a6017d
jeanggabriel/jean-scripts
/curso em video/programaresolucaoporcramer3x3empython.py
1,761
4.21875
4
print ("\n Programa em Python para resolver um sistema de equa��es com tr�s inc�gnitas") print ("\n Estou definindo um sistema de tr�s equa��es com tr�s inc�gnitas desta forma:") print ("\n \n ax + by + cz = R1 \n dx + ey + fz = R2 \n gx + hy + iz = R3 \n") print ("\n Digite os valores para: \n") # O usu�rio d� valores aos coeficientes a = int(input("a \n")) b = int(input("b \n")) c = int(input("c \n")) r1 = int(input("r1 \n")) d = int(input("d \n")) e = int(input("e \n")) f = int(input("f \n")) r2 = int(input("r2 \n")) g = int(input("g \n")) h = int(input("h \n")) i = int(input("i \n")) r3 = int(input("r3 \n")) # Aqui � a regra de Cramer, propriamente dita. det = ((a * e * i) + (b * f * g) + (c * d * h)) - ((c * e * g) + (a * f * h) + (b * d * i)) detx = ((r1 * e * i) + (b * f * r3) + (c * r2 * h)) - ((c * e * r3) + (r1 * f * h) + (b * r2 * i)) dety = ((a * r2 * i) + (r1 * f * g) + (c * d * r3)) - ((c * r2 * g) + (a * f * r3) + (r1 * d * i)) detz = ((a * e * r3) + (b * r2 * g) + (r1 * d * h)) - ((r1 * e * g) + (a * r2 * h) + (b * d * r3)) # Define os valores das inc�gnitas, com casas decimais. if ((det == 0) and (detx !=0) and (dety !=0) and (detz !=0)): print ("\n\n ====[ Sistema Imposs�vel ]====") elif ((det == 0) and (detx == 0) and (dety == 0) and (detz == 0)): print("\n\n ====[ Sistema Poss�vel e Indeterminado ]====" ) else: x = (round(detx, 3) / round(det, 3)) y = (round(dety, 3) / round(det, 3)) z = (round(detz, 3) / round(det, 3)) print ("\n\n====[ Sistema Possivel e Determinado ]====") print ("\nOs resultados s�o (aproximados com 4 casas decimais):") print ("\n x = %.4f" % x) print ("\n y = %.4f" % y) print ("\n z = %.4f" % z) print() # Fim
false
f5bc910e44639ae828c56017c5f659e8c02c370c
LizaShengelia/100-Days-of-Code--Python
/Day10.Project.py
1,278
4.3125
4
from art import logo #add def add(n1, n2): return n1 + n2 #subtract def subtract(n1, n2): return n1 - n2 #multiply def multiply(n1, n2): return n1 * n2 #divide def divide(n1, n2): return n1 / n2 operations = { "+": add, "-": subtract, "*": multiply, "/": divide } def calculator(): print(logo) num1 = float(input("What is first number?: ")) for math in operations: print(math) operation_symbol = input("Pick an operation from this line above: ") num2 = float(input("What is next number?: ")) answer1 = operations[operation_symbol](num1, num2) final_num = print(f"{num1} {operation_symbol} {num2} = {answer1}") question = input(f"Type 'y' to continue calculating with {answer1} or type 'n' to exit: ") should_continue = True while should_continue: num3 = float(input("What is next number?: ")) operation_symbol = input("Pick another operation from this line above: ") answer2 = operations[operation_symbol](answer1, num3) print(f"{answer1} {operation_symbol} {num3} = {answer2}") question = input(f"Type 'y' to continue calculating with {final_num} or type 'n' to exit: ") if question == 'y': answer1 = answer2 else: should_continue = False calculator() calculator()
true
df6c4c6355a62b8545bb50779b624a3ad6ce8a3c
ermanh/dailycoding
/20200715_inversion_count.py
2,116
4.1875
4
''' 2020-07-15 [from dailycodingproblems.com #44] We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions it has. Do this faster than O(N^2) time. You may assume each element in the array is distinct. For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. ''' # Solution comments: # Used merge sort to perform recursive comparisons between elements in the # right array with elements in the left array, with O(n log n) performance class Inversions: def __init__(self, array): self.array = array self.counts = 0 self.result = self.merge_sort(self.array) def count(self): return self.counts def merge_sort(self, array): if len(array) < 2: return array result = [] midpoint = int(len(array) / 2) left = self.merge_sort(array[:midpoint]) right = self.merge_sort(array[midpoint:]) i = 0 j = 0 while i < len(left) and j < len(right): if left[i] > right[j]: result.append(right[j]) j += 1 self.counts += (len(left) - i) else: result.append(left[i]) i += 1 result += left[i:] result += right[j:] return result ''' # TESTS Inversions([1, 2, 3, 4, 5]).count() == 0 Inversions([2, 1, 3, 4, 5]).count() == 1 Inversions([2, 1, 4, 3, 5]).count() == 2 Inversions([2, 4, 1, 3, 5]).count() == 3 Inversions([3, 2, 1, 5, 4]).count() == 4 Inversions([2, 3, 5, 4, 1]).count() == 5 Inversions([4, 2, 5, 1, 3]).count() == 6 Inversions([4, 5, 2, 1, 3]).count() == 7 Inversions([4, 5, 2, 3, 1]).count() == 8 Inversions([4, 5, 3, 2, 1]).count() == 9 Inversions([5, 4, 3, 2, 1]).count() == 10 '''
true
89a63d37c1520e8a2e2adeb42a92fbf0214cf72a
ermanh/dailycoding
/20200706_balanced_brackets.py
1,509
4.25
4
''' 2020-07-06 [from dailycodingproblem.com #27] Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). For example, given the string "([])[]({})", you should return true. Given the string "([)]" or "((()", you should return false. ''' def balanced(string): # start with placeholder to avoid index error / clumsy empty list checking ledger = [' '] for s in string: last_open_bracket = ledger[-1] if s not in '({[]})': pass if s in '({[': if last_open_bracket not in ' ({[': return False ledger.append(s) elif s in ')}]': if ( (s == ')' and last_open_bracket == '(') or (s == '}' and last_open_bracket == '{') or (s == ']' and last_open_bracket == '[') ): ledger.pop() else: return False if ledger[-1] != ' ': return False return True ''' # TESTS (must all return True) # Base cases from question balanced("([])[]({})") == True balanced("([)]") == False balanced("((()") == False balanced("((((((((((asdf))))))))))") == True balanced("((((((((((asdf)))))))))))))") == False # No brackets should still return True balanced("asdf") == True # Starting with a closing bracket should return False balanced("]asdf[") == False balanced("))asdf((") == False balanced("}}}asdf") == False '''
true
f06e6cb2349160b53b3897dee89b9a8620b47a4a
ermanh/dailycoding
/20200727_line_breaks.py
1,604
4.25
4
''' 2020-07-27 [from dailycodingproblem.com #57] Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less. You must break it up so that words don't break across lines. Each line has to have the maximum possible amount of words. If there's no way to break the text up, then return null. You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word. For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10. ''' def line_breaks(string, k): lines = [] line = '' for word in string.split(' '): if line == '': line = word else: if len(line + ' ' + word) <= k: line += ' ' + word else: lines.append(line) line = word lines.append(line) return lines ''' # TESTS line_breaks("the quick brown fox jumps over the lazy dog", 5) == [ "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] line_breaks("the quick brown fox jumps over the lazy dog", 10) == [ "the quick", "brown fox", "jumps over", "the lazy", "dog"] line_breaks("the quick brown fox jumps over the lazy dog", 15) == [ 'the quick brown', 'fox jumps over', 'the lazy dog'] line_breaks("the quick brown fox jumps over the lazy dog", 20) == [ 'the quick brown fox', 'jumps over the lazy', 'dog'] '''
true
d6a249c5f49bae6495eeaaf2fe118286fe9f55e5
cartoonshow57/SmallPythonPrograms
/multiples_of_num.py
386
4.46875
4
"""This program takes a positive integer and returns a list that contains first five multiples of that number""" def list_of_multiples(num1): lst = [] for i in range(1, 6): multiple = num1 * i lst.append(multiple) return lst num = int(input("Enter a positive number: ")) print("The first five multiples of", num, "are", list_of_multiples(num)) input()
true
de55a87bc414dc26a65f9b12d350550779446579
cartoonshow57/SmallPythonPrograms
/nested_loop.py
252
4.25
4
# A dummy program for how a nested loop works print("Nested loop example") print("-------------------------------") for i in range(1, 4, 1): for j in range(1, 1001, 999): print(format(i * j, "8d"), end="") print() print("EOP") input()
true
5cf128f4cb83571f291b8d6981914cb0106c372a
cartoonshow57/SmallPythonPrograms
/sum_of_array.py
392
4.21875
4
# This program prints the sum of all the elements in an array def sum_of_array(arr1): total = sum(list(arr1)) return total arr = [] n = int(input("Enter the number of elements in the array: ")) for i in range(n): arr.append(int(input("Enter no. in array: "))) print("The given array is,", arr) print("The sum of given elements in the array is", sum_of_array(arr)) input()
true
89a4b8735d13a7a2536d3fa18c80cda5c8b46b68
cartoonshow57/SmallPythonPrograms
/array_replacement.py
661
4.21875
4
"""Given an array of n terms and an integer m, this program modifies the given array as arr[i] = (arr[i-1]+1) % m and return that array""" def array_modification(arr1, m1): test_arr = [] index = 0 for _ in arr1: s = (arr1[index - 1] + 1) % m1 test_arr.append(s) index += 1 return test_arr arr = [] n = eval(input("Enter the number of elements in the array: ")) for j in range(n): arr.append(eval(input("Enter array element: "))) m = eval(input("The modulo will be taken with which number? ")) print("The given array is:", arr) print("The modified array comes out to be:", array_modification(arr, m)) input()
true
40247c58ddd68593214c719ac84db9252174b69c
cartoonshow57/SmallPythonPrograms
/first_and_last.py
431
4.1875
4
"""This program takes an array and deletes the first and last element of the array""" def remove_element(arr1): del arr1[0] del arr1[-1] return arr1 arr = [] n = int(input("Enter number of elements in the list: ")) for i in range(n): arr.append(int(input("Enter array element: "))) print("The given list is: ") print(arr) print("After removing first and last element: ") print(remove_element(arr)) input()
true
8c841eabc2a03af875f2b7286a86c2e5ac14eae4
motirase/holbertonschool-higher_level_programming-1
/0x07-python-test_driven_development/0-add_integer.py~
472
4.21875
4
#!/usr/bin/python3 """ function 0-add_integer adds two integers """ def add_integer(a, b=98): """adds two numbers >>> add_integer(4, 3) 7 >>> add_integer(5, 5) 10 """ fnum = 0 if type(a) is int or type(a) is float: fnum += int(a) else: raise TypeError("a must be an integer") if type(b) is int or type(b) is float: fnum += int(b) else: raise TypeError("b must be an integer") return fnum
true
bf094483c1d4fcc049e9fcb3aab8c57e8429badf
hly189/hw
/lab3.py
1,585
4.1875
4
def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) def sum(n): if n==0: return 0 else: return n + sum(n-1) def ab_plus_c(a,b,c): if b==0: return c else: return a + ab_plus_c(a, b-1,c) def square(x): return x*x def summation(n, term): """ >>> summation(3, square) 14 """ if n==0: return term(0) else: return term(n) + summation(n-1, term) def hailstone(n): i = 0 print(n) while n != 1: if n%2==0: n = n//2 else: n = n*3+1 i = i +1 print(n) return i + 1 def hailstone2(n): print(n) if n==1: return if n%2==0: return hailstone2(n//2) else: return hailstone2(n*3+1) def compose1(f, g): """"Return a function h, such that h(x) = f(g(x)).""" def h(x): return f(g(x)) return h def repeated(f, n): if n==0: return lambda x: x else: return compose1(f, repeated(f, n - 1)) def factorial(n): i, total = 0, 1 if n==0: return 1 else: while i < n: total = total*(i+1) i = i +1 return total def falling(n, k): """ Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 """ total, i = 1, 0 if k==0: return 1 else: while i < k: total = total * n n = n-1 i = i+1 return total def falling2(n, k): """ Compute the falling factorial of n to depth k. >>> falling2(6, 3) # 6 * 5 * 4 120 >>> falling2(4, 0) 1 """ if k==0: return 1 else: return n * falling2(n-1, k-1)
false
fb7d4013fd9394072a043c958e1e35b1ff8f3b63
Dyke-F/Udacity_DSA_Project1
/Task4.py
1,441
4.125
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of numbers> The list of numbers should be print out one per line in lexicographic order with no duplicates. """ def find_telemarketers(data1: list, data2: list): caller = set() responder = set() texter = set() reciever = set() for call in data1: caller.add(call[0]) responder.add(call[1]) for call in data2: texter.add(call[0]) reciever.add(call[1]) prob_telemarketers = [] RespTextRecieves = set().union(responder, texter, reciever) for contact in caller: if contact not in RespTextRecieves: prob_telemarketers.append(contact) return sorted(prob_telemarketers) prob_telemarketers = find_telemarketers(calls, texts) print("These numbers could be telemarketers:") for prob_telemarketer in prob_telemarketers: print(prob_telemarketer)
true
d6396e1980649d9fcfbe3e5a50f3fb6f37016731
aditya-sengupta/misc
/ProjectEuler/Q19.py
1,067
4.21875
4
"""You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?""" def weekday_shift(month, year): if(month == 2): if(year%400 == 0 or (year%4 == 0 and year%100 != 0)): return 1 return 0 if(month in [4, 6, 9, 11]): return 2 return 3 def first_of_month(month, year): if(month == 2 and year == 1983): return 2 elif(month == 1 and year == 1900): return 1 elif(month > 1): return (weekday_shift(month - 1, year) + first_of_month(month - 1, year))%7 else: return (weekday_shift(12, year - 1) + first_of_month(12, year - 1))%7
true
5d393e90f23624f1a27ca7af73fa9606e08beaf4
B3rtje/dataV2-labs
/module-1/Code-Simplicity-Efficiency/your-code/challenge-2_test.py
1,678
4.25
4
import string import random def new_string(length): letters = string.ascii_lowercase+string.digits str = ''.join(random.choice(letters) for num in range(length)) return str #print(get_random_string(10)) def string_gen (): strings = [] number_of_strings = input("How many strings do you want to generate? ") minimum_length = input("What is the minimum length that you want? ") maximum_length = input("What is the max length that you want? ") while not number_of_strings.isnumeric(): print("We only accept numeric values.") number_of_strings = input("How many strings do you want to generate?") while not minimum_length.isnumeric(): print("We only accept numeric values. ") minimum_length = input("What the minimum length that you want? ") while not maximum_length.isnumeric(): print("We only accept numeric values. ") maximum_length = input("What is the max length that you want? ") number_of_strings = int(number_of_strings) minimum_length = int(minimum_length) maximum_length = int(maximum_length) while True: if maximum_length < minimum_length: print("Program reboots because your max is smaller than your minimum") string_gen() break else: break final_length = [minimum_length, maximum_length] final_length = random.choice(final_length) while number_of_strings > 0: string = new_string(final_length) strings.append(string) number_of_strings = number_of_strings - 1 return strings print(string_gen())
true
486440929bfc62b5fc48823002c695afeacd67bb
sailesh190/pyclass
/mycode/add_book.py
252
4.375
4
address_book = [] for item in range(3): name = input("Enter your name:") email = input("Enter your email:") phone = input("Enter your phone number:") address_book.append(dict(name=name, email=email, phone=phone)) print(address_book)
true
405fbc0f2d07a41d15ff248af2e429e45de498e7
AhmUgEk/tictactoe
/tictactoe_functions.py
1,974
4.125
4
""" TicTacToe game supporting functions. """ # Imports: import random def display_board(board): print(f' {board[1]} | {board[2]} | {board[3]} \n-----------\n {board[4]} | {board[5]} | {board[6]}\ \n-----------\n {board[7]} | {board[8]} | {board[9]} \n') def player_input(): marker = 0 while marker == 0: choice = str(input('Choose whether to be "X" or "O": ')).upper() if choice == 'X' or choice == 'O': marker += 1 else: print('That choice is not valid.') return choice def place_marker(board, marker, position): board[position] = marker def win_check(board, mark): winning_combs = ([1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]) for comb in winning_combs: if board[comb[0]] == mark and board[comb[1]] == mark and board[comb[2]] == mark: return True else: continue def choose_first(): first = random.randint(1, 2) print(('\n') + (f'Player {first} goes first.\n')) return first def space_check(board, position): return board[position] == ' ' def full_board_check(board): return ' ' in board def player_choice(board): choice = 0 while choice == 0: try: pos = int(input('Please choose your next position: ')) if pos >= 1 and pos <= 9: if space_check(board, pos): choice += pos return choice else: print('Oops, that space is already taken.\n') continue print('That choice is not valid.\n') continue except ValueError: print('That choice is not valid.\n') continue def replay(): again = (input('Would you like to go again? Enter "Y" or "N"... ')).lower() return again == 'y'
true
8c988bf453d8f1c5bb69272e69e254df77c1b874
shreeji0312/learning-python
/python-Bootcamp/assignment1/assignment1notes/basicEx2.py
2,924
4.5625
5
# WPCC # basicEx2.py # Let's take a look at some different types of data that Python # knows about: print(10) print(3.14) print("Python is awesome!") print(True) # There are 4 fundamental types of data in Python: # integers, floating point numbers, strings, and booleans # You can create more types of data, but we'll examine those # later on. # You can declare a "variable" like this in Python: x = 54 # This variable is of the type "int" # We can see this by running the "type" function: print(type(x)) # this prints: <class 'int'> # Python will interpret this variable as an integer number # We can also make variables of type `float` y = 5.43 print(type(y)) # <class 'float'> # This type of data will store fractional numbers # The next data type is called a string. This data type will hold # a sequence of characters, and by doing so can store pretty much all # kinds of different data like names, colors, addresses etc. A string can # be defined with single quotes ('') or double quotes (""). # Be careful as strings can also store numbers, and numbers stored # in string ARE NOT # the same as their equivalent integer or float forms: a_number = '13' # <class 'str'> another_number = 13 # NOTE PYTHON DOESN'T SEE THESE VARIABLES AS THE SAME THING. # One will hold the sequence of characters: '1', and '3' # The other is the integer representation of the number 13 # Lastly, we have booleans. This type of data can only take on two different # values: true, or false. When making booleans in Python, you must capitalize # the first letter: True/False a_bool = True another_bool = False print(type(a_bool)) # <class 'bool'> # When declaring a variable, you must follow some rules with its name: # the name may contain lowercase/uppercase letters and as well as numbers, # but the first character must NOT be a number. """ 50cent = "the best" """ # THIS IS NOT A VALID VARIABLE. (put a "#" on the previous line to run this file) # but this is: w20_e3j = True # Be careful when referring to an existing variable, VARIABLES ARE CASE SENSITIVE # `variable_with_good_name` IS NOT THE SAME AS `Variable_with_good_name` print(x) x = 2.71 # We can reassign the same variable to a different type, # and Python won't care. In other programming languages, # this is NOT allowed. But Python doesn't care, it's different! # Python is smart, and will automatically convert between different # types if needed. For example, let's try to divide a floating # point number by an integer some_number = 10.5 some_other_number = 2 print(some_number / some_other_number) # The answer is 5.25 (type is `float`). In other languages, the different types # would not play well together, but as I mentioned before, Python is smart ######################### # EXERCISE ######################### # Write a python program that makes a variable of every type mentioned in this file. # Then print out their values
true
46004672cd99417c2bc0027e364ecb4441f1c8f9
shreeji0312/learning-python
/python-Bootcamp/assignment1/assignment1notes/basicEx6.py
1,907
4.84375
5
# WPCC # basicEx6.py # So far we've made our own variables that store # data that we have defined. Let's look at how we can # ask the user to enter in data that we can manipulate # in our program # We will use the `input` function to ask the user to enter # some data user_input = input("Please enter a number: ") # We must give the input function a string. This string will be displayed # to the user and wait for the to enter data. Once the user has entered # the data, the `user_input` variable will take on that value print(user_input) # This will print exactly what the user entered. If we print its type: print(type(user_input)) # We see that it's type is <class 'str'> i.e. a string # That might be a problem if we want to ask the user for a number: user_input = input("Please enter your age: ") """ print(user_input + 1) """ # What happens if we try to add 1 to the user's input? # We will get an error because Python doesn't know how to add the # string data type with the integer data type. But we know that `user_input` # is in fact an integer number. So how can we tell Python that `user_input` # is an integer? # We must do something called "type casting." When we cast a variable to a # different type, we're telling Python to interpret said variable as a # different type. # For example, we can cast `user_input` (which is a string) to an integer, # that way we can do arithmetic operations on it: x = int(user_input) # Now `x` will hold the integer interpretation of `user_input` and we may now # add 1 to it: print(x + 1) # We can cast variables to more types: a = str(user_input) b = float(user_input) c = int(user_input) b = bool(user_input) ######################### # EXERCISE ######################### # Write a program that asks the user to enter their birth month, # birth day, and birth year into separate variables. # Then output the sum of all three values.
true
6c4c8561cb46045307cf14a1481f97b3e63c1af8
shreeji0312/learning-python
/python-Bootcamp/assignment5/assignment5notes/2dlistEx1.py
2,000
4.71875
5
# WPCC # 2dlistEx1.py # We're going to look at what a 2D list is. # A 2D list is a list that contains other lists. # For example: marks = [ [90, 85, 88], [68, 73, 79] ] # The list `marks` contains 2 other lists, each containing # integers. We would say that this list is of size 2x3: # two lists, each containing 3 elements print(len(marks)) # This will print how many lists are in `marks` print(len(marks[0])) # This will print how many elements are in the first list inside `marks` # So why would we want to create something like this? # In some problems, we need to model something like a grid # or board that requires 2 coordinates or 2 indices. For example, # in a game of chess a piece's location is represented with 2 values: # a row position and a column position. We can model a chess board using # a 2D list board = [ [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # The `board` list contains 8 other lists, each containing 8 numbers. (8x8) # This above list has a 1 in the first list at the sixth index. # The way we would access that element is by first taking the index of the # list, then the index of the element inside of that list. # So to get the 7th element in the 1st list: print( board[0][6] ) # This will print `1` # Notice that each list the same length. In Python, it's not necessary to keep # all lists the same length, but it's definitely easier (as we've seen before, Python # can work with different kinds of data). In other programming languages, # making a 2D list with different list sizes would not be possible. ######################### # EXERCISE ######################### # Write a Python program that creates a 3x3 2D list of ints. # Then print out the middle element i.e. The element in the 2nd list, at the 2nd spot
true
291d09272a542e9b24fab373d154466f9d1b0c30
shreeji0312/learning-python
/python-Bootcamp/assignment4/assignment4notes/functionEx2.py
1,611
4.84375
5
# WPCC # functionEx2.py # When we call some Python standard functions, it gives us back # a value that we can assign to a variable and use later in our programs. # For example: import random randomNumber = random.randint(0, 10) # This function will return the value it generates so we can assign its # value to `randomNumber` # So how can we do that in our own functions: # Let's take a look at the function from the last note: ''' def myAddFunction(a, b): print("The sum is", a + b) ''' # This function will add the numbers, but we can't use it later in our # program ''' sum = myAddFunction(10, 5) ''' # This will not give us the expected 15. `myAddFunction` will only print the sum, # not return it # So we can modify this function to return the value instead. def myAddFunction(a, b): return a+b theSum = myAddFunction(10, 20) print(theSum) # Our function now "returns" the value instead of printing it. # This means that during runtime, the function call will take on the value # that is returned: # This is what it would look like behind the scenes: ''' theSum = myAddFunction(10, 20) theSum = .... compute theSum = 20 ''' # Note: when a function reaches a `return` statement, it will terminate the whole # function. For example: def exFunc(): return True print("PRINT ME PLS!!") exFunc() # The print will never happen because the function will have terminated # at the return statement ######################### # EXERCISE ######################### # Write a function called `letterGrade()` that will take in # a grade (integer) and return the appropriate letter grade
true
20656a0b0704de6339feab22f2a2a4d539cda92f
fantasylsc/LeetCode
/Algorithm/Python/75/0056_Merge_Intervals.py
977
4.15625
4
''' Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. ''' class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if len(intervals) <= 1: return intervals res = [] intervals.sort() res.append(intervals[0]) for item in intervals[1:]: if res[-1][1] >= item[0]: res[-1][1] = max(res[-1][1], item[1]) else: res.append(item) return res
true
a312e0acb76d0747602ccf4c39d799a3c814c30c
fantasylsc/LeetCode
/Algorithm/Python/1025/1007_Minimum_Domino_Rotations_For_Equal_Row.py
2,473
4.1875
4
''' In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same. If it cannot be done, return -1. Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] Output: 2 Explanation: The first figure represents the dominoes as given by A and B: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. Example 2: Input: A = [3,5,1,2,3], B = [3,6,3,3,4] Output: -1 Explanation: In this case, it is not possible to rotate the dominoes to make one row of values equal. Note: 1 <= A[i], B[i] <= 6 2 <= A.length == B.length <= 20000 ''' # greedy approach # notice that if the job can be done, all A or B should be A[0] or B[0] class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: def check(x): rotations_a = rotations_b = 0 for i in range(n): if A[i] != x and B[i] != x: return -1 elif A[i] != x: rotations_a += 1 elif B[i] != x: rotations_b += 1 return min(rotations_a, rotations_b) n = len(A) rotations = check(A[0]) if rotations != -1: return rotations else: return check(B[0]) # backtracking # TLE # class Solution: # def minDominoRotations(self, A: List[int], B: List[int]) -> int: # self.res = float('inf') # rotation = self.backtrack(A[:], B[:], 0, 0) # if self.res != float('inf'): # return self.res # else: # return -1 # def backtrack(self, A, B, start, rotation): # if len(set(A[:])) == 1 or len(set(B[:])) == 1: # self.res = min(self.res, rotation) # return # for i in range(start, len(A)): # A[i], B[i] = B[i], A[i] # rotation += 1 # self.backtrack(A[:], B[:], start + 1, rotation) # A[i], B[i] = B[i], A[i] # rotation -= 1
true
a18260a2c70db8afa8c17a910f0ea09a4d1802b1
fantasylsc/LeetCode
/Algorithm/Python/100/0079_Word_Search.py
2,907
4.15625
4
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. Constraints: board and word consists only of lowercase and uppercase English letters. 1 <= board.length <= 200 1 <= board[i].length <= 200 1 <= word.length <= 10^3 ''' ''' 1. loop to choose start point 2. backtrack recursion end condition 3. check current status, boundary, board[row][col] == suffix[0] 4. mark visited point 5. loop through four directions for backtracking 6. recover the change (backtrack) a little more complex than regular backtrack problems ''' class Solution: def exist(self, board: List[List[str]], word: str) -> bool: """ :type board: List[List[str]] :type word: str :rtype: bool """ self.ROWS = len(board) self.COLS = len(board[0]) self.board = board # start recursion from every position for row in range(self.ROWS): for col in range(self.COLS): if self.backtrack(row, col, word): return True # no match found after all exploration return False def backtrack(self, row, col, suffix): # bottom case: we find match for each letter in the word if len(suffix) == 0: return True # Check the current status, before jumping into backtracking # row or col out of range or self.board[row][col] != suffix[0] if row < 0 or row == self.ROWS or col < 0 or col == self.COLS \ or self.board[row][col] != suffix[0]: return False # self.board[row][col] == suffix[0] ret = False # mark the choice before exploring further. self.board[row][col] = '#' # explore the 4 neighbor directions for rowOffset, colOffset in [(0, 1), (1, 0), (0, -1), (-1, 0)]: ret = self.backtrack(row + rowOffset, col + colOffset, suffix[1:]) # break instead of return directly to do some cleanup afterwards if ret: break ''' # sudden-death return, no cleanup. if self.backtrack(row + rowOffset, col + colOffset, suffix[1:]): return True ''' # revert the change, a clean slate and no side-effect self.board[row][col] = suffix[0] # Tried all directions, and did not find any match return ret
true
8f3f5394b435a3b706388f72f98d14ac42e5ed10
fantasylsc/LeetCode
/Algorithm/Python/75/0065_Valid_Number.py
2,383
4.125
4
''' Validate if a given string can be interpreted as a decimal number. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e53" => false Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: Numbers 0-9 Exponent - "e" Positive/negative sign - "+"/"-" Decimal point - "." Of course, the context of these characters also matters in the input. ''' ''' Consider the following cases: - 空格: 空格可以出现在开头和结尾,不能出现在中间。 - 符号:符号前面如果有字符的话必须是空格或者是自然底数,标记sign为true。 - 数字:标记num和numAfterE为true,numAfterE表示自然底数后面是否有数字。 - 小数点:如果之前出现过小数点或者自然底数,返回false,否则标记dot为true。 - 自然底数:如果之前出现过自然底数或者之前从未出现过数字,返回false,否则标记exp为true,numAfterE为false。 - 其他字符:返回false。 ''' class Solution: def isNumber(self, s: str) -> bool: num = False numAfterE = True dot = False exp = False sign = False n = len(s) for i in range(n): if s[i] == ' ': if i < n- 1 and s[i + 1] != ' ' and (num or dot or exp or sign): return False elif s[i] == '+' or s[i] == '-': if i > 0 and s[i - 1] != 'e' and s[i - 1] != ' ': return False sign = True elif s[i] >= '0' and s[i] <= '9': num = True numAfterE = True elif s[i] == '.': if dot or exp: return False dot = True elif s[i] == 'e': if exp or not num: return False exp = True numAfterE = False else: return False return num and numAfterE
false
955c1c68bdd8c6c869585f98009b603eb3938d28
amirhosseinghdv/python-class
/Ex4_Amirhossein Ghadiri.py
1,617
4.1875
4
"""#Ex12 num1=int(input("addad avval?")) num2=int(input("addad dovvom?")) if num1 >= num2: print(num2) print(num1) else: print(num1) print(num2) """ """#13: num=int(input("please enter a number lower than 20: ")) if num >= 20: print("Too high") else: print("Thank you") """ """#14: num=int(input("Enter a number between 10 and 20(inclusive: ")) if 10<= num <=20: print("Thank you") else: print("Incorrect answer") """ """#15: color=input("Enter your favorite color: ") if color == "red" or color == "Red" or color == "RED": print("I like red too.") else: print("I don't like " +color+ ", i prefer red.") """ """#16: q1=input("Is it raining?") Q1=q1.lower() if Q1 == "yes": q2=input("Is it windy?") Q2=q2.lower() if Q2 == "yes": print("It is too windy for an umbrella.") else: print("Take an umbrella.") else: print("Enjoy your day.") """ """#17: age=float(input("Your age?")) if age >= 18: print("You can vote.") elif age >= 17: print("You can learn to drive.") elif age >= 16: print("You can buy a lottery ticket.") else: print("You can go Trick-or-Treating.") """ """#18: num=float(input("Enter a number: ")) if num < 10: print("Too low.") elif num > 20: print("Too high.") else: print("Correct.") """ """#19: num=float(input("Enter 1, 2 or 3: ")) if num == 1: print("Thank you.") elif num == 2: print("Well done.") elif num == 3: print("Correct.") else: print("Error message.") """
true
07d431c2473e33a00b597bc6412af322f116abab
AnumaThakuri/pythonassignment
/assignment4/question 1.py
310
4.28125
4
#average marks of five inputted marks: marks1=int(input("enter the marks 1:")) marks2=int(input("enter the marks 2:")) marks3=int(input("enter the marks 3:")) marks4=int(input("enter the marks 4:")) marks5=int(input("enter the marks 5:")) sum=marks1+marks2+marks3+marks4+marks5 avg=sum/5 print("average=",avg)
true
86ed441f6d4ab832a0087ed1b6b5adac3085ebcf
AnumaThakuri/pythonassignment
/Python test1/question 1.py
264
4.34375
4
#convert tempersture clesius to farenhuet and vice versa farenheit=float(input("Enter the temperature : ")) celsius=(farenheit-32)*5/9 print(farenheit ," Farenheit is",celsius,"Celsius") farenheit=(celsius*9/5)+32 print(celsius," Celsius is",farenheit,"Farenheit")
false
e343ff42820c7d794248635ec646eb8d4b184181
lxiong515/Module13
/GuessGame/topic1.py
2,385
4.15625
4
""" Program: number_guess.py Author: Luke Xiong Date: 07/18/2020 This program will have a set of buttons for users to select a number guess """ import tkinter as tk from random import randrange from tkinter import messagebox window = tk.Tk() window.title("Guessing Game") label_intro = tk.Label(window, text = "Guess a number from 0 to 9") label_instruct = tk.Label(window, text = "Click a button below!") label_guess = tk.Label(window, text="Your Guesses: ") # create the buttons buttons = [] for index in range(0, 10): button = tk.Button(window, text=index, command=lambda index=index : process(index), state=tk.DISABLED) buttons.append(button) btnStartGameList = [] for index in range(0, 1): btnStartGame = tk.Button(window, text="Start Game", command=lambda : startgame(index)) btnStartGameList.append(btnStartGame) # grid label_intro.grid(row=0, column=0, columnspan=5) label_instruct.grid(row=2, column=0, columnspan=3) label_guess.grid(row=4, column=0, columnspan=5) for row in range(0, 2): for col in range(0, 5): i = row * 5 + col # convert 2d index to 1d. 5= total number of columns buttons[i].grid(row=row+10, column=col) btnStartGameList[0].grid(row=13, column=0, columnspan=5) guess = 0 secretNumber = randrange(10) print(secretNumber) guess_row = 4 # reset all variables def init(): global buttons, guess, totalNumberOfGuesses, secretNumber, guess_list, guess_row secretNumber = randrange(10) print(secretNumber) guess_row = 4 guess_list = [] def process(i): global totalNumberOfGuesses, buttons, guess_row, guess_list guess = i guess_list=[] if guess == secretNumber: messagebox.showinfo(title="Congratulations!", message="That's the correct number!") for b in buttons: b["state"] = tk.DISABLED else: #save the guess to a list guess_list.append(i) #print the list to verify it is passing the number #print(guess_list) #need to display the guess_list!!! but how? buttons[i]["state"] = tk.DISABLED status = "none" def startgame(i): global status for b in buttons: b["state"] = tk.NORMAL if status == "none": status = "started" btnStartGameList[i]["text"] = "Retart Game" else: status = "restarted" init() print("Game started") window.mainloop()
true
a970f1be719d68082548cf222aeff5beaea5da64
cyan33/leetcode
/677-map-sum-pairs/map-sum-pairs.py
1,235
4.15625
4
# -*- coding:utf-8 -*- # # Implement a MapSum class with insert, and sum methods. # # # # For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one. # # # # For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix. # # # Example 1: # # Input: insert("apple", 3), Output: Null # Input: sum("ap"), Output: 3 # Input: insert("app", 2), Output: Null # Input: sum("ap"), Output: 5 # class TrieNode(): def __init__(self, count = 0): self.count = count self.children = {} class MapSum(object): def __init__(self): """ Initialize your data structure here. """ self.map = {} def insert(self, key, val): self.map[key] = val def sum(self, prefix): return sum([val for k, val in self.map.items() if k.startswith(prefix)]) # Your MapSum object will be instantiated and called as such: # obj = MapSum() # obj.insert(key,val) # param_2 = obj.sum(prefix)
true
f7eb0bfd643b4d386350d8a220d768d734e2041b
vaibhavranjith/Heraizen_Training
/Assignment1/Q8.py
354
4.25
4
#registration problem (register only people above the age 18) name=input("Enter the name: \n") mbno=int(input("Enter the mobile number:\n")) age=int(input("Enter the age:\n")) if age<=18: print("Sorry! You need to be at least 18 years old to get membership.") else : print(f"Congratulations {name} for your successful registration.")
true
e563732e0c4613d96718dbe04f094fb26a4823da
Dionisiohenriq/Python-Learning
/alura_python/Filmes/playlist.py
1,182
4.1875
4
# herança é usada tanto para o reuso, quanto para absorver o polimorfismo(ducktyping), # herança pelo polimorfismo - atributos, métodos # herança pelo reuso de código e remoção de duplicação # herança = extensão # composição = conceito de 'tem um' ao invés de 'é um' # Classes abstract based classes - abc - obrigam a implementar métodos da superclasse nas classes # filhas # herança múltipla, utiliza os métodos na ordem classe > superclasse > superclasse em mesmo nível hierárquico, super-superclasse # classes mixin são utilizadas para criar comportamentos(métodos) que são utilizados em classes complexas class Playlist(): def __init__(self, nome, programas): self.nome = nome self._programas = programas def __str__(self): return [print(programa) for programa in self._programas] def __getitem__(self, item): return self._programas[item] def __len__(self): return len(self._programas) @property def tamanho(self): return len(self._programas) def listagem(self): return [self._programas] # def __iter__(self): # return self._programas.__iter__()
false
bb3b04baf74550ea0cc12ff62e717d90fc2ceca7
hack-e-d/Rainfall_precipitation
/Script/prediction_analysis.py
1,567
4.5
4
# importing libraries import pandas as pd import numpy as np import sklearn as sk from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # read the cleaned data data = pd.read_csv("austin_final.csv") # the features or the 'x' values of the data # these columns are used to train the model # the last column, i.e, precipitation column # will serve as the label X = data.drop(['PrecipitationSumInches'], axis = 1) # the output or the label. Y = data['PrecipitationSumInches'] # reshaping it into a 2-D vector Y = Y.values.reshape(-1, 1) # consider a random day in the dataset # we shall plot a graph and observe this # day day_index = 798 days = [i for i in range(Y.size)] # initialize a linear regression classifier clf = LinearRegression() # train the classifier with our # input data. clf.fit(X, Y) # plot a graph of the precipitation levels # versus the total number of days. # one day, which is in red, is # tracked here. It has a precipitation # of approx. 2 inches. print("the precipitation trend graph: ") plt.scatter(days, Y, color = 'g') plt.scatter(days[day_index], Y[day_index], color ='r') plt.title("Precipitation level") plt.xlabel("Days") plt.ylabel("Precipitation in inches") plt.show() inpt=[] inpt=input("enter the input").split() for i in range(len(inpt)): inpt[i]=float(inpt[i]) print(inpt) inpt=np.array(inpt) inpt = inpt.reshape(1, -1) print('The precipitation in inches for the input is:', clf.predict(inpt))
true
e3187b055b6db5a497b94602820ac86b8671e637
rajagoah/Tableua_rep
/EmployeeAttritionDataExploration.py
2,105
4.125
4
import pandas as pd df = pd.read_csv("/Users/aakarsh.rajagopalan/Personal documents/Datasets for tableau/Tableau project dataset/WA_Fn-UseC_-HR-Employee-Attrition.csv") #printing the names of the columns print("names of the columns are:") print(df[:0]) #checking if there are nulls in the data #note that in pandas documentation the NULL or NaN data is called as Missing data """While checking for NULL values in a dataframe, we use the isnull() function on the data frame. If we want to check if there are 'any' missing values, then we use the chained function isnull().any() If we want to retrieve the count of missing values across the entire data frame, we need to use the chained function, isnull().sum().sum() Note: in isnull().sum().sum() --> the first chained sum() is going to give the number of missing values in each row in dataframe. the second sum() will add the values returned by the previous sum() function""" print('\n***************checking for null values in the data frame***************\n') if df.isnull().sum().sum() == 0: print('NO NULLS') else: print(df.isnull().sum().sum()) #Exploring the data #Age of employee who are considered Attrition=Yes df_attrition_yes = df[df['Attrition'] =='Yes'] print(df_attrition_yes[['Age']].mean()) #analyzing relationship between age and years at company print(df_attrition_yes[['Age','YearsAtCompany']].head(10)) #checking the number of records in the data frame for Attrition = yes print('The number of rows are: ',len(df_attrition_yes.index)) """the same can be done using the following code""" print('The number of rows are: ',df_attrition_yes.shape) print('The number of rows are: ',df_attrition_yes['Age'].count()) #exploring the environmentSatisfaction and JobSatisfaction print(df_attrition_yes[['EnvironmentSatisfaction','JobSatisfaction']]) #exploring performance rate print(df_attrition_yes[['PerformanceRating']].min(), df_attrition_yes[['PerformanceRating']].max()) #exploring years since last promotion print(df_attrition_yes[['YearsSinceLastPromotion']].min(),df_attrition_yes[['YearsSinceLastPromotion']].max())
true
2c25567847813a6b87ab0952612e89fad3123b66
EGleason217/python_stack
/_python/python_fundamentals/course_work.py
1,988
4.25
4
print("Hello World!") x = "Hello Python" print(x) y = 42 print(y) print("this is a sample string") name = "Zen" print("My name is", name) name = "Zen" print("My name is " + name) first_name = "Zen" last_name = "Coder" age = 27 print(f"My name is {first_name} {last_name} and I am {age} years old.") first_name = "Zen" last_name = "Coder" age = 27 print("My name is {} {} and I am {} years old.".format(first_name, last_name, age)) # output: My name is Zen Coder and I am 27 years old. print("My name is {} {} and I am {} years old.".format(age, first_name, last_name)) # output: My name is 27 Zen and I am Coder years old. x = "hello world" print(x.title()) #tuples dog = ('Bruce', 'cocker spaniel', 19, False) print(dog[0]) # output: Bruce dog[1] = 'dachshund' # ERROR: cannot be modified ('tuple' object does not support item assignment) #lists empty_list = [] ninjas = ['Rozen', 'KB', 'Oliver'] print(ninjas[2]) # output: Oliver ninjas[0] = 'Francis' ninjas.append('Michael') print(ninjas) # output: ['Francis', 'KB', 'Oliver', 'Michael'] ninjas.pop() print(ninjas) # output: ['Francis', 'KB', 'Oliver'] ninjas.popcopy(1) print(ninjas) # output: ['Francis', 'Olive #dictionaries empty_dict = {} new_person = {'name': 'John', 'age': 38, 'weight': 160.2, 'has_glasses': False} new_person['name'] = 'Jack' # updates if the key exists new_person['hobbies'] = ['climbing', 'coding'] # adds a key-value pair if the key doesn't exist print(new_person) # output: {'name': 'Jack', 'age': 38, 'weight': 160.2, 'has_glasses': False, 'hobbies': ['climbing', 'coding']} w = new_person.pop('weight') # removes the specified key and returns the value print(w) # output: 160.2 print(new_person) # output: {'name': 'Jack', 'age': 38, 'has_glasses': False, 'hobbies': ['climbing', 'coding']} print("Hello" + 42) # output: TypeError print("Hello" + str(42)) # output: Hello 42 total = 35 user_val = "26" total = total + user_val # output: TypeError total = total + int(user_val) # total will be 61
true
2a585f085a104e399c0a623e278a25642d8c0166
anthonytrevino/Monday
/objectsandclasses.py
1,870
4.15625
4
class Person(object): def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.friends =[] self.greeting_count = 0 def greet(self, other_person): self.greeting_count += 1 print("Hello {0}, I am {1}!".format (other_person.name, self.name)) def print_contact_info(self): print("My email: " + self.email + ", and my phone number: " + self.phone) def add_friend(self, other_person): self.friends.append(other_person) def num_friends(self): len(self.friends) #jordan.friends.append(sonny) # sonny.friends.append(jordan) sonny = Person("Sonny", "sonny@hotmail.com", "483-485-4948") jordan = Person("Jordan", "jordan@aol.com", "495-586-3456") sonny.greet(jordan) jordan.greet(sonny) print(sonny.email, sonny.phone) print(jordan.email, jordan.phone) sonny.print_contact_info() jordan.print_contact_info() jordan.add_friend(sonny) sonny.add_friend(jordan) # print(len(jordan.friends)) # print(len(sonny.friends)) # class Vehicle: # def __init__(self,make,model,year): # self.make = make # self.model = model # self.year = year # # def print_info(self): # print(self.make,self.model,self.year) # # car = Vehicle("Honda", "Accord", "2019") # car.print_info() # class Dog: # # # Class Attribute # species = 'mammal' # # # Initializer / Instance Attributes # def __init__(self, name, age): # self.name = name # self.age = age # # # # Instantiate the Dog object # philo = Dog("Philo", 5) # mikey = Dog("Mikey", 6) # # # Access the instance attributes # print("{} is {} and {} is {}.".format(philo.name, philo.age, mikey.name, mikey.age)) # # # Is Philo a mammal? # if philo.species == "mammal": # print("{0} is a {1}!".format(philo.name, philo.species)) #
false
cdf54f108bf8e4d7b26613b3d6ac3dcac3083157
ColorfulCodes/ATM
/ATM .py
1,073
4.15625
4
# We will be creating a bank account class BankAccount(object): balance = 0 def __init__(self, name): self.name = name def __repr__(self): return "This account belongs to %s and has a balance of %.2f dollars." % (self.name, self.balance) def show_balance(self): print "Your balance is: $%.2f." % (self.balance) def deposit(self, amount): if amount <= 0: print "Sorry, but you're broke." return else: print "You have a total of %s." % (amount) self.balance += amount self.show_balance() def withdraw(self,amount): if amount > self.balance: print "Invalid. Try again." return else: print " The user is drawing $%.2f." % (amount) self.balance -= amount self.show_balance() my_account = BankAccount("Jazmeen") print my_account my_account.show_balance my_account.deposit(2000) my_account.withdraw(1000) print my_account
true
dde5c4982b3a03e1c44d086a5a86924d91e83b1b
kylejablonski/Python-Learning
/conditionals.py
786
4.46875
4
print("Hello, World! This is a conditionals program test.") # prompts for a value and checks if its more or less than 100 maxValue = int(input("Please enter a value: ")) if maxValue > 100: print("The max value of {0} is greater than 100!".format(maxValue)) elif maxValue < 100: print("The max value of {0} is less than 100!".format(maxValue)) else: print("Looks like the value you entered is not a max value!") # grabs user input and using an expression to determine what to print firstName = input("Now enter your first name: ") firstName = firstName if firstName == 'Bill' else 'That was not a name' print("Wow coolname, {0}".format(firstName)) if not len(firstName) > 10: print("that is a medium size name") else: print("Whoa shorty, that name is not long.")
true
ae8ee65d9527b2edfd5b393bb69d70016ddabede
Gafan154/MichaelGafan
/FactGood.py
483
4.1875
4
print("Factorial") def FactInput(): global num num=0 num = input("enter interger number: ") if not num.isdigit(): FactInput() def Fact(num): f=1 while num > 1: f=f*num num-=1 return(f) more='y' while more == 'y': FactInput() num=int(num) f=Fact(num) print('Factorial of: ',num,' is ',f) more = input("enter y to continue: ")
false
33de7e691ca65a230c76d269d1ae6f5a9e6647eb
Lonabean98/pands-problem-sheet
/es.py
812
4.40625
4
#This program reads in a text #file and outputs the number of e's it contains. #It can also take the filename from an argument on the command line. #Author: Lonan Keane #The sys module provides functions and variables used to # manipulate different parts of the Python runtime environment. import sys # sys.argv returns a list of command line arguments # passed to a Python script. filename= sys.argv[1] #opening the argument as f with open(filename) as f: #reads all the text from a file into a string. x=f.read() #This is the start of the e count e_count= 0 #looping through every character in the file for letter in x: if letter =='e' or letter== 'E': # if the letter is e or E, add one to the e count e_count += 1 #print the final e count print(e_count)
true
028ef354ab87048c660f7c74c1d117f43b23b757
elimbaum/euler
/002/002.py
411
4.21875
4
#! /usr/bin/env python3.3 """ Project Euler problem 002 Even Fibonacci Numbers by Eli Baum 14 April 2013 """ print("Project Euler problem 002") print("Even Fibonacci Numbers") n = int(input("Upper Limit: ")) # Brute-Force calculate all of the fibonacci numbers a, b = 0, 1 sum = 0 while True: a, b = a + b, a if a > n: break # We have reached the upper limit; stop if a % 2: sum += a print(sum)
true
1f341dec6a19daad68ae3cd636a1d395d1c539dd
elimbaum/euler
/003/003.py
687
4.25
4
#! /usr/bin/env python3.3 """ Project Euler problem 003 Largest Prime Factor by Eli Baum 14 April 2013 """ from math import * print("Project Euler problem 003") print("Largest Prime Factor") n = float(input("n = ")) """ We only need to find ONE prime factor. Then we can divide, and factor that smaller number. """ largestPrime = 0 factored = False while not factored: upperLimit = floor(sqrt(n)) # We only need to check up to sqrt(n) for i in range(2, upperLimit): factored = True # If no more factors are found, while loop stops. if not (n % i): n /= i factored = False if i > largestPrime: # Add the highscore! largestPrime = i break print(int(n))
true
2aa4a954d83a4e6773947d6fef64ff41cc2f1986
keivanipchihagh/AUTHUB
/03/Data Structures and Algorithms/notes/codes/Merge Sort.py
1,045
4.28125
4
import random def merge_sort(array): # Return condition if len(array) <= 1: return # Find middle middle = len(array) // 2 # Find left hand left_side = array[:middle] # Find right hand right_side = array[middle:] # Sort first half merge_sort(left_side) # Sort second half merge_sort(right_side) i = j = k = 0 # Rearrange array while i < len(left_side) and j < len(right_side): if left_side[i] < right_side[j]: array[k] = left_side[i] i += 1 else: array[k] = right_side[j] j += 1 k += 1 # Add remaining elements while i < len(left_side): array[k] = left_side[i] i += 1 k += 1 while j < len(right_side): array[k] = right_side[j] j += 1 k += 1 # Driver method if __name__ == "__main__": array = random.sample(range(30), 10) print('Initial Array:', array) merge_sort(array = array) print('Sorted Array:', array)
false
e05d23b8f68f0fcf422ce4a91f5aed4fdfa7630c
samiatunivr/NLPMLprojects
/linearRegression.py
1,821
4.53125
5
__author__ = 'samipc' from numpy import loadtxt def linearRegression(x_samples, y_labels): length = len(x_samples) sum_x = sum(x_samples) sum_y = sum(y_labels) sum_x_squared = sum(map(lambda a: a * a, x_samples)) sum_of_products = sum([x_samples[i] * y_labels[i] for i in range(length)]) a = (sum_of_products - (sum_x * sum_y) / length) / (sum_x_squared - ((sum_x ** 2) / length)) b = (sum_y - a * sum_x) / length return a, b # lets work on one typical example example used of linear regression(our data file has two columns: column 1 represent the # population of a city and column two represents a profit of a shop in the city) so we our goal is to find the relationship between these # vairabiles in order to find out which city we will be sitting our business. So our objective function is is given as h(x) = lamda_t*x; # the lamada is the parameter of our model, and we seek to minimize the cost fuction which #can be done using different algorithms but commonly we use gredient descent algorithm. # here is just a simple linear regression applying the function in wikipedia (works with two variables but if we want to work with multiple variabiles # we need to do these steps: # substact the mean of each feature from the entire data sets X= is dataset, m_i = mean(X(:,i)) i a samples, # divid the feature values by the std deviation to understand how these features are deviated. X(:,i)-m_i/s_i, we will have a (normalized features) #Load the dataset toy_data_business = loadtxt('data.txt', delimiter=',') x = toy_data_business[:, 0] y = toy_data_business[:, 1] print linearRegression(x, y) # https://en.wikipedia.org/wiki/Linear_regression output = (1.1930336441895988, -3.8957808783119017) # W are loosing (our profite is decreasing if open a shop in this region)
true
91f974b6597229fe3904f31e9ebc98b52e966a5d
timfornell/PythonTricksDigitalToolkit
/Lesson4.py
514
4.25
4
""" Lesson 4: Implicit returns """ # Python will automatically return None, all following functions will return the same value def foo1(value): if value: return value else: return None def foo2(value): """ Bare return statement implies 'return None'""" if value: return value else: return def foo3(value): """ Missing return statement implies 'return None'""" if value: return value print(foo1(False)) print(foo2(False)) print(foo3(False))
true
3f3ce30522dc34b97d1db423092598cf0d56ed80
ArnyWorld/Intro_Python
/8.-Condicionales.py
1,735
4.125
4
#Las condicionales nos permiten realizar una acción cuando se cumple cierta condición edad = 15 if edad >= 18: print('Eres mayor de edad') else: print('Eres menor de edad') experiencia = 3 if experiencia == 3: print('Tienes experiencia de 3 años') else: print('No tienes la experiencia solicitada') #negación nombre = "Ronaldo" if nombre != "Arnaldo": print('No eres Arnaldo') else: print('Si eres Arnaldo') """ nombre = "Ronaldo" if not nombre == "Arnaldo": print('No eres Arnaldo') else: print('Si eres Arnaldo') """ usuario_autenticado= True if usuario_autenticado: print('Acceso al sistema') else: print('Debes iniciar sesión') #Existen diferentes operadores que son utilizadas para realizar condiciones """ < menor > mayor <= menor igual >= mayor igual != distinto == igual """ #Condicionales Anidados usuario_Admin = True if usuario_autenticado: if usuario_Admin: print('ACCESO TOTAL') else: print('Acceso al sistema') else: print('Debes iniciar sesión') #elif ocupacion = 'Estudiante' if ocupacion == 'Estudiante': print('Tienes 50% dedescuento') elif ocupacion == 'Jubilado': print('Tienes 75% dedescuento') else: print('Debes pagar el 100%') #condicionales con operadores lógicos """ El operador AND dara una respuesta verdadera siempre y cuando las condiciones sean verdaderas El operador OR dara una respuesta verdadera siempre y cuando exista al menos una condición verdadera """ usuario_autenticado = True usuario_Admin = True if usuario_autenticado and usuario_Admin: print('Administrador') elif usuario_autenticado: print('Acceso al sistema') else: print('Debes iniciar sesión')
false
5d54fac367fd107da96dbebc34f99ffa55188742
geeta-kriselva/python_excercise
/Prime_number.py
599
4.125
4
# Checking, if user input number is prime a number. if not printing all the facors. n= input("Enter the number: ") try: num = int(n) except: print("Enter only integer number") quit() if num > 1: factor = [] a = 0 for i in range(2,num+1): if (num % i) == 0: factor.insert(a,i) a = a + 1 #if len(factor) <= 1: #print(num, "is a prime number") else: print(num, "is not a prime number") for i in range (len(factor)): print("The factor is: ", factor[i]) else: print(num, "is a prime number")
true
38cebc4b8358782b77b27e9f46c0b76a17b24b17
JoseBalbuena181096/python_course
/lesson_10/adivina.py
1,699
4.125
4
from utilidades import logo from utilidades import limpiar_consola from random import randint from time import sleep VIDAS_FACIL = 10 VIDAS_DIFICIL = 5 def elegir_dificultad(): dificultad = input('¿Qué dificultad deseas?, F para fácil y D para difícil.\n').upper() if dificultad == 'F': return VIDAS_FACIL elif dificultad == 'D': return VIDAS_DIFICIL else: return -1 def verificar_numero(numero_usr,numero_mqn,turnos): if numero_usr > numero_mqn: print('‘Tu número es grande’') print('Reintente adivinar...') sleep(3) return turnos-1 elif numero_usr < numero_mqn: print('Tu número es pequeño') print('Reintente adivinar...') sleep(3) return turnos-1 elif numero_usr == numero_mqn: print(f'Felicidades ganaste tu número {numero_usr} el número secreto {numero_mqn}') sleep(3) return -1 def juego(): limpiar_consola() print('Bienvenido al juego de \n') print(logo) print('Piensa un número entre 0 y 100\n') numero_maquina = randint(0,100) turnos = elegir_dificultad() numero_usuario = -1 while numero_maquina != numero_usuario and turnos >= 0: limpiar_consola() #test #print(numero_maquina) print(f'Tu tienes {turnos} turnos para adivinar el número') numero_usuario = int(input('Ingresa un posible número .\n')) turnos = verificar_numero(numero_usuario,numero_maquina,turnos) if turnos == 0: limpiar_consola() print('Ya no tienes turnos disponibles perdiste.') sleep(3) return juego() limpiar_consola()
false
684a461578aa7a89a5d314b87c8ae225787e79ce
o8oo8o/Py_Design_Patterns
/factory.py
896
4.21875
4
#!/usr/bin/env python """ 抽象工厂模式 """ class PetShop: def __init__(self, animal_factory=None): self.pet_factory = animal_factory def show_pet(self): pet = self.pet_factory.get_pet() print("动物类型:", str(pet)) print("动物叫声:", pet.speak()) print("吃的东西:", self.pet_factory.get_food()) class Dog: def speak(self): return "wang" def __str__(self): return "Dog" class Cat: def speak(self): return "miao" def __str__(self): return "Cat" # Factory class class DogFactory: def get_pet(self): return Dog() def get_food(self): return "dog food" class CatFactory: def get_pet(self): return Cat() def get_food(self): return "cat food" if __name__ == "__main__": shop = PetShop(DogFactory()) shop.show_pet()
false
9c33904e4f7aa5755bdc68499645da20d9c86902
MatiasToniolopy/condicionales_python
/profundizacion_2.py
1,990
4.1875
4
# Tipos de variables [Python] # Ejercicios de profundización # Autor: Inove Coding School # Version: 2.0 # NOTA: # Estos ejercicios son de mayor dificultad que los de clase y práctica. # Están pensados para aquellos con conocimientos previo o que dispongan # de mucho más tiempo para abordar estos temas por su cuenta. # Requiere mayor tiempo de dedicación e investigación autodidacta. # IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA # Ejercicios de práctica numérica y cadenas ''' Enunciado: Realice un programa que consulte por consola: - El nombre completo de la persona - El DNI de la persona - La edad de la persona - La altura de la persona Finalmente el programa debe imprimir dos líneas de texto por separado - En una línea imprimir el nombre completo y el DNI, aclarando de que campo se trata cada uno Ej: Nombre Completo: Nombre Apellido , DNI:35205070, - En la segunda línea se debe imprimir el nombre completo, edad y altura de la persona Nuevamente debe aclarar el campo de cada uno, para el que lo lea entienda de que se está hablando. ''' print('Sistema de ingreso de datos') # Empezar aquí la resolución del ejercicio #ingresando datos, nombre completo print("¿como se llama?") nombre_completo = input() print(f"me alego de conocerlo, {nombre_completo}") #ingresando datos, DNI print("ingrese su numero de DNI") DNI = input() print("sus datos fueron aprobados") print(f"compruebe si los datos, {nombre_completo}, y {DNI}, son validos") #ingresando edad print("ahora ingrerse su edad en numeros") edad = input() print(f"la edad ingresada es, {edad}") #ingresando altura print("por favor, por ultimo ingrese su altura") altura = input() print(f"la altura ingrasada es, {altura}") #lineas de datos ingresados print(f"los datos ingresados son, {nombre_completo}, con {DNI}") print(f"bienvenido a inove, {nombre_completo}, su edad es {edad}, y su altura {altura}") print("gracias por confiar en nosotros")
false
bee70d6fa16e25998f08830db5669e8b260e93d7
DriesDD/python-workshop
/Examples/guess.py
1,237
4.21875
4
""" This uses the random module: https://www.w3schools.com/python/module_random.asp Exercises: 1. Can you make it a number between one and 100? Give more hints depending on whether the player is close or not? And change the number of guesses that the player can make? 2. Can you make the game into a function called startgame(difficulty) which starts a game and accepts the game difficulty as a parameter? 3. What do {0} and {1} do in the final lines of the program? How else could you write this? 4. How would you go about adding a computer opponent which also takes turns guessing? """ import random guesses_made = 0 name = input('Hello! What is your name?\n') number = random.randint(1, 20) print ('Well, ' + name + ', I am thinking of a number between 1 and 20 (inclusive).') while guesses_made < 6: guess = int(input('Take a guess: ')) guesses_made += 1 if guess < number: print ('Your guess is too low.') if guess > number: print ('Your guess is too high.') if guess == number: break if guess == number: print ('Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)) else: print ('Nope. The number I was thinking of was {0}'.format(number))
true
554f0ccf1ca0bd3bd7da513e690f74fa1f170f4e
Rockforge/python_training
/exercise17.py
321
4.15625
4
# exercise17.py # Data type: tuple denominations = ('pesos', 'centavos') # denominations = ('pesos',) # this should be the syntax for one element tuples print(denominations) print(type(denominations)) print(denominations[1]) print('--- Entering loop ---') for denomination in denominations: print(denomination)
true
6c6341cf4989c57c420cf661aa26836f35a2f4f4
Leownhart/My_Course_of_python
/Geek University/Seção 5/Exercicios/EX21.py
1,121
4.25
4
''' 21 - Escreva o menu de opções abaixo. Leia a opção do usuário e execute a operação escolhida. Escreva uma mesagem de erro se a opção for inválida. Escolha a opção: 1 - Soma de 2 números. 2 - Diferença entre 2 números (maior pelo menor) 3 - Produto entre 2 números. 4 - Divisão ente 2 números (o denominador não pode ser zero). ''' print('[1] Soma de 2 números. \n' '[2] Diferença entre 2 números (maior pelo menor) \n' '[3] Produto entre 2 números. \n' '[4] Divisão ente 2 números (o denominador não pode ser zero).') op = int(input('Opção: ')) number1 = int(input('Número 1: ')) number2 = int(input('Número 2: ')) if op == 1: print(f'Soma = {number1 + number2}') elif op == 2: if number1 > number2: print(f'Diferença entre {number1} é {number2} = {number1 - number2}') else: print(f'Diferença entre {number2} é {number1} = {number2 - number1}') elif op == 3: print(f'O produto é {number1 * number2}') elif op == 4: if number1 > 0: print(f'{number1 / number2}') else: print('O denominador e inválido')
false
ec9b8fac5dd0be6f60102c2eaebe615fbfb9a430
Leownhart/My_Course_of_python
/Geek University/Seção 4/tipo_float.py
390
4.125
4
""" Tipo Float -> Váriaveis com ponto flutuante """ # Errado valor = 1, 44 print(valor) # Certo so ponto de viata float valor = 1.44 print(valor) print(type(valor)) # É possivel realizar dupla atribuição valor1, valor2 = 1, 44 print(valor1) print(valor2) print(type(valor1)) print(type(valor2)) # Podemos converter um float para um int res = int(valor) print(res) print(type(res))
false
8ad662296e95222506e01a903b694aaddbde2b15
Leownhart/My_Course_of_python
/Geek University/Seção 6/entendendo_ranges.py
744
4.375
4
""" - Precisamos conhecer o loop for para utilizar o range. Ranges são utilizados para gerar sequências numéricas, não de forma aleatória, mas sim de maneira especifica. Formas gerais: # Forma 01 range(valor_de_parada) OBS: valor_de_parada não inclusive (inicio padrão 0, e passo de 1 em 1) # Forma 1 for num in range(11): print(num) # Forma 2 range(valor_de_inicio, valor_de_parada) OBS: valor_de_parada não inclusive (inicio especificado, e passo de 1 em 1) for num in range(1, 11) print(num) # Forma 3 range(valor_de_inicio, valor_de_parada, passo) OBS: Valor_de_parada não inclusive (inicio especificado pelo usuário, e passo especificado pelo mesmo) for num in range(1, 10, 2) print(num) """
false
8e5c4b8fbcf49eb02931a653bbbba9d49be94611
tazi337/smartninjacourse
/Class2_Python3/example_00630_secret_number_exercise_1.py
771
4.21875
4
# Modify the secret number game code below such # that it shows the number of attempts # after each failed attempt # Modify the secret number game code below such # that it shows the number of attempts # after each failed attempt secret = "1" counter = 5 while counter > 0: counter -= 1 guess = input("guess the number") if guess == secret: print("yes, the guess was right!") else: print(f"Sorry, thats not correct. Number of further guesses: {counter}") else: print("game over") secret = "10" counter = 0 while counter < 5: guess = input("Guess the secret number") counter += 1 if guess == secret: print("You won!") break else: print("Try again!") else: print("Game Over")
true
2f056da07759ce4b904eeb8fb3410261289aa87a
tazi337/smartninjacourse
/Class1_Python3/example_00300_operations_strings.py
962
4.40625
4
greeting = "Hello World!" name = "Smartninja!" # ADDING STRINGS (CONCAT) print(greeting) print(greeting + " - AI ") # MULTIPLYING STRINGS - das Beispiel hier erzeugt einen String mit 20 Sternchen print("*" * 20) # PRINTING THEM BY INSERTING print("Greeting: {}, Name: {}".format(greeting, name)) # new in Python 3: print(f"Greeting: {greeting}, Name: {name}") # durch "f" wird es ein formatierbarer String, ich kann Variablen hinzufügen in geschwungener Klammer # CHECKING FOR (UN)EQUALITY print(greeting == name) print(greeting == "Hello World!") # CHECKING FOR OCCURRENCE print(greeting in "Hello World! is the first greeting in a computer language") # checken, ob etwas bestimmtes in einem text vorkommt. # genauer definieren könnte man es noch mit regex (folgt später) # WATCH OUT FOR USING THE CORRECT TYPES print("3" + "3") print(int("3") + int("3")) print(str(3)) # print int("3") + "3" # TypeError # print int("a") # ValueError
false
dae58627d930502a1a950949637285e6a1275921
mjftw/design-patterns
/example-design-patterns/iterator/iterator_example.py
240
4.40625
4
'''Trivially simple iterator example - python makes this very easy!''' def main(): a = 'a' b = 'b' c = 'c' iterable = [a, b, c] for element in iterable: print(element) if __name__ == '__main__': main()
true
a0f6ba8f4571e7eb2fa3db91f82fae617f8e7093
CC3688/studycode
/Python/lxf-paython/004pythonBasic.py
1,287
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @ CC3688 # email:442677028@qq.com #条件判断 #if age = 20 if age >= 18 : print('your age is',age) print('adult') #if else age = 10 if age >= 18 : print('your age is',age) print('adult') else: print('your age is',age) print('adult') #elif ---->else if python 写为elif 注意多条件判断时,条件的先后顺序.if语句从上往下判 # 断,如果在 某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elif和else age = 2 if age >= 18: print('your age is',age,'. your are an adult') elif age >=10: print('your age is',age,'.Your are a teenager') else: print('your age is',age,'.Your are a kid') #input() 得到的是个字符串 可以用int() 进行转格数据类型 如果转不了就会报错 ''' birth = input('birth: ') #参数是显示给用户看的,提示用 birth = int(birth) if birth < 2000: print ("你是一个00前") else: print ("你是一个00后") ''' print ("-------homework-----") height = 1.75 weight = 80.5 #bmi = weight/(height*height) bmi = 17 if bmi > 32 : print ("严重肥胖") elif bmi >= 28 : print ("肥胖") elif bmi >=25: print ("过重") elif bmi >=18.5: print ("正常") else : print ("过轻")
false
d0a2a502929ec839607ab88eb4fa6eca97141342
jkoppel/QuixBugs
/python_programs/sqrt.py
420
4.3125
4
def sqrt(x, epsilon): approx = x / 2 while abs(x - approx) > epsilon: approx = 0.5 * (approx + x / approx) return approx """ Square Root Newton-Raphson method implementation. Input: x: A float epsilon: A float Precondition: x >= 1 and epsilon > 0 Output: A float in the interval [sqrt(x) - epsilon, sqrt(x) + epsilon] Example: >>> sqrt(2, 0.01) 1.4166666666666665 """
true
14857cf1f6d3397403c422ebad8994bc33848216
jkoppel/QuixBugs
/correct_python_programs/mergesort.py
2,389
4.15625
4
def mergesort(arr): def merge(left, right): result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:] or right[j:]) return result if len(arr) <= 1: return arr else: middle = len(arr) // 2 left = mergesort(arr[:middle]) right = mergesort(arr[middle:]) return merge(left, right) """ def mergesort(arr): def merge(left, right): result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:] or right[j:]) return result if len(arr) == 0 or len(arr) == 1: return arr else: middle = len(arr) // 2 left = mergesort(arr[:middle]) right = mergesort(arr[middle:]) return merge(left, right) def mergesort(arr): def merge(left, right): result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:] or right[j:]) return result if len(arr) == 1 or len(arr) == 0: return arr else: middle = len(arr) // 2 left = mergesort(arr[:middle]) right = mergesort(arr[middle:]) return merge(left, right) def mergesort(arr): def merge(left, right): result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:] or right[j:]) return result if len(arr) < 2: return arr else: middle = len(arr) // 2 left = mergesort(arr[:middle]) right = mergesort(arr[middle:]) return merge(left, right) """
true
23bf4b2a12455334e5fb0ffa4fce75a11cdb2378
jkoppel/QuixBugs
/python_programs/hanoi.py
1,138
4.40625
4
def hanoi(height, start=1, end=3): steps = [] if height > 0: helper = ({1, 2, 3} - {start} - {end}).pop() steps.extend(hanoi(height - 1, start, helper)) steps.append((start, helper)) steps.extend(hanoi(height - 1, helper, end)) return steps """ Towers of Hanoi hanoi An algorithm for solving the Towers of Hanoi puzzle. Three pegs exist, with a stack of differently-sized disks beginning on one peg, ordered from smallest on top to largest on bottom. The goal is to move the entire stack to a different peg via a series of steps. Each step must move a single disk from one peg to another. At no point may a disk be placed on top of another smaller disk. Input: height: The height of the initial stack of disks. start: The numbered peg where the initial stack resides. end: The numbered peg which the stack must be moved onto. Preconditions: height >= 0 start in (1, 2, 3) end in (1, 2, 3) Output: An ordered list of pairs (a, b) representing the shortest series of steps (each step moving the top disk from peg a to peg b) that solves the puzzle. """
true
2069cdf48656121df91bcc30ffe95be6a01d0392
ksharonkamal/workshop
/day3/2.py
236
4.125
4
#program to sum all items in dictionary dict1 = {"tony" : 100 , "thor" : 200 , "peter" : 300 ,"strange" : 400} sum = 0 # for i in dict1.values(): # sum+=i for i in dict1: sum+=dict1[i] print("sum of items in dict1 is ",sum)
false
c0421854953fd6080d9eefc56fade47695ffa823
Raghumk/TestRepository
/Functions.py
1,076
4.46875
4
# Parameter functions is always pass by reference in Python def fun1( Name ): Name = "Mr." + Name return Name def fun2(Name = "Raghu"): Name = "Mr." + Name return Name print (fun1("Raghu")) print (fun1(Name="Kiran")) # Named argument print (fun2()) # Default argument #### Variable length arguments def Multiple_Arguments(arg1, *vartuple): "This prints " print(arg1) ## First argument for x in vartuple: ## Subsequent arguments print(x) return x print ('multiple araguments = ', Multiple_Arguments(10, 20, 30)) ## Anonymous functions # not declared using 'def' # use lamda keyword for anaonymous functions # can take any number of arguments # cannot access outside variables. will have local namespace # syntax: # lambda [ arg1, [,arg2, arg3..]] : expression sum = lambda arg1, arg2, arg3 : arg1 + arg2 + arg3 # lambda function with 3 argument sum2 = lambda : 10 # lambda function without argument print ("Lambda sum = " , sum(10,20,30)) # Two types of variables. Global & Local
true
661fe981ec3b27d9b9d4f5d36e30634bf642d196
Raghumk/TestRepository
/Tuples.py
310
4.40625
4
#Tuples are sequence of Immutable (unchangable) objects tup1= ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = "a", "b", "c", "d" print (tup1, "\n", tup2 , "\n" , tup3 ) # accessing tuple elements is same as accessing list element print (tup1[1]) # chemistry. del tup1
false
24851e56fd5704a5693657d13cee92004aa81d7c
kneesham/cmp_sci_4250
/Main.py
2,458
4.25
4
### # Name: Theodore Nesham # Project: 4 # Date: 11/02/2019 # Description: This project was used to show inheritance, polymorphism, and encapsulation. The parent class is Product # and the two children classes are Book and Movie. The two subclasses override the print_description # function showing the use of polymorphism, as well as inherit functions and data members from product. ### class Product: __name = "Product Name" __price = 0 __discount_percent = 0 def __init__(self, name, price, discount_percent): self.__name = name self.__price = price self.__discount_percent = discount_percent def get_name(self): return self.__name def get_discount_price(self): return round(self.__price - self.__price * self. __discount_percent, 2) def get_discount_amount(self): return round(self.__price * self.__discount_percent, 3) def print_description(self): print("Product name: " + self.__name + "\nDiscount: $" + str(self.get_discount_amount()) + "\nPrice: $" + str(self.get_discount_price()) + "\n") class Book(Product): __author = "" def __init__(self, name, author, price, discount_percent): Product.__init__(self, name, price, discount_percent) # calling the Parent constructor. self.__author = author def print_description(self): print("Book name: " + self.get_name() + "\nauthor: " + self.__author + "\ndiscount amount: $" + str(self.get_discount_amount()) + "\nprice: $" + str(self.get_discount_price()) + "\n" ) class Movie(Product): __year = "" def __init__(self, movie_name, year, price, discount_percent ): Product.__init__(self, movie_name, price, discount_percent) self.__year = year def print_description(self): print("Movie name: " + self.get_name() + "\nYear: " + str(self.__year) + "\ndiscount amount: $" + str(self.get_discount_amount()) + "\nprice: $" + str(self.get_discount_price()) + "\n" ) custom_product = Product("Popcorn", 4.99, 0.01) batman_movie = Movie("Batman", 1999, 59.99, 0.05) cool_book = Book("The Mythical Man Moth", "Frederick P. Brooks, JR.", 29.99, 0.01) custom_product.print_description() batman_movie.print_description() cool_book.print_description()
true
c269df6a9e5ab28181e7073991e7fcd6756e1c6d
ahermassi/Spell-Checker
/src/trie/trie.py
1,712
4.125
4
from src.node.trie_node import TrieNode class Trie: def __init__(self): self.root = TrieNode() def __contains__(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ word = word.strip() root = self.root for c in word: if c not in root: # This is equivalent to: if c not in root.children. See __contains__ method of TrieNode. return False root = root[c] # This is equivalent to: root = root.children[c]. See __getitem__ method of TrieNode. return root.end_of_word def __len__(self): def helper(root): nonlocal length if root.end_of_word: length += 1 else: for node in root.children.values(): helper(node) root, length = self.root, 0 if not root: return 0 helper(root) return length def add(self, word): """ Traverse the trie and add new nodes as we go. :type word: str :rtype: None """ word = word.strip() root = self.root # n is for "node" for c in word: if c not in root: root[c] = TrieNode() root = root[c] root.end_of_word = True def starts_with(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ root = self.root for c in prefix: if c not in root: return False root = root[c] return True
true
580d41a8f9f430feaac5bdfbd8126afffa481d00
Tochi-kazi/Unit3-10
/calculate_average .py
358
4.15625
4
# Created by : Tochukwu Iroakazi # Created on : oct-2017 # Created for : ICS3UR-1 # Daily Assignment - Unit3-10 # This program displays average print('type in your score') userinput = input() counter = 0 numtotal = 0 for userinput in range (0,100): numtotal = numtotal + userinput counter = counter + 1 mark = numtotal / counter else: print(mark)
true
70277b5371bcdb5190de68567903b4ed8aade82f
thomasdephuoc/bootcamp_python
/day_00/ex_03/count.py
651
4.4375
4
def text_analyzer(text=None): """This function counts the number of upper characters, lower characters, punctuation and spaces in a given text.""" if text is None: text = input("What is the text to analyse?") nb_char = sum(1 for c in text if c.isalpha()) nb_upper = sum(1 for c in text if c.isupper()) nb_lower = sum(1 for c in text if c.islower()) nb_punc = sum(1 for c in text if c == "!") nb_spaces = sum(1 for c in text if c == " ") print("The text contains", nb_char, "characters:\n-", nb_upper, "upper letters\n-", nb_lower, "lower letters\n-", nb_punc, "punctuation marks\n-", nb_spaces, "spaces")
true
c696337cda0492a06385ab26fdff89cf8de0aa8f
irene-yi/Classwork
/Music.py
2,108
4.28125
4
class Music: # if you pass in artists while calling your class # you need to add it to init def __init__(self, name, artists): self.name = name self.artists = artists self.friends = {} # Pushing information to the array def display(self): print() print ("Your artists:") for artists in self.artists: print (artists) def add (self): # gather user input here add_artist = input('What artist do you want to add?') self.artists.append(add_artist) print ("Your artists:") for artists in self.artists: print (artists) def delete (self): # Deletes the last artist last given self.artists.pop() print ("Your artists:") for artists in self.artists: print (artists) # what are you comparing to? # how do you get that info? # Add to new datatype friend and shared song def compare_array(self, friend): compare = [thing for thing in self.artists if thing in friend.artists] # add value of compare to artist_array # setting the key in friends hash = to the value self.friends[friend.name] = compare print(self.friends) def add_friend(self): friend_name = input("Who do you want to add?") artists_name = input("Who do you want to add?") # adds the key #adds the value self.friends[friend_name] = artists_name print(self.friends) # Add friends and shared songs # for testing call your class and methods # name = Music(pass in arguments) estelle = Music('Estelle', ['La la las', 'Car Seat Head Rest']) # name, #artist array ben = Music('Ben', ['La la las', 'Food']) catie = Music('Ben', ['Car Seat Head Rest', 'Food', 'Cat']) while True: print("Enter 1 to display the list of artists") print("Enter 2 to add artists") print("Enter 3 to delete artists") print("Enter 4 to compare") print("Enter 5 to add friends") print("Enter 6 to quit") userChoice = int(input()) if userChoice is 1: estelle.display() elif userChoice is 2: estelle.add() elif userChoice is 3: estelle.delete() elif userChoice is 4: Music.compare_array(estelle, ben) elif userChoice is 5: estelle.add_friend() elif userChoice is 6: quit()
true
c4a1f0448e9ce013071569c6e3710bec01261f46
paralaexperimentacion/experiment1
/red_day16.py
2,003
4.25
4
import turtle import random #setting up variables t = turtle #to make writing code easier t.speed(10) while True: #assigning random numbers to variables for number and color num = random.randint(10,40) r = random.randint(1,255) b = 0 g = 0 t.pd() #assigns color of turtle t.color(r, b, g) #keeps the turtle from doing things out of the size of the screen if t.xcor() > 150: #if turtle reaches the side of the screen t.ht() #hides turtle from view t.pu() t.setx(-150) #brings turtle to opposite side of the screen t.st() #brings turtle back to view t.pd() elif t.xcor() < -150: t.ht() t.pu() t.setx(150) t.st() t.pd() if t.ycor() > 150: t.ht() t.pu() t.sety(-150) t.st() t.pd() elif t.ycor() < -150: t.ht() t.pu() t.sety(150) t.st() t.pd() #actually drawing if r < 85: #controls movement if r < 85 t.fd(num) t.rt(num / 2) for x in range(3): #draws three circles lol = random.randint(0,5) #sets radius for circle randomly if lol <= 3: #randomizes if fill happens or not t.begin_fill() #starts filling for a shape the turtle makes t.circle(lol) t.end_fill() #stops filling else: t.circle(lol) elif r >= 85 and r <= 170: #controls movement if r >= 85 and r <= 170 t.fd(num / 2) t.rt(num / 4) for x in range(5): #draws a star t.rt(144) t.fd(10) else: #controls movement if r > 170 and prints text t.fd(num / 4) t.lt(num / 2) if r < 200: #randomizes text that is printed t.write("HI", True, font = ("Verdana", 6, "normal")) #prints text if r < 255 and r >= 200: t.write("LOVE", True, font = ("Verdana", 6, "normal")) if r == 255: t.write("HAIL SATAN", True, font = ("Verdana", 12, "normal"))
false
7c78cdd9a7c791a82adfe6e19f2f9e1a63f3a953
IronManCool001/Python
/Guess The Number/main.py
590
4.125
4
import random chances = 5 print("Welcome To Guess The Number Game") no = random.randint(0,256) run = True while run: guess = int(input("Enter your guess")) if guess == no: print("You Got It") run = False break elif guess > no: print("You guessed higher!") chances -= 1 elif guess < no: print("You guessed lower!") chances -= 1 if chances == 0: print("You Lose") run = False
true