blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
40c7b0f8fe9101a9227cac07d0c9f6cbd5ef7fcc
AaronChelvan/adventOfCode
/2016/day6part1.py
1,079
4.15625
4
#!/usr/bin/python3 #Converts a letter to the corresponding number #a->0, b->1, ..., z->25 def charToNumber(char): return ord(char) - 97 #Converts a number to the corresponding letter #0->a, 1->b, ..., 25->z def numberToChar(number): return chr(number + 97) with open('day6_input.txt') as f: lines = f.readlines() answer = [] #Find the most frequent letter in each column for column in range(len(lines[0])-1): #An array containing the frequency of each letter. #Index 0 -> a, Index 1 -> b, etc. letterFreq = [0]*26 #Count the frequencies of each letter for line in lines: line = line.rstrip() letterFreq[charToNumber(line[column])] += 1 #Find the most common letter, by finding the highest value in letterFreq mostFreqLetterIndex = 0 #The index of the most frequent letter. 'a' has index 0, 'b' has index 1, etc. for i in range(len(letterFreq)): if letterFreq[i] > letterFreq[mostFreqLetterIndex]: mostFreqLetterIndex = i answer.append(numberToChar(mostFreqLetterIndex)) print("The error-corrected version of the message is: " + "".join(answer))
true
3b56fdb3d884695176207f5748a3c111d53cba06
gudmundurgh/Forritun
/dæmatímar/python_basic_excercises.py
253
4.25
4
low = int(input("Enter an integer: ")) high = int(input("Enter another integer: ")) sum_of_integers = 0 for i in range(low, high+1): if i % 3 == 0 or i % 5 == 0: sum_of_integers = sum_of_integers + i print(i) print(sum_of_integers)
false
afd6126ccad94f42620bd7c33233666f0c71e3a2
k08puntambekar/IMCC_Python
/Practical3/Program7.py
591
4.28125
4
# 7.Write a program to implement composition. class Company: def __init__(self, company_name, company_address): self.company_name = company_name self.company_address = company_address def m1(self): print("You are in", self.company_name, "company based in ", self.company_address) class Employee: def __init__(self, company_name, company_address): self.obj = Company(company_name, company_address) def m2(self): print("You are with an employee from this company") self.obj.m1() emp = Employee("Wipro", "Pune") emp.m2()
false
92f59612b2697db155da1bdc625fdabc115867b0
k08puntambekar/IMCC_Python
/Practical3/Program5.py
589
4.375
4
# 5. Write a program to implement polymorphism. class Honda: def __init__(self, name, color): self.name = name self.color = color def display(self): print("Honda car name is : ", self.name, " and color is : ", self.color) class Audi: def __init__(self, name, color): self.name = name self.color = color def display(self): print("Audi car name is : ", self.name, " and color is : ", self.color) HondaCar = Honda("Honda City", "White") AudiCar = Audi("A6", "Black") for car in (HondaCar, AudiCar): car.display()
true
f6e52e7cc61e9176624dcb96c899034e8ab011ea
jennyfothergill/project_euler
/problems/p9.py
712
4.28125
4
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. from math import sqrt n = 1000 def is_triplet(a, b, c): if a**2 + b**2 == c**2: return True return False def find_triplet(n): for a in range(1, n): for b in range(a+1, n): for c in range(1000-a-b, n): #print(a,b,c) if a+b+c == n: if is_triplet(a,b,c): return a,b,c a,b,c = find_triplet(n) print(f"The sum of triplet {a}, {b}, and {c} = 1000")
true
e75b4ae01cdd3c69351143331b14b526c68b660e
Michael-Zagon/ICS3U-Unit4-07-Python
/1_2_number_printer.py
485
4.375
4
#!/usr/bin/env python3 # Created by: Michael Zagon # Created on: Oct 2021 # This program lists every number from 1000 to 2000 def main(): # This function lists every number from 1000 to 2000 counter = 0 # Process and Output for counter in range(1000, 2001): if counter % 5 == 0: print("") print(counter, end=" ") else: print("{0} ".format(counter), end="") print("\nDone.") if __name__ == "__main__": main()
true
15025d260c7794e1a19a129429e2991d8a705ada
devilhtc/leetcode-solutions
/0x01e9_489.Robot_Room_Cleaner/solution.py
2,537
4.125
4
# """ # This is the robot's control interface. # You should not implement it, or speculate about its implementation # """ # class Robot: # def move(self): # """ # Returns true if the cell in front is open and robot moves into the cell. # Returns false if the cell in front is blocked and robot stays in the current cell. # :rtype bool # """ # # def turnLeft(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def turnRight(self): # """ # Robot will stay in the same cell after calling turnLeft/turnRight. # Each turn will be 90 degrees. # :rtype void # """ # # def clean(self): # """ # Clean the current cell. # :rtype void # """ class Solution: def cleanRoom(self, robot): """ :type robot: Robot :rtype: None """ def goto(pos1, pos2): # robot always face up if pos2[0] - pos1[0] == 1: # go right robot.turnRight() m = robot.move() robot.turnLeft() elif pos2[0] - pos1[0] == -1: # go left robot.turnLeft() m = robot.move() robot.turnRight() elif pos2[1] - pos1[1] == 1: # go up m = robot.move() else: # go down robot.turnLeft() robot.turnLeft() m = robot.move() robot.turnLeft() robot.turnLeft() return m visited = collections.defaultdict(lambda: False) x = 0 y = 0 stack = [[0, 0, 0]] visited[(0, 0)] = True dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] while len(stack) > 0: last = stack[-1] x, y, t = tuple(last) if t == 4: robot.clean() stack.pop() if len(stack) > 0: # backtrack goto((x, y), stack[-1][:2]) continue dx, dy = dirs[t] nx, ny = x + dx, y + dy stack[-1][2] += 1 if visited[(nx, ny)]: continue m = goto((x, y), (nx, ny)) if m: # moved to (nx, ny) visited[(nx, ny)] = True stack.append([nx, ny, 0])
true
f1b5efe9da688ec3db58dac8a9bb293ef095ae5a
gwccu/day3-Maya-1000
/problemSetDay3.py
728
4.21875
4
integer = int(input("Tell me a number.")) if integer % 2 == 0: print("That is even.") else: print("Why did you put in an odd number? I don't like them.") a = int(input("Tell me another number.")) if a % 2 == 0: print("That is even.") else: print("Why did you put in an odd number? I don't like them.") b = int(input("Tell me a third number.")) if b % 2 == 0: print("That is even.") else: print("Why did you put in an odd number? I don't like them.") if b % 2 == 0 and a % 2 == 0 and integer % 2 == 0: print("all your numbers are even! wow!") else: print("You put at least one odd number, which I didn't like. :(") print(" I didn't have time for part 3, as I needed to leave early. Sorry!")
true
a182e54029a511e2475e56f3de533a1685fc9c97
Fanz11/homework3
/main.py
1,177
4.28125
4
# первое number1 = [1, 2, 3] #числа number2 = [i * 2 for i in number1] #умножение на 2 print(number2) #ответ # второе number1 = [1, 2, 3] #числа number2 = [i ** 2 for i in number1] #возведение в вторую степень print(number2) #ответ #трертье list = 'Hello world' if " " in list: #если есть пробел list = list.upper() #перевод в верхний регистр print(list) #ответ else: #если нет пробела list = list.lower() #то переводиться в нижний регистр print(list) #ответ #четвертое for i in range(1900, 2021): # диапозон годов print(i) # вывод
false
be98c59ba48044650c0e0a990b1cdd831d1b1d0f
gflorianom/Programacion
/Practica5/Ejercicio3.py
404
4.25
4
"""Biel Floriano Morey - 1 DAW - PRACTICA5 - EJERCICIO 3 Escriu un programa que demani notes i les guardi en una llista. Per a terminar d'introduir notes, escriu una nota que no estigui entre 0 i 10. El programa termina escrivint la llista de notes. """ print "Escribe una nota" n=float(raw_input()) notas=[] while (n<=10 and n>=0): notas.append(float(n)) n=float(raw_input("otra nota")) print notas
false
7ab1de683ab9a0a12d0b7e7d78378244412f3fd3
gflorianom/Programacion
/Practica5/Ejercicio10.py
922
4.28125
4
"""Biel Floriano Morey - 1 DAW - PRACTICA5 - EJERCICIO 10 Escriu un programa que et demani els noms i notes d'alumnes. Si escrius una nota fora de l'interval de 0 a 10, el programa entendr que no vols introduir ms notes d'aquest alumne. Si no escrius el nom, el programa entendr que no vols introduir ms alumnes. Nota: La llista en la que es guarden els noms i notes s [ [nom1, nota1, nota2, etc], [nom2, nota1, nota2, etc], [nom3, nota1, nota2, etc], etc] """ print "Dame un nombre" n=raw_input() personas=[] personas2=[] while n<>"": personas.append(n) print "Escribe una nota" nota=float(input()) while nota<=10 and nota>=0: personas.append(nota) print "Escribe otra nota" nota=float(input()) personas2.append(personas) print "Introduce otro nombre" n=raw_input() personas=[] print "Las notas de los alumnos son: " print (personas2)
false
7124ec44628cab139bbfb750fd872c95623ce33f
keerthikapopuri/Python
/lab2_8.py
205
4.1875
4
def factorial(n): if n==0: return 1 else: recurse=factorial(n-1) result=n*recurse return result n=int(input("enter a number: ")) res=factorial(n) print(res)
false
d301a77da333fee20a0792a4aa2e21e3230913a9
sherry-fig/CEBD1100_Work
/function2.py
336
4.125
4
def isnumbernegative(n): if n<0: return True return False print(isnumbernegative(4)) my_value=-2 #print number is negative OR number is positive if isnumbernegative(my_value): print("number is negative") else: print("number is positive") def isnumbernegative(n): return n<0 print(isnumbernegative(4))
false
313e68bb71568fe1e8709fd03ecb4e999bc29ac5
lisali72159/leetcode
/easy/1200_min_abs_diff.py
1,088
4.15625
4
# Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. # Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows # a, b are from arr # a < b # b - a equals to the minimum absolute difference of any two elements in arr # Example 1: # Input: arr = [4,2,1,3] # Output: [[1,2],[2,3],[3,4]] # Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. # Example 2: # Input: arr = [1,3,6,10,15] # Output: [[1,3]] def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: result = [] arr.sort() min_diff = float("inf") for i in range(1, len(arr)): current_diff = arr[i] - arr[i - 1] if current_diff < min_diff: min_diff = current_diff result = [[arr[i-1], arr[i]]] elif current_diff == min_diff: result.append([arr[i-1], arr[i]]) return result
true
e29ba721cad2cf58d8c8c2e41b6b69347a96a677
jzohdi/practice
/SimpleSymbols.py
1,138
4.125
4
# Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence # by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them # (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. # So the string to the left would be false. The string will not be empty and will have at least one letter # # def checkArray(myArray): for x in range(len(myArray)): if myArray[0].isalpha(): return False if myArray[(len(myArray) - 1)].isalpha(): return False if myArray[x].isalpha(): if myArray[x-1] == '+' and myArray[x+1] == '+': return True if myArray[x-1] != '+' or myArray[x+1] != '+': return False def SimpleSymbols(str): newArray = [] for i in range(len(str)): newArray.append(str[i]) if checkArray(newArray): return 'true' if not checkArray(newArray): return 'false' print SimpleSymbols(raw_input())
true
2c570dd2659fa744d2234d7e70062979008c9fe3
nsky80/competitive_programming
/Hackerrank/Archive 2019/Python Evaluation(built_ins).py
412
4.375
4
# The eval() expression is a very powerful built-in function of Python. It helps in evaluating an expression. # The expression can be a Python statement, or a code object. # >>> x = 3 # >>> eval('x+3') # 6 # >>> a = 'x**2 + x**1 + 1' # >>> eval(a) # 13 # >>> type(eval("len")) # <class 'builtin_function_or_method'> # >>> type("len") # <class 'str'> # >>> a = 'print(2 + 3)' # >>> eval(a) # 5 eval(input())
true
e0ceeb1da7502b6db937c7cf7da90f4c8adb1eb4
BrichtaICS3U/assignment-2-logo-and-action-NAKO41
/logo.py
2,391
4.34375
4
# ICS3U # Assignment 2: Logo # <NICK SPROTT> # adapted from http://www.101computing.net/getting-started-with-pygame/ # Import the pygame library and initialise the game engine import pygame pygame.init() import math # Define some colours # Colours are defined using RGB values BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BEETSRED = (181, 16, 32) PURP = (49, 7, 122)#this purple is the colour of the main body of the logo LIGHTPURP = (79, 55, 122)#this is used to colour in the small faded circle YELLOW = (242,161,0)#this is the colour of the ark # Set the screen size (please don't change this) SCREENWIDTH = 400 SCREENHEIGHT = 400 # Open a new window # The window is defined as (width, height), measured in pixels size = (SCREENWIDTH, SCREENHEIGHT) screen = pygame.display.set_mode(size) pygame.display.set_caption("Eclipse logo") # This loop will continue until the user exits the game carryOn = True # The clock will be used to control how fast the screen updates clock = pygame.time.Clock() #---------Main Program Loop---------- while carryOn: # --- Main event loop --- for event in pygame.event.get(): # Player did something if event.type == pygame.QUIT: # Player clicked close button carryOn = False # --- Game logic goes here # There should be none for a static image # --- Draw code goes here # Clear the screen to white screen.fill(WHITE)#changed to background to black # Queue different shapes and lines to be drawn #i am drawing the eclipse logo pygame.draw.ellipse(screen,YELLOW,[2,10,400,380])#this is the yellow arc pygame.draw.ellipse(screen,WHITE,[30,0,400,400])#this circle is used to create the arc in the logo pygame.draw.ellipse(screen,PURP,[40,30,340,340])#this is the body circle pygame.draw.ellipse(screen,LIGHTPURP,[110,105,200,200])#mid light purple circle pygame.draw.rect(screen,PURP,[110,105, 200,100])#blocks half the light purple pygame.draw.rect(screen,WHITE,[39,150,400,20])#white line #1 pygame.draw.rect(screen,WHITE,[39,190,400,20])#white line #2 pygame.draw.rect(screen,WHITE,[39,230,400,20])#white line #3 # Update the screen with queued shapes pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Once the main program loop is exited, stop the game engine pygame.quit()
true
0f0f464b3c550ec5397d59392aa038993d3521a1
ankurtechtips/att
/circularqueue.py
1,159
4.15625
4
# This is the CircularQueue class class CircularQueue: # taking input for the size of the Circular queue def __init__(self, maxSize): self.queue = list() # user input value for maxSize self.maxSize = maxSize self.head = 0 self.tail = 0 # add element to the queue def enqueue(self, data): if self.size() == (self.maxSize - 1): return("Queue is full!")20 else: self.queue.append(data) self.tail = (self.tail+1) % self.maxSize return True # remove element from the queue def dequeue(self): if self.size() == 0: return("Queue is empty!") else: data = self.queue[self.head] self.head = (self.head+1) % self.maxSize return data q = CircularQueue(7) # change the enqueue and dequeue statements as you want print(q.enqueue(10)) print(q.enqueue(20)) print(q.enqueue(30)) print(q.enqueue(40)) print(q.enqueue(50)) print(q.enqueue('Studytonight')) print(q.enqueue(70)) print(q.enqueue(80)) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue())
true
7e4a9f3cd3ebc8aa92284b5b2c62a1256b51f401
rastislp/pands-problem
/weekday.py
1,677
4.46875
4
#Rastislav Petras #12 Feb 2020 #Excercise 5 #Write a program that outputs whether or not today is a weekday. # An example of running this program on a Thursday is given below. print() print("Welcome in day teller.") print() import datetime #import librarys with time functions. import calendar #import librarys with calendar functions. x = datetime.datetime.today() #assign today current time year = x.strftime("%Y") # extract year from x #print("year:", year) month = x.strftime("%m") # extract month from x #print("month:", month) day = x.strftime("%d") # extract day from x #print("day:", day) year = int(year) #converts string into integer month = int(month) #converts string into integer day = int(day) #converts string into integer z = calendar.weekday(year, month,day) # wwekday function calculates week day (1-7) based on date entered #print(z) if (z < 6): #conditional statement if weekday is betwen 1-5 print("Today",x ,"is a week day, unfortunately ;-(") else: #conditional statement if weekday is betwen 6 and 7 print("Today",x ,"is a weekend ;-)") print() #empty blank lne #bonus year = int(input('Enter a year: ')) #input integer as follow: year month day month = int(input('Enter a month: ')) day = int(input('Enter a day: ')) date1 = calendar.weekday(year, month, day) # week day number is assigned to variable date1 not used in this case date2 = datetime.date(year, month, day) # fulll date is assigned to variable date2 date3 = calendar.day_name[date1] # week day name is assigned to variable date3 print("Day you have entered", date2, "is: ",date3) # print out full date and week date name.
true
04a05dfedb19b73cb631555d9ea17d8c79f00b26
rastislp/pands-problem
/primenum.py
542
4.125
4
# Ian McLoughlin # Computing the primes. # My list of primes - TBD. P = [] # Loop through all of the numbers we're checking for primality. for i in range(2, 1000): # Assume that i is a prime. isprime = True # Loop through all values j from 2 up to but not including i. for j in P: # See if j divides i. if i % j == 0: # If it does, i isn't prime so exit the loop and indicate it's not prime. isprime = False break # If i is prime, then append to P. if isprime: P.append(i) # Print out our list. print(P)
true
5d807153dd64a43c86d4db233d3cc20b9a62fc5c
williamSouza21/exercicios-em-python
/Calculadora_1.0_.py
1,122
4.3125
4
valor1 = float(input("Digite o 1° valor: ")) valor2 = float(input("Digite o 2° valor: ")) print("Operações matemáticas da calculadora: ") print("1- Adição") print("2- Subtração") print("3- Multiplicação") print("4- Divisão") print("5- Potenciação") print("6- Radiciação") operação = int(input("Escolha a operação: ")) if(operação == 1): soma = valor1 + valor2 print("{} + {} = {:.2f}".format(valor1, valor2, soma)) elif(operação == 2): subtração = valor1 - valor2 print("{} - {} = {:.2f}".format(valor1, valor2, subtração)) elif(operação == 3): multiplicação = valor1 * valor2 print("{} * {} = {:.2f}".format(valor1, valor2, multiplicação)) elif(operação == 4): divisão = valor1 / valor2 print("{} / {} = {:.2f}".format(valor1, valor2, divisão)) elif(operação == 5): potenciação = pow(valor1, valor2) print("{} ^ {} = {:.2f}".format(valor1, valor2, potenciação)) elif(operação == 6): radiciação = pow(valor1, 1/2) print("A raiz quadrada de {} é {:.2f}".format(valor1, radiciação)) else: print("Operação inválida!")
false
93b119123f07094a993e4420dd6e56be1918d59b
ZyryanovAV/lb8
/Общее 1.py
693
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Решите задачу: создайте словарь, где ключами являются числа, а значениями – строки. # Примените к нему метод items(), c с помощью полученного объекта dict_items создайте # новый словарь, "обратный" исходному, т. е. ключами являются строки, а значениями – # числа. if __name__ == '__main__': school = {1: 'One', 2: 'Two', 3: 'Three'} new_school = {} for key, value in school.items(): new_school[value] = key print(new_school)
false
9d5dd4c12b1186a88ad6379c9a4a058d63d3bfde
ishleigh/PythonProjects
/BulletsAdder.py
805
4.21875
4
""" 1. Paste text from the clipboard -pyperclip.paste() 2. Do something to it- add bullets * 3. Copy the new text to the clipboard -pyperclip.copy() """ #! python3 # bulletPointAdder.py - Adds Wikipedia bullet points to the start # of each line of text on the clipboard. import pyperclip text = pyperclip.paste() #copy text to the clipboard # Separate lines and add stars. lines = text.split('\n') #after every new line add * before the follwoing line for i in range(len(lines)): # loop through all indexes for "lines" list lines[i] = '* ' + lines[i] # add star to each string in "lines" list """ To make this single string value, pass lines into the join() method to get a single string joined from the list’s strings """ text = '\n'.join(lines) pyperclip.copy(text)
true
7363fe66b7718058f37b9dcb90dc140b3b569fec
r426/python_basics
/10_special_numbers_no_sum.py
782
4.28125
4
# Find out if it is a special number: # composed of only odd prime digits and # the sum of its digits is an even number. # Implementation based on the number of digits # (not their sum). def number(): while True: userInput = input('Please enter a non-negative integer number: ') if userInput.isnumeric(): return int(userInput) else: print("Input error.") def isSpecial(num): if num == 0: return False noOfDigits = 0 while num > 0: digit = num % 10 if digit == 3 or digit == 5 or digit == 7: noOfDigits += 1 num //= 10 else: return False if noOfDigits % 2 == 0: return True else: return False print(isSpecial(number()))
true
b5a9de5c17145944f5e182c5a947aafa642e2146
r426/python_basics
/03_reverse_number.py
468
4.3125
4
# Generate the reverse of a given number N. def number(): while True: userInput = input('Please enter a big non-negative integer number: ') if userInput.isnumeric(): return int(userInput) else: print("Input error.") def reverse(number): reverseNumber = 0 while number != 0: reverseNumber = reverseNumber * 10 + number % 10 number //= 10 return reverseNumber print(reverse(number()))
true
74b0ef4a5944da5c9e586712e0b28630abcf1f38
richardOlson/cs-module-project-recursive-sorting
/src/searching/searching.py
2,520
4.34375
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # the base case if start > end: return -1 # pick the middle point = start + ((end - start)//2) if arr[point] == target: return point if arr[point] > target: # need to go left here end = point -1 else: start = point + 1 return binary_search(arr, target, start, end) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # This is the comparator that I made that will # return 0 to mean go left and 1 to mean go right def comparator(target_val, point_chosen_val, ascending=True): if ascending: # this is ascending order if target_val < point_chosen_val: return 0 # this means to to left else: return 1 # go right else: # descending if target_val > point_chosen_val: return 0 # Go left else: return 1 # go right def binary_search_inner(arr, target, start, end, ascending=True): # base case if start > end: return -1 # moving to the middle of the start and the end pt_chosen = start + ((end - start)//2) if arr[pt_chosen] == target: return pt_chosen else: # figuring which way to travel if comparator(target_val=target, ascending=ascending, point_chosen_val=arr[pt_chosen]) == 0: # means to go left end = pt_chosen -1 else: # in here means to go right start = pt_chosen + 1 return binary_search_inner(arr, target, start, end, ascending) def agnostic_binary_search(arr, target): # creating the binary search that is order agnostic # I am making this method to call the one above and # be a wrapper of the method above # first will be checking to see if the arr is empty if len(arr) == 0: return False # will check to see if the who is the larger value # the first or the last if arr[0] <= arr[len(arr)-1]: # This means that we have ascending order return binary_search_inner(arr, target, start=0, end=len(arr)-1, ascending=True) else: return binary_search_inner(arr, target, start=0, end=len(arr)-1, ascending=False)
true
ff295d4749a6c22db1c54b07c127d7debb27e1f3
raju7572/learning_python
/chapter7,8&9.py
2,485
4.1875
4
def sequence(n): while n != 1: print(n), if n % 2 == 0: # n is even n = n / 2 else: # n is odd n = n * 3 + 1 while True : line=raw_input('>') if line == 'done': break print(line) print('done!') import matheval var = ('math.sqrt(5)') 2.26069774997898 eval('type(mayh.pi)') import math def factorial(n): """computes factorial of n.""" if n == 0: return 1 else: recurse = factorial(n - 1) result = n * recurse return result def estimate_pi(): """compute an estimate of pi.""" total = 0 k = 0 factor = 2 * math.sqrt(2) / 9801 while True: num = factorial * (4 * k) * (1103 + 26390 * k) den = factorial(k) ** 4 * 396 ** (4 * k) term = factor * num / den total += term if abs(term) < 1e-15: break k += 1 return 1 / total print(estimate_pi()) fruit = 'banana' letter = fruit[1] print(letter) preflixes = 'JKLMNOPQ' sufflix = 'ack' for letter in preflixes: print(letter + sufflix) word= "banana" count=0 for letter in word: if letter=='a': count=count+1 print(count) word='banana' new_word=word.upper() print(new_word) def any_lowercase1(s): for c in s: if c.islower(): return True else: return False def any_lowercase2(s): for c in s: if 'c'.islower(): return 'True' else: return 'False' def any_lowercase3(s): for c in s: flag=c.islower() return flag def any_lowercase4(s): flag=false for c in s: flag=flag or c.islower() def is_abecedarian(word): previous=word[0] for c in word: if c <previous: return False previous=creturn True def is_abecedarian(word): if len(word)<=1: return True if word[0]>word[1]: return False return is_abecedarian(word[1:]) def is_abecedarian(word): i=0 j=len(word)-1 while i<j: if word[i]!=word[j]: return False i=i+1 j=j-1 return True
false
492d7bf144f95fe083013ca38e4e94ed849c4a79
a123aaa/python_know
/Python知识清单/字符串(str)的查询.py
491
4.3125
4
arr='hello,hello' print(arr.index('lo')) #3 print(arr.find('lo')) #3 print(arr.rindex('lo')) #9 print(arr.rfind('lo')) #9 #字符串的查询 #index() 查找子串第一次出现的位置,如果找不到就报错 #rindex() 查找子串最后一次出现的位置,如果找不到就报错 #find() 查找子串第一次出现的位置,如果找不到就返回-1 #rfind() 查找子串最后一次出现的位置,如果找不到就返回-1
false
ec65536007e903b26e133bb7319a8ae70af247e5
a123aaa/python_know
/Python知识清单/字符串(str)大小写变换.py
781
4.21875
4
arr='aBcDe' app=arr.swapcase() print(app) #AbCdE app=arr.upper() print(app) #ABCDE app=arr.lower() print(app) #abcde arr='I LOVE YOU' print(arr.title()) #I Love You arr='I LOVE YOU' print(arr.capitalize()) #I love you #新字符串=字符串 .upper() 把所有字母改为大写 #新字符串=字符串 .lower() 把所有字母改为小写 #新字符串=字符串 .swapcase() 把所有字母的大小写交换 #新字符串=字符串 .capitalize() 把第一个单词的第一个字符改为大写,其他单词都为小写 #新字符串=字符串 .title() 把每个单词的第一个字符转换为大写,把每个单词的其余字符转换为小写
false
5c1433f1a874101aed6c6da3edff753181d8b785
a123aaa/python_know
/Python知识清单/内置函数range.py
1,160
4.21875
4
for i in range(3): print(i) #0 1 2 for i in range(-3): print(i) #无 for i in range(1,5): print(i) #1 2 3 4 for i in range(-3,5): print(i) #-3 -2 -1 0 1 2 3 4 for i in range(-3,-5): print(i) #无 for i in range(2,8,2): print(i) #2 4 6 for i in range(2,8,-2): print(i) #无 print(3 in range(1,5,2)) #True print(-3 in range(-5,2,2)) #True print(8 in range(1,8,1)) #False #range()函数用于创造一个整数序列,返回值是一个迭代器对象 #stop必须大于0,当stop为负时,什么都不打印 #range( stop ) 创造一个[0,stop-1]之间的整数序列,步长默认为1. #range( start ,stop ) 创造一个[start ,stop-1]之间的整数序列,步长默认为1。start可以为负数 #range( start ,stop ,step) 创造一个[0,stop-1]之间的整数序列,步长为strp #range()函数不用时仅仅存储start,stop,step三个参数,只有当参与计算时才有相关元素 #可以用 in 和 not in 判断整数序列是否存在
false
d7d14f7f96abc194328ef5700d56ca7a73cbe97b
a123aaa/python_know
/Python知识清单/列表(list)排序.py
1,218
4.28125
4
#列表名 . sort() 达到升序效果,且地址不变 #列表名 . sort( reverse = False ) 达到升序效果,且地址不变 #列表名 . sort( reverse = True ) 达到降序效果,且地址不变 #新列表名 = sorted(列表名) 达到升序效果,地址改变 #新列表名 = sorted(列表名 ,reverse = False ) 达到升序效果,地址改变 #新列表名 = sorted(列表名 ,reverse = True ) 达到降序效果,地址改变 arr=[60,50,40,30,20,10] arr.sort() #或者 arr.sort( reverse = False ) print(arr) #[10, 20, 30, 40, 50, 60] arr=[10,20,30,40,50,60] arr.sort( reverse = True ) print(arr) #[60, 50, 40, 30, 20, 10] arr=[98, 54, 40, 20, 10] new_arr=sorted(arr) #new_arr=sorted(arr,reverse = False ) print(new_arr) #[10, 20, 40, 54, 98] arr=[20,40,10,98,54] new_arr=sorted(arr,reverse=True) #或者new_arr=sorted(arr) print(new_arr) #[98, 54, 40, 20, 10]
false
b810f69f0cbbd72a740385f8e954cc7524769ab8
MannyP31/CompetitiveProgrammingQuestionBank
/Arrays/Maximum_Difference.py
1,177
4.28125
4
''' From all the positive integers entered in a list, the aim of the program is to subtract any two integers such that the result/output is the maximum possible difference. ''' # class to compute the difference class Difference: def __init__(self, a): # getting all elements from the entered list self.__elements = a def computeDifference(self): # maximum difference would be the difference between the largest and the smallest integer Difference.maximumDifference = max(self.__elements)-min(self.__elements) return Difference.maximumDifference # end of Difference class # getting the input _ = input() a = [int(e) for e in input().split(' ')] # creating an object of the class d = Difference(a) # calling function 'computeDifference' to compute the difference d.computeDifference() # printing the result print(d.maximumDifference) ''' COMPLEXITY: Time Complexity -> O(N) Space Complexity -> O(1) Sample Input: 3 1 2 5 Sample Output: 4 Explanation: Integer with max value--> 5 Integer with min value--> 1 Hence, maximum difference--> 5-1 = 4 '''
true
3203f96749773440ba87ed366bd845ea5a43a2c9
MannyP31/CompetitiveProgrammingQuestionBank
/DSA 450 GFG/reverse_linked_list_iterative.py
960
4.125
4
#https://leetcode.com/problems/reverse-linked-list/ # Iterative method #Approach : # Store the head in a temp variable called current . # curr = head , prev = null # Now for a normal linked list , the current will point to the next node and so on till null # For reverse linked list, the current node should point to the previous node and the first node here will point to null # Keep iterating the linkedlist until the last node and keep changing the next of the current node to prev node and also # update the prev node to current node and current node to next node # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head): curr = head prev = None while(curr != None): next = curr.next curr.next = prev prev = curr curr = next return prev
true
5c3d15047bcfc2d2d43b0063c428effa2b6c88d1
MannyP31/CompetitiveProgrammingQuestionBank
/Data Structures/Graphs/WarshallAlgorithm.py
1,567
4.25
4
''' A program for warshall algorithm.It is a shortest path algorithm which is used to find the distance from source node,which is the first node,to all the other nodes. If there is no direct distance between two vertices then it is considered as -1 ''' def warshall(g,ver): dist = list(map(lambda i: list(map(lambda j: j, i)), g)) for i in range(0,ver): for j in range(0,ver): dist[i][j] = g[i][j] #Finding the shortest distance if found for k in range(0,ver): for i in range(0,ver): for j in range(0,ver): if dist[i][k] + dist[k][j] < dist[i][j] and dist[i][k]!=-1 and dist[k][j]!=-1: dist[i][j] = dist[i][k] + dist[k][j] #Prnting the complete short distance matrix print("The distance matrix is\n") for i in range(0,ver): for j in range(0,ver): if dist[i][j]>=0: print(dist[i][j],end=" ") else: print(-1,end=" ") print("\n") #Driver's code def main(): print("Enter number of vertices\n") ver=int(input()) graph=[] #Creating the graph print("Enter the graph\n") for i in range(ver): a =[] for j in range(ver): a.append(int(input())) graph.append(a) warshall(graph,ver) if __name__=="__main__": main() ''' Time Complexity:O(ver^3) Space Complexity:O(ver^2) Input/Output: Enter number of vertices 4 Enter the graph 0 8 -1 1 -1 0 1 -1 4 -1 0 -1 -1 2 9 0 The distance matrix is 0 3 -1 1 -1 0 1 -1 4 -1 0 -1 -1 2 3 0 '''
false
942a3dd1c36e73edb02447e99929d8025b0814cd
MannyP31/CompetitiveProgrammingQuestionBank
/Data Structures/Stacks/balanced_parentheses.py
792
4.21875
4
## Python code to Check for # balanced parentheses in an expression #Function to check parentheses def validparentheses(s): open_brace=["{","[","("] closed_brace=["}","]",")"] stack=[] for i in s: if i in open_brace: stack.append(i) elif i in closed_brace: p=closed_brace.index(i) if len(stack)>0 and open_brace[p]==stack[len(stack)-1]: stack.pop() else: return False if(len(stack)==0): #return true if given expression is balanced return True else: return False #return false is not balanced s=input("Enter the Expression to be evaluated:") if(validparentheses(s)): print("Expression is Balanced") else: print("Expression is Unbalanced")
true
7979d5e0293630e4b6934b5cf35600e720028bd2
MannyP31/CompetitiveProgrammingQuestionBank
/General Questions/Longest_Common_Prefix.py
868
4.28125
4
#Longest Common Prefix in python #Implementation of python program to find the longest common prefix amongst the given list of strings. #If there is no common prefix then returning 0. #define the function to evaluate the longest common prefix def longestCommonPrefix(s): p = '' #declare an empty string for i in range(len(min(s, key=len))): f = s[0][i] for j in s[1:]: if j[i] != f: return p p += f return p #return the longest common prefix n = int(input("Enter the number of names in list for input:")) print("Enter the Strings:") s = [input() for i in range(n)] if(longestCommonPrefix(s)): print("The Common Prefix is:" ,longestCommonPrefix(s)) else: print("There is no common prefix for the given list of strings, hence the answer is:", 0)
true
791bf0a4ddf889ce2cccfaf1837e9e6dd8b103f6
MannyP31/CompetitiveProgrammingQuestionBank
/Arrays/Array Reversal.py
225
4.3125
4
'''This is a Program to reverse an array i.e. Input: 1,2,3,4,5 Output:5,4,3,2,1''' # Taking array input l=input().split() #Creating reverse array r=[] for i in range(0,len(l)): r.append(int(l[len(l)-i-1])) print(r)
false
84c655acc227222e4f6e141c97949be2aac1e22a
mori-c/cs106a
/sandbox/sandcastles.py
1,495
4.3125
4
""" File: sandcastles.py ------------------------- Practice of control flow, variable and function concepts using the following files: 1 - subtract_numbers.py 2 - random_numbers.py 3 - liftoff.py """ import random import array def main(): """ Part 1 - user inputs numbers, py separates numbers with substracton operator - input(42) - int(input) - print(4-2) """ print('Let\'s start a program. You\'ll be entering 2 numbers where one number subtracts from another.') num1 = input('Enter first number: ') num1 = int(num1) num2 = input('Enter second number: ') num2 = int(num2) total = num1 - num2 total = str(total) print('Your result is ' + total) """ Part 2 - print 10 random intergers between 0 and 100 - random.randint() -> generate random numbers - print rand(10) - NUM_RANDOM -> randomizes 10 numbers - MIN_RANDOM - MAX_RANDOM """ min_random = 0 max_random = 100 for i in range(10): num_random = random.randint(min_random, max_random) print(num_random) """ Part 3 - spaceship launch - reserve print from 10 to 1 - print('Liftoff!') - for i in range() """ success = 'Liftoff!' def countdown(): # for i in reversed(range(1, max_count + 1)): for i in range(10, 0, -1): print(i) # print(success) countdown() print(success) # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
ff56ce66a59f499b792bd149fe299703dc332a71
JokerJudge/py111_lab
/Tasks/a2_priority_queue.py
1,622
4.28125
4
""" Priority Queue Queue priorities are from 0 to 5 """ from typing import Any queue = [] MIN_QUEUE_PRIORITY = 5 def enqueue(elem: Any, priority: int = 0) -> None: """ Operation that add element to the end of the queue :param elem: element to be added :return: Nothing """ global queue queue.append((priority, elem)) return None def dequeue() -> Any: """ Return element from the beginning of the queue. Should return None if not elements. :return: dequeued element """ global queue, MIN_QUEUE_PRIORITY min_ = MIN_QUEUE_PRIORITY min_res = None if queue: #for i in queue: # находим сначала минимальный приоритет # if i[0] < min_: # min_ = i[0] #for i in queue: # выбираем первый в списке элемент с минимальной очередью # if i[0] == min_: # temp = i[1] # queue.remove(i) # return temp for i in queue: # переделал. Теперь работает за один проход по циклу if i[0] < min_: min_ = i[0] min_res = i[1] temp = min_res queue.remove((min_, min_res)) return temp else: return None def peek(ind: int = 0, priority: int = 0) -> Any: """ Allow you to see at the element in the queue without dequeuing it :param ind: index of element (count from the beginning) :return: peeked element """ global queue if queue: try: return queue[ind][1] except IndexError: return None else: return None def clear() -> None: """ Clear my queue :return: None """ global queue queue = [] return None if __name__ == "__main__": pass
false
cfeb93211aa0377e330ddde26d4eed63766f790f
vinaym97/Simple-Tic-Tac-Toe
/Topics/Split and join/Spellchecker/main.py
906
4.1875
4
"""Write a spellchecker that tells you which words in the sentence are spelled incorrectly. Use the dictionary in the code below. The input format: A sentence. All words are in the lowercase. The output format: All incorrectly spelled words in the order of their appearance in the sentence. If all words are spelled correctly, print OK. Sample Input: srutinize is to examene closely and minutely Sample Output: srutinize examene Sample Input: all correct Sample Output: OK""" dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal', 'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize', 'sign', 'the', 'to', 'uncertain'] sentence = input().split() wrong_word = [] for i in sentence: if i not in dictionary: wrong_word.append(i) if len(wrong_word) == 0: print("OK") else: for word in wrong_word: print(word)
true
8979055b59283c406fc719d073cecbb72c327f06
mchughj/AirQualitySensor
/storage/create_sqlite_db.py
1,666
4.46875
4
#!/usr/bin/python3 # This program will create the table structure within the # sqlite3 database instance. It destroys existing data # but only if you allow it. import sqlite3 import os.path def create_connection(db_file): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(db_file) print("Created the database '{}' with sqlite version {}".format(db_file,sqlite3.version)) except Error as e: print(e) return conn def drop_then_create_table(conn): try: c = conn.cursor() remove_table_sql = """ DROP TABLE IF EXISTS aq;""" c.execute(remove_table_sql) create_table_sql = """ CREATE TABLE IF NOT EXISTS aq( id integer PRIMARY KEY, sensor_id integer, ts integer, pm1 integer, pm10 integer );""" c.execute(create_table_sql) except sqlite3.Error as e: print(e) conn = None database_name = 'air_quality.db' if os.path.exists(database_name): while True: answer = raw_input( "DB {} exists! Continue will erase all data. Continue? [y/n]: ".format(database_name)) if answer.lower() not in ('y', 'n'): print("Not an appropriate choice.") continue if answer.lower() == 'y': break else: exit() try: conn = create_connection(database_name) drop_then_create_table(conn) finally: if conn: conn.close()
true
dfd958a2a422e5a3cabc1c3a41e9a32a2dbb8242
Nelcyberth86/IntroProgramacion
/practico_1/9.2.py
578
4.15625
4
num1 = int(input("ingrese numero: ")) num2 = int(input("ingrese, numero: ")) suma = "suma" or "+" resta = "resta" or "-" multiplicacion = "multiplicacion" or "*" division= "division" or "/" operacion = str(input("operacion, que decea realizar: ")) if operacion== suma or "+": resultado= num2 + num1 print(resultado) elif operacion == resta or "-": resultado = num1 - num2 print(resultado) elif operacion == multiplicacion or "*": resultado = num1 *num2 print(resultado) elif operacion == division or "/": resultado = num1 / num2 print(resultado)
false
31a805a8387d66f06ecf741aaec458dc413f27f6
jm9176/Data_structures_practice
/If_Tree_is_BST.py
734
4.40625
4
''' To check if the given tree is a BST tree or not ''' # creating a class for the node class Node: def __init__(self, node = None): self.node = node self.left = None self.right = None # Function running a chek on the given tree def chk_tree(temp): if not temp: return if temp.left is not None and temp.right is not None: if temp.left.node > temp.node or temp.right.node < temp.node : return -1 chk_tree(temp.left) chk_tree(temp.right) # Tree input root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) if chk_tree(root) == -1: print('Tree not BST') else: print('Tree is BST')
true
a80a73379941066b0356763a25be654d7786db9a
jm9176/Data_structures_practice
/Finding_max_of_sub_arrays.py
503
4.3125
4
''' Finding the maximum value in each of the sub array of size k. If the given array is [10,5,2,7,8,7] then the resulting output should be [10,7,8,8]. ''' # this fnction will return the list of # max element of the sub array def max_sub(arr, k): max_sub_arr = [] for i in range(len(arr)-k+1): max_sub_arr.append(max(arr[i:i+k])) return max_sub_arr # Defining the input list arr =[10,5,-1,7,8,7] k = int(input("Enter the size of sub-arrays: ")) print(max_sub(arr, k))
true
d2d6b6221c9f0b6ce00befa87966ba9c55a9425c
jm9176/Data_structures_practice
/Finding_pair_with_given_sum.py
571
4.125
4
# finding a pair with a given sum def pair_check(arr, var_sum): for var in arr: if var_sum - var in arr: print "Match found" return var, var_sum - var else: print "Match not found" arr = [] try: for i in range(int(input("Enter the length of the list: "))): arr.append(int(input("Enter the elements in the list: "))) var_sum = int(input("Enter the sum that you want to find: ")) print pair_check(arr, var_sum) except: print "The input is not a number"
true
02d59a4c2fad30f306482a63ffa5966511543f88
jm9176/Data_structures_practice
/Finding_the_lowest_positive_missing_element.py
645
4.375
4
''' Find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. ''' # Function to find and add the lowest positive element # to the defined input def input_elem(arr): elem_search = 1 found = 0 while found == 0: if elem_search not in arr: arr.append(elem_search) found = 1 return elem_search, arr else: elem_search += 1 # Define the input arr = [3,4,-1,1,5,6] print(input_elem(arr))
true
c32b529aab468b5b36632d52080c9f0663d27f6c
saikiranshiva/assignmentwork2
/calculator.py
820
4.125
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: choice = input("Enter choice(1/2/3/4): ") if choice in ('1', '2', '3', '4'): n1 = float(input("Enter first number: ")) n2 = float(input("Enter second number: ")) if choice == '1': print(n1, "+", n2, "=", add(n1, n2)) elif choice == '2': print(n1, "-", n2, "=", subtract(n1, n2)) elif choice == '3': print(n1, "*", n2, "=", multiply(n1, n2)) elif choice == '4': print(n1, "/", n2, "=", divide(n1, n2)) break else: print("Invalid Input")
false
1b240c41de5a51243305a8d33f694fa835d2aba6
Merkasi/rpsls.
/rpsls.py
2,996
4.1875
4
""" 第一个小项目:Rock-paper-scissors-lizard-Spock 作者:杨敬升 日期:2020/11/15 """ import random def name_to_number(name): if name=='石头' : name=0 if name=='史波克' : name=1 if name=='纸' : name=2 if name=='蜥蜴' : name=3 if name=='剪刀' : name=4 return name def number_to_name(number): if number==0 : number='石头' if number==1 : number='史波克' if number==2 : number='纸' if number==3 : number='蜥蜴' if number==4 : number='剪刀' return number def rpsls(player_choice): y=random.randrange(0,4) player_choice=choice_name player_choice_number=name_to_number(player_choice) while player_choice_number==name_to_number('石头') : print('您出的是'+number_to_name(0)+','+'计算机出的是'+number_to_name(y)) if y==3 or y==4 : print('您赢了') if player_choice_number == y: print('您和计算机出的一样呢') if y==1 or y==2 : print('计算机赢了') break while player_choice_number==name_to_number('史波克') : print('您出的是' + number_to_name(1) +','+ '计算机出的是' + number_to_name(y)) if y==4 or y==0 : print('您赢了') if player_choice_number==y : print('您和计算机出的一样呢') if y== 2 or y==3 : print('计算机赢了') break while player_choice_number==name_to_number('纸') : print('您出的是' + number_to_name(2) +','+ '计算机出的是' + number_to_name(y)) if y==1 or y==0 : print('您赢了') if player_choice_number==y : print('您和计算机出的一样呢') if y==3 or y==4 : print('计算机赢了') break while player_choice_number==name_to_number('蜥蜴') : print('您出的是' + number_to_name(3) +','+ '计算机出的是' + number_to_name(y)) if y==1 or y==2 : print('您赢了') if player_choice_number==y : print('您和计算机出的一样呢') if y==0 or y==4 : print('计算机赢了') break while player_choice_number==name_to_number('剪刀') : print('您出的是' + number_to_name(4) +','+ '计算机出的是' + number_to_name(y)) if y==2 or y==3 : print('您赢了') if player_choice_number==y : print('您和计算机出的一样呢') if y==0 or y==1 : print('计算机赢了') break return player_choice_number print("欢迎使用RPSLS游戏") print("----------------") print("请输入您的选择:") choice_name=input() if choice_name != '石头' and choice_name !='剪刀' and choice_name !='纸' and choice_name !='蜥蜴' and choice_name !='史波克' : print('Error: No Correct Name') rpsls(choice_name)
false
69163cc318847e1c18b91c7c7c6203aee9e7365b
QUSEIT/django-drf-skel
/libs/utils.py
701
4.125
4
from decimal import Decimal import random import string def convert_weight_unit(from_, to, weight): """单位转换""" units = ['lb', 'oz', 'kg', 'g'] kg_2_dict = { 'oz': Decimal('35.2739619'), 'lb': Decimal('2.2046226'), 'g': Decimal(1000), 'kg': Decimal(1), } if from_ not in units or to not in units: raise Exception('Invalid Unit') if from_ == to: return weight return kg_2_dict.get(to) / kg_2_dict.get(from_) * weight def random_string(string_length=10): """Generate a random string of fixed length """ letters = string.ascii_letters return ''.join(random.choice(letters) for _ in range(string_length))
true
987b4ab8d7c7a262ece34dabdbdd182c087adc2c
kelseyoo14/oo-melons
/melons.py
2,009
4.28125
4
"""This file should have our order classes in it.""" class AbstractMelonOrder(object): """A melon order at UberMelon.""" # initializing class attributes that are default for all melons order shipped = False def __init__(self, species, qty, order_type, tax, country_code): """Initialize melon order attributes""" # bind user input to class attributes self.species = species self.qty = qty self.order_type = order_type self.tax = tax self.country_code = country_code # def get_total(self): """Calculate price.""" # calculate and return a total price given tax, qty, and price if self.species.lower() == "christmas melon": base_price = 5 * 1.5 else: base_price = 5 total = (1 + self.tax) * self.qty * base_price if order_type == 'international' and qty < 10: total += 3 return total else: return total def mark_shipped(self): """Set shipped to true.""" # mark order as shipped self.shipped = True class DomesticMelonOrder(AbstractMelonOrder): """A domestic (in the US) melon order.""" def __init__(self, species, qty): """Initialize melon order attributes""" # user super method to use superclass init on species and qty super(DomesticMelonOrder, self).__init__(species, qty, 'domestic', 0.08, None) class InternationalMelonOrder(AbstractMelonOrder): """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): """Initialize melon order attributes""" # user super method to use superclass init on species and qty super(InternationalMelonOrder, self).__init__(species, qty, 'international', 0.17, country_code) def get_country_code(self): """Return the country code.""" # return the value of country code return self.country_code
true
1c1a06d62faada3fbb4992a94b6fa909e07ae4fc
Thraegwaster/my-pi-projects
/old-rpi-files/test_count.py
327
4.125
4
# This is just a test def testcount(): myCount = raw_input("Enter your count: ") if myCount == '3': print("The number of thy counting") elif myCount == '4': print("Four shalt thou not count") elif myCount == '5': print("Five is right out") else: print("Thou shalt count to three, no more, no less.") testcount()
true
9efee6b49cc9b260986d5dbe7db8df7c48d7a1ea
Thraegwaster/my-pi-projects
/python3/chris/primefactorizor/divider.py
662
4.25
4
# Divider # Takes a number and a divisor as input, then counts how many times # the number goes into the divisor before a remainder is enocuntered. def divider(dividend, divisor): index = 0 # we don't want dividend to be changed by the subsequent calculation. quotient = dividend while quotient % divisor == 0: quotient = quotient / divisor index += 1 return index # main userdividend = int(input("Enter the dividend\n")) userdivisor = int(input("Enter the divisor\n")) answer = divider(userdividend, userdivisor) print("\nThere is a factor of", userdivisor, "^", answer, "in", userdividend, ".") input("\n\nPress the enter key to continue")
true
3cc7c35b40fef068a4cc6c697d0016c03a522807
endurance11/number-game
/gtn.py
659
4.25
4
print(''' Welcome If you want to beat the Computer, guess the right number between 0 and 9 Remember you have only 3 guesses ''') name=input("What's your name? ") import random number=random.randint(0,9) guess_count=0 guess_limit=3 while guess_count<guess_limit: guess=int(input("@@@@>>> GUESS : ")) guess_count+=1 if guess == number : print(' Congratulations ' + name + ' you guessed the right number :)' ) break elif guess < number : print("Number too low!") elif guess > number : print("Number too high!") else : print(' Sorry ' + name + ' you failed ): ') num=str(number) print(' The number I was thinking was ' + num )
true
c7d4837df914029e8595e16fdab3589c2bbc2a5f
furkanbakkal/Machine-Learning-with-Tensorflow
/draw.py
1,064
4.1875
4
# draw square in Python Turtle from os import name import turtle import time def boxing(start_point_x, start_point_y,length,label): t = turtle.Turtle() turtle.title("Squid Game Challange") wn = turtle.Screen() wn.setup(1200, 800) wn.bgpic("test.gif") t.hideturtle() t.penup() #don't d_raw when turtle moves t.goto(start_point_x-600, start_point_y-400) t.showturtle() #make the turtle visible t.pendown() # drawing first side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing second side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing third side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree # drawing fourth side t.forward(length) # Forward turtle by s units t.right(90) # Turn turtle by 90 degree t.write(label,font=("Verdana",10)) time.sleep(3)
false
aba13551e40c413eff1db924393773a94a607eeb
giangtranml/Project-Euler
/P1-10/p4.py
884
4.21875
4
""" Name: Largest palindrome product. A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. -------------------------------------------------------------- A palindromic number is a number that its original and reversed is equal. """ def reversed_num(num): r_num = 0 while num//10 > 0: r_num += num % 10 r_num *= 10 num //= 10 return r_num def is_palindrome(num): reversed = reversed_num(num) if num == reversed: return True return False l_ = [] for i in range(100, 1000): for j in range(100, 1000): k = i * j if is_palindrome(k): l_.append(k) res = max(l_) print(res)
true
83300e85e3fad296133b01f26bd276208f18cc06
modibhargav/python11amweek
/nummax.py
241
4.125
4
x=int(input("Enter Num1 :")) y=int(input("Enter Num2 :")) z=int(input("Enter Num3 :")) if x>y: if x>z: print("%d is max"%x) else: print("%d is max"%z) elif y>z: print("%d is max"%y) else: print("%d is max"%z)
false
09b9bdaecc3aecd8a4562096bc262df90135ca1c
hi-yee/MyPython
/py_14 字符串.py
1,427
4.1875
4
""" 字符串 1、 字符串和元组一样,一旦定下来就不能更改,如果需要更改只能 str = 'i love my family' str =str[:6] + '插入的字符串' + str[6:] 比较操作符,逻辑操作符,成员关系操作符的操作与列表/元组是一样的 """ # 2、 通过拼接就字符串的各部分得到新的字符串,并不是真正意义上的改变了原字符串,原来的那个‘家伙’ # 还在,只是将变量指向了新的字符串(旧的字符串一旦失去了变量的引用,就是会Python的垃圾回收机制释放掉) str = 'i love my family' str = str[:6] print(str) # 3、当需要访问字符串的其中一个字符的时候,只需要用索引列表或者元组的方法来索引字符串即可 """ 字符串和元组一样,一旦定下来就不能更改,如果需要更改只能, 通过拼接的方式来进行改变了 str = 'i love my family' str =str[:6] + '插入的字符串' + str[6:] """ str1 = 'i love my family' str1 =str[:6] + '我最棒' + str1[6:] print(str1) # 字符串的常见奇葩方法 # 1、capitalize() 方法, 把字符串的第一个字符爱称大写 str2 = 'i love you' print(str2.capitalize()) # 2、casefold() 方法, 把字符串的第一个字符爱称大写 str2 = 'I love You' print(str2.casefold()) # 3、casefold() 方法, 把字符串的第一个字符爱称大写 str2 = 'I love You' print(str2.casefold())
false
31132c770344013588f88d6178ebca95df3d869c
viltsu123/basic_python_practice
/data_analysis_learning/MatplotlibExample.py
1,653
4.28125
4
import numpy as np import matplotlib.pyplot as plt print("** Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command do you use if you aren't using the jupyter notebook?**") print("plt.show()") print() x = np.arange(0, 100) y = x*2 z = x**2 ''' ## Exercise 1 ** Follow along with these steps: ** * ** Create a figure object called fig using plt.figure() ** * ** Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax. ** * ** Plot (x,y) on that axes and set the labels and titles to match the plot below:** fig = plt.figure() ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax.plot(x,y,'blue') ax.set_xlabel("x") ax.set_ylabel("y") ax.set_title("title") ''' ''' ## Exercise 2 ** Create a figure object and put two axes on it, ax1 and ax2. Located at [0,0,1,1] and [0.2,0.5,.2,.2] respectively.** fig2 = plt.figure() ax1 = fig2.add_axes([0.1,0.1,0.8,0.8]) ax2 = fig2.add_axes([0.3,0.5,.2,.2]) ax1.plot(x,z,'r') ax1.set_ylabel('Z') ax1.set_xlabel('X') ax2.plot(x,y,'r') ax2.set_title('zoom') ax2.set_ylabel('Y') ax2.set_xlabel('X') plt.show() ''' ''' #Exercise 3 fig2 = plt.figure() ax1 = fig2.add_axes([0.1,0.1,0.8,0.8]) ax2 = fig2.add_axes([0.3,0.5,.2,.2]) ax1.plot(x,z,'r') ax1.set_ylabel('Z') ax1.set_xlabel('X') ax2.plot(x,y,'r') ax2.set_title('zoom') ax2.set_ylabel('Y') ax2.set_xlabel('X') ax2.set_xlim(20,22) ax2.set_ylim(30,50) plt.tight_layout() plt.show() ''' #Exercise 4 fig, axes = plt.subplots(1,2, figsize=(8,4)) axes[0].plot(x,y,'red',linewidth=0.5,linestyle="--") axes[1].plot(x,z,'green',linewidth=2,linestyle=":") plt.tight_layout() plt.show()
true
94ee5e375cb64e6b6786a95f1e62148b1e45b0ef
Nishi216/PYTHON-CODES
/NUMPY/numpy8.py
1,107
4.34375
4
''' Numpy sorting ''' #Different ways of sorting import numpy as np array = np.array([[10,2,4],[5,9,1],[3,2,8]]) print('The array is : \n',array) print('The sorted array is : \n',np.sort(array,axis=None)) print('Sorting array along the rows : \n',np.sort(array,axis=1)) print('Sorting array along the columns : \n',np.sort(array,axis=0)) print('Sorting array along the last axis: \n',np.sort(array,axis=-1)) print() print() array1 = np.array([9,3,4,2,8,7,1,6,9]) print('The array is : \n',array1) indexes = np.argsort(array1) #this will sort the array and then will provide the indexes for the sorted array sorted_array = np.zeros(len(indexes),dtype=int) for ele in range(len(indexes)): sorted_array[ele]=array1[indexes[ele]] print("Sorted array is : ",sorted_array) print() array1 = np.array([9,3,4,2,8,7,1,6,9]) print('The array is : \n',array1) array2 = np.array([5,4,9,2,3,7,0,9,8]) print('The array is : \n',array2) for (i,j) in zip(array1,array2): print(i,' ',j) result = np.lexsort((array2,array1)) print('Sorted indexes are : ',result)
true
99d11a07744936b5fc9f64e07c2237d23c45236e
Nishi216/PYTHON-CODES
/NUMPY/numpy10.py
614
4.25
4
''' Creating your own data type and using it to create the array ''' import numpy as np dt = np.dtype(np.int64) print('The data type is: ',dt) print() dt = np.dtype([('age',np.int32)]) print('The data type defined is: ',dt) print('The data type of age is: ',dt['age']) print() dt = np.dtype([('name','S20'),('age',np.int32),('cgpa','f4')]) student = np.array([('abc',18,8.65),('ngh',20,9.31),('kjh',19,9.00)],dtype=dt) print('The data type corresponding to the names are: ',dt) print('The array is: ',student) print('Name of the students : ') for names in student['name']: print(names)
true
7760126769cbf27c81971da7354bc33c57fd3085
Nishi216/PYTHON-CODES
/DICTIONARY/dict1.py
1,527
4.34375
4
#for creating a dictionary dict = {'prog_lang1':'python','prog_lang2':'java','prog_lang3':'c++','prog_lang4':'javascript'} print('The dictionary created is: ') print(dict) print() #to get only the keys from dictionary print('The keys are: ',dict.keys()) #this will give in list form for val in dict.keys(): #this is for accessing individually print(val,end=' ') print() print() #to get only the values from dictionary print('The values are: ',dict.values()) #this will give in list form for val in dict.values(): #this is for accessing individually print(val,end=' ') print() print() #for updating an existing dictionary - to update an old value or to add a new value print('old dictionary: ',dict) dict['prog_lang5']='PHP' dict['prog_lang6']='HTML' print('updated dictionary is: ',dict) print() print() #to change the value of any existing key dict['prog_lang5']='CSS' print('New update: ') print(dict) print() #dict.items() - returns the key-value pairs in the form of tuples inside the list print('The key value pairs are: ') print(dict.items()) print() print('For getting access to key value pair tuples individually: ') for val in dict.items(): print(val) print() print('For getting the keys and values separately: ') for key,value in dict.items(): print('Key is :',key,end=' ') print('Value is:',value) ''' SO HERE THE DICTIONARY METHODS USED ARE - .keys() .values() .items()'''
true
42b3891d2911ea5f8f42f74f223f6120ee4c255a
caglagul/example-prime-1
/isprimex.py
555
4.1875
4
def isprime(x): counter = 0 for i in range(2, x): if x % i == 0: counter = counter + 1 if counter == 0: print("True! It is a prime number.") else: print("False! It is not a prime number.") while True: x = int(input("Enter a number:")) if x>0: if x % 2 == 0: print("This number is an even number.") else: print("This number is an odd number.") if x>1: isprime(x) break else: print("Please enter a number higher than 1.")
true
05d25aedab2b5f0916042557f2635ba79a9d9257
ShunKaiZhang/LeetCode
/search_insert_position.py
776
4.1875
4
# python3 # Given a sorted array and a target value, return the index if the target is found. # If not, return the index where it would be if it were inserted in order. # You may assume no duplicates in the array. # Here are few examples. # [1,3,5,6], 5 → 2 # [1,3,5,6], 2 → 1 # [1,3,5,6], 7 → 4 # [1,3,5,6], 0 → 0 # My solution class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ out = len(nums) for i in range(len(nums)): if nums[i] > target: out = i break elif nums[i] == target: out = i break return out
true
8a2027785914b52545d65b1332d2502ced8e3b5d
ShunKaiZhang/LeetCode
/flatten_binary_tree_to_linked_list.py
1,491
4.40625
4
# python3 # Given a binary tree, flatten it to a linked list in-place. # For example, # Given # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ # 6 # My solution # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ def search(node): if node is None: return None left_leaf = search(node.left) right_leaf = search(node.right) if node.left is not None and node.right is not None: cur = node.right node.right = node.left node.left = None left_leaf.right = cur return right_leaf elif node.left is not None: node.right = node.left node.left = None return left_leaf elif node.right is not None: return right_leaf else: return node search(root) return
true
900d468157c948c32bc959f9462e861e765a9d85
ShunKaiZhang/LeetCode
/reverse_words_in_a_string_III.py
484
4.21875
4
# python3 # Given a string, you need to reverse the order of # characters in each word within a sentence while still preserving whitespace and initial word order. # Example: # Input: "Let's take LeetCode contest" # Output: "s'teL ekat edoCteeL tsetnoc" # My solution class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ s_words = s.split() return ' '.join(it[::-1] for it in s_words)
true
72fa161b02264138f4c7ec6b2e12f31413c23baa
ShunKaiZhang/LeetCode
/binary_search_tree_iterator.py
1,317
4.1875
4
# python3 # Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. # Calling next() will return the next smallest number in the BST. # Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. # My solution # Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.root = root nodes = [self.root] self.val = [] while nodes: cur = nodes.pop(0) if cur is None: continue self.val.append(cur.val) nodes.append(cur.left) nodes.append(cur.right) self.val.sort() def hasNext(self): """ :rtype: bool """ return len(self.val) != 0 def next(self): """ :rtype: int """ return self.val.pop(0) # Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next())
true
36574b984807772900de46bab6121a6932936d7c
MaxDol8888/CodeClubProjects
/quizshowGame.py
736
4.125
4
print('======= WELCOME TO GABY''S QUIZSHOW! =======') score = 0 #ask first question print("What city is this years Olympics in?") answer = input() if answer == "Rio" or answer == "rio": print("Correct!") score += 1 print("Your current score is:", score) else: print("Your current score is:", score) print() #ask second question print("What is the national bird of New Zealand?") answer = input() if answer == "kiwi" or answer == "Kiwi": print("Correct!") score += 1 print("Your current score is:", score) else: print("Your current score is:", score) print() #add more questions here #print final score and goodbye message print() print("Thank you for playing! Your final score was", score)
true
410308838ec85af96605487ecbcb139688446a83
christos-dimizas/Python-for-Data-Science-and-Machine-Learning
/pythonDataVisualization/Seaborn/regressionPlot.py
2,810
4.1875
4
# ------------------------------------------------------------ # # ------- Regression Plots ------- # # Seaborn has many built-in capabilities for regression plots, # however we won't really discuss regression until the machine # learning section of the course, so we will only cover the # lmplot() function for now. # lmplot allows you to display linear models, but it also # conveniently allows you to split up those plots based off # of features, as well as coloring the hue based off of features. # ------------------------------------------------------------ # import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset('tips') # ------------------------------------------------------------ # # lmplot() # ------------------------------------------------------------ # sns.lmplot(x='total_bill', y='tip', data=tips) plt.show() sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex') plt.show() sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', palette='coolwarm') plt.show() # ------------------------------------------------------------ # # Working with Markers # ------------------------------------------------------------ # # lmplot kwargs get passed through to regplot which is a more general form of lmplot(). regplot has a scatter_kws # parameter that gets passed to plt.scatter. So you want to set the s parameter in that dictionary, which corresponds # (a bit confusingly) to the squared markersize. In other words you end up passing a dictionary with the base # matplotlib arguments, in this case, s for size of a scatter plot. In general, you probably won't remember this # off the top of your head, but instead reference the documentation. # http://matplotlib.org/api/markers_api.html# http:/ sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', palette='coolwarm', markers=['o', 'v'], scatter_kws={'s': 100}) plt.show() # ------------------------------------------------------------ # # Using a Grid # ------------------------------------------------------------ # # We can add more variable separation through columns and rows with the use of a grid. Just indicate this # with the col or row arguments sns.lmplot(x='total_bill', y='tip', data=tips, col='sex') plt.show() sns.lmplot(x="total_bill", y="tip", row="sex", col="time", data=tips) plt.show() sns.lmplot(x='total_bill', y='tip', data=tips, col='day', hue='sex', palette='coolwarm') plt.show() # ------------------------------------------------------------ # # Aspect and Size # ------------------------------------------------------------ # # Seaborn figures can have their size and aspect ratio adjusted with the size and aspect parameters sns.lmplot(x='total_bill', y='tip', data=tips, col='day', hue='sex', palette='coolwarm', aspect=0.6, size=8) plt.show()
true
bf25de63b2eab4bc13a97a2ebcc8f61232c3bbe1
jaugustomachado/Curso-Next-Python
/Aula 2 - operadores lógicos e estrutura condicional/bhaskara.py
1,175
4.1875
4
#Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. # O programa deverá pedir os valores de a, b e c e fazer as consistências, # informando ao usuário nas seguintes situações: # a- Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau # e o programa não deve fazer pedir os demais valores, sendo encerrado; #b- Se o delta calculado for negativo, a equação não possui raizes reais. # Informe ao usuário e encerre o programa; #c- Se o delta calculado for igual a zero a equação possui apenas uma raiz real; #informe-a ao usuário; #d- Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário; a = float(input('digite o valor de a: ')) if a == 0: print('programa encerrado') else: b = float(input('digite o valor de b: ')) c = float(input('digite o valor de c: ')) d=(b**2)-(4*a*c) if d<0: print('não existem raízes reais') elif d == 0 : print('existe apenas uma raiz real:', -b/(2*a)) else: print('existem duas raízes reais: ', (-b+(d**(1/2)))/(2*a) , 'e', (-b-(d**(1/2)))/(2*a) )
false
a0878140048d20558fa8917718542a0ee465c567
TerryLun/Code-Playground
/generate_magic_squares.py
727
4.125
4
import copy import magic_square import rotate_matrix import flip_matrix def generate_magic_squares_three_by_three(): magic_squares = [] m = magic_square.solve(3) magic_squares.append(copy.deepcopy(m)) for _ in range(3): rotate_matrix.rotate_matrix(m) magic_squares.append(copy.deepcopy(m)) flip_matrix.flip_matrix_horizontal(m) magic_squares.append(copy.deepcopy(m)) for _ in range(3): rotate_matrix.rotate_matrix(m) magic_squares.append(copy.deepcopy(m)) return magic_squares def main(): sq = generate_magic_squares_three_by_three() for i in sq: for r in i: print(*r) print() if __name__ == '__main__': main()
false
bbf8b5718568d7b9ef2974b393b8ce361eeefe1f
TerryLun/Code-Playground
/Leetcode Problems/lc1389e.py
680
4.28125
4
""" 1389. Create Target Array in the Given Order Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. """ def createTargetArray(nums, index): target = [] for i, j in zip(index, nums): if i >= len(target): target.append(j) else: target.insert(i, j) return target
true
9313918ae338b6950bc3df26b30b83962403e82a
syvwlch/MIT-OpenCourseWare---6.00
/ps1b.py
1,291
4.34375
4
# Problem Set 1 # Name: Mathieu Glachant # Collaborators: None # Time Spent: 0:30 # # Gathering user inputs initial_balance=float(raw_input('Enter the outstanding balance' ' on your credit card: ')) annual_interest_rate=float(raw_input('Enter the annual credit card interest rate' ' as a decimal: ')) # Initialize some variables minimum_monthly_payment=0.0 outstanding_balance=initial_balance # Iterating until the minimum payment is sufficient to pay off the debt while outstanding_balance>0: minimum_monthly_payment=minimum_monthly_payment+10.0 outstanding_balance=initial_balance month=0 # Iterating each month while it's less than a year AND the debt is not paid while month<12 and outstanding_balance>0: month+=1 # Calculating the month interest_paid=round(annual_interest_rate/12*outstanding_balance, 2) principal_paid=minimum_monthly_payment-interest_paid outstanding_balance=outstanding_balance-principal_paid # Calculate and print the results over the year print 'RESULT' print 'Monthly payment to pay off debt in one year: '+str( minimum_monthly_payment) print 'Number of months needed: '+str(month) print 'Remaining balance: $'+str(outstanding_balance)
true
185a14e652863682964e15764408405f45459dc9
harshilvadsara/Getting-started-with-python-Coursera
/Assignment 5.2.py
391
4.15625
4
largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try : numb = int(num) except : print('Invalid input') if smallest is None : smallest = numb elif numb < smallest : smallest = numb elif numb > largest : largest = numb print("Maximum is", largest) print("Minimum is", smallest) #for output 7,2,bob,10,4 and after that done it will execute.
true
ce952e7599a131cf66e9079a68505a09438b2b77
MarcBanuls/Freecodecamp_Projects
/Data_Analysis_With_Python_Projects/Mean_Variance_Standard_Deviation_Calculator/mean_var_std.py
1,431
4.1875
4
# Import Numpy import numpy as np def calculate(lst): # In case the list has the expected length, it will be reshaped to a 3x3 matrix if len(lst) == 9: reshaped = np.reshape(lst, (3,3)) # In case the list has a different length, a ValueError is raised else: raise ValueError("List must contain nine numbers.") # Here in each key it is used a numpy function changing the axis to calculate through rows, columns and flattened (without # adding an axis parameter). Also the result of the numpy array is converted to list to follow the guidelines # of the README.md calculations = {"mean": [np.mean(reshaped, axis = 0).tolist(), np.mean(reshaped, axis = 1).tolist(), np.mean(reshaped).tolist()], "variance": [np.var(reshaped, axis = 0).tolist(), np.var(reshaped, axis = 1).tolist(), np.var(reshaped).tolist()], "standard deviation": [np.std(reshaped, axis = 0).tolist(), np.std(reshaped, axis = 1).tolist(), np.std(reshaped).tolist()], "max": [np.max(reshaped, axis = 0).tolist(), np.max(reshaped, axis = 1).tolist(), np.max(reshaped).tolist()], "min": [np.min(reshaped, axis = 0).tolist(), np.min(reshaped, axis = 1).tolist(), np.min(reshaped).tolist()], "sum": [np.sum(reshaped, axis = 0).tolist(), np.sum(reshaped, axis = 1).tolist(), np.sum(reshaped).tolist()]} return calculations
true
62e00457178016c2402e9e6413b2a6c83505d33d
mohammedvaghjipurwala/Learning-Python-
/Palindrome.py
414
4.625
5
################################################# # #Ask the user for a string and print out whether this string is a palindrome or not. # ################################################# Str = input("Enter a string: ").lower() ### Reverse the string Rev_str = Str[::-1] #condition if palindrome if Str == Rev_str: print ("""%s is a palindrome"""%Str) else: print ("""%s is not a palindrome"""%Str)
true
f6847b87e545e85958b4b887a495a89394863a25
mohammedvaghjipurwala/Learning-Python-
/DrawBoard.py
1,094
4.5
4
####################################################################### ''' Time for some fake graphics! Let’s say we want to draw game boards that look like this: --- --- --- | | | | --- --- --- | | | | --- --- --- | | | | --- --- --- This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more). Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s print statement. ''' ####################################################################### def DrawBoard(rows,cols): dash = " ---" pipe = "| " for i in range(0,rows): if i % 2 == 0: print (dash * (cols)) else: print (pipe * (cols + 1)) def UserInput(): print ("Enter the size of the board:: \n") rows = (int(input("Enter the number of rows: ")) * 2) + 1 cols = int(input("Enter the number of cols: ")) return (rows,cols) if __name__ == "__main__": row, col = UserInput() DrawBoard(row, col)
true
594fbb3446570ebd9253162ee6a1f89828a8a49d
Srajan-Jaiswal/Python-Programming
/amstrong_number.py
213
4.1875
4
a=int(input("Enter the number: ")) num=a ans=0 while(num>0): d = num%10 ans+=pow(d,3) num = int(num/10) if(ans==a): print("It's an amstrong number.") else: print("It's not an amstrong number")
true
bf27462cadd90e8001922e3fdf5ef602671f2aba
Jcvita/CS1
/Week1/hexes.py
1,201
4.125
4
""" Joseph Vita 8/26/19 CS-141 Herring hexes.py uses turtle to draw 2 large hexagons that are comprised of smaller hexagons. The second hexagon is offset by the same distance as one side of a hexagon. """ import turtle def makeHex(): """generates a hexagon by moving forward 50 pixels 6 times with a difference of 60 degrees each""" turtle.forward(50) turtle.left(60) turtle.forward(50) turtle.left(60) turtle.forward(50) turtle.left(60) turtle.forward(50) turtle.left(60) turtle.forward(50) turtle.left(60) turtle.forward(50) turtle.left(60) def makeBigHex(): """Uses makeHex() 6 times at 60 degree intervals to make a larger hexagon out of smaller hexagons""" makeHex() turtle.forward(50) turtle.right(60) makeHex() turtle.forward(50) turtle.right(60) makeHex() turtle.forward(50) turtle.right(60) makeHex() turtle.forward(50) turtle.right(60) makeHex() turtle.forward(50) turtle.right(60) makeHex() turtle.forward(50) turtle.right(60) makeHex() makeBigHex() turtle.right(60) makeBigHex() turtle.done()
false
95d45a6991967fecc5356eefce42740706d50514
Jcvita/CS1
/Week7/biggiesort.py
1,608
4.25
4
""" Joseph Vita CSCI-141 Herring 10/9/19 biggiesort.py reads numbers from a file, puts them in a list and sorts them using the BiggieSort algorithm """ def main(): # file = open(input("Sort which file? ")) file = open('C:\\Users\\jcvit\\Documents\\CS1\\Week7\\nums') lines = file.readlines() tempstr = '' for line in lines: tempstr += line lst = tempstr.split('\n')[:-1] for x in range(len(lst)): lst[x] = int(lst[x]) print("unsorted:") print(lst) print("sorted") print(biggie_sort(lst)) def biggie_sort(lst): """ sorts a list by iterating through the list and swapping the greatest integer with the next last place for each element in the list precondition: lst must be all integers :param lst: :return: """ for x in range(len(lst) - 1, 1, -1): lst = swap(lst, x, find_max_from(lst, 0, x)) return lst def swap(lst, first, second): """ takes in a list and swaps the position of the two inputted indexes precondition:first and second :param lst: :param first: :param second: :return: """ temp = lst[first] lst[first] = lst[second] lst[second] = temp return lst def find_max_from(lst, lo, hi): """ takes in a list and returns the nth maximum integer value inside the list precondition:lst contains all strings, ints or floats """ max = int(lst[0]) for x in range(len(lst)): if int(lst[lo]) < int(lst[x]) < int(lst[hi]): max = int(lst[x]) return max if __name__ == '__main__': main()
true
8141a45c20d0dc7cc3cb51f2faf361bfbeb7e1b1
Jcvita/CS1
/Week4/zigzag.py
1,728
4.3125
4
""" Joseph Vita Program creates a colored zig zag stair shape using recursion """ import turtle def main(): turtle.speed(0) depth = int(input("How many layers do you want? ")) zigzag(100, depth, 0) turtle.done() def draw_l(size, back, count): """ param: size precondition: turtle facing direction that L should be (north or south) precondition: turtle up or down postcondition: turtle facing starting direction postcondition: turtle up """ if count % 2 == 1: turtle.left(45) if back == 1: turtle.forward(size / 2) turtle.right(90) turtle.forward(size) else: turtle.backward(size) turtle.left(90) turtle.backward(size / 2) if count % 2 == 1: turtle.right(45) turtle.penup() def zigzag(size, depth, count): """ param: size param: depth precondition: turtle facing east precondition: pen down postcondition: turtle facing east postcondition: pen up """ turtle.penup() if depth < 1: pass elif depth >= 1: turtle.left(90) turtle.pendown() if count % 2 == 0: turtle.pencolor("red") else: turtle.pencolor("green") draw_l(size, 1, count) zigzag(size / 2, depth - 1, count + 1) turtle.penup() draw_l(size, 0, count) turtle.right(180) turtle.pendown() if count % 2 == 0: turtle.pencolor("red") else: turtle.pencolor("green") draw_l(size, 1, count) zigzag(size / 2, depth - 1, count + 1) turtle.penup draw_l(size, 0, count) turtle.left(90) print(count) main()
true
086243d392736aeb25fec6784922fde63c5b0873
anushalihala/SOC2018
/hackathons/week2/trienode.py
1,703
4.375
4
#!/usr/bin/env python3 class TrieNode(object): """ This class represents a node in a trie """ def __init__(self, text: str): """ Constructor: initialize a trie node with a given text string :param text: text string at this trie node """ self.__text = text self.__children = {} self.__ends_word = False def get_ends_word(self): """ Does this node end a word? :return: True if this node ends a word, False otherwise """ return self.__ends_word def set_ends_word(self, ends_word: bool): """ Set whether or not this node ends a word in a trie :param ends_word: value determining whether this node ends a word :return: None """ self.__ends_word = ends_word def get_child(self, char: str): """ Return the child trie node that is found when you follow the link from the given character :param char: the character in the key :return: the trie node the given character links to, or None if that link is not in trie """ if char in self.__children.keys(): return self.__children[char] else: return None def insert(self, char: str): """ Insert a character at this trie node :param char: the character to be inserted :return: the newly created trie node, or None if the character is already in the trie """ if char not in self.__children: next_node = TrieNode(self.__text + char) self.__children[char] = next_node return next_node else: return None
true
bb3e5d77d477bc3f690b548406bacab3e31ac902
Zumh/PythonUdemyLessons
/PythonLessons/FibonnaciNumber.py
2,962
4.28125
4
# This is Naive algorithm for calculating nth term of Fibonnaci Sequence # This is the big-O notation formula, T(n) = 3 + T (n-1) + T(n-2). # Here we create the program to caclulate fibonnaci number # First we assign two number in dynamic array or datastructer which is 0 and 1 # Then we add the number using recursive function def fibRecursive(number): if number <= 1: return number return fibRecursive(number-1) + fibRecursive(number-2) number = int(input("Input Max fib number")) number = fibRecursive(number) print (number) # Here we have O(Log(n)) algorithm that fibbonnaci sequence # we can use formula that derive from matrix # If the number is EVEN then we can put k = n/2 # If n is odd, we can put k = ( n + 1 )/2 # we find the nth Fibbonacci number # in with O(Log n) arithmatic operations MAX =1000 # Create an array for allocating memory fNumber = [0]* MAX # Returns n'th fibonnaci number using table f[] def fib(number) : # Base cases if(number == 0 ) : return 0 if(number == 1 or number ==2): fNumber[number] = 1 return (fNumber[number]) # If fib(n) is already computed if (fNumber[number]): return fNumber[number] if(number & 1): k = (number + 1) //2 else: k = number // 2 # Applying aove formula [Note value number&1 is 1] # if number is odd, else 0. if((number & 1)) : fNumber[number] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) else: fNumber[number] = (2*fib(k-1) + fib(k)) * fib(k) return fNumber[number] # Driver code number = 9 print(fib(number)) # This code is from Kikita Tiwari. # The efficient of this program is O(n) # Efficient Algorithm # using Dynmaic Programming def FibEfCalculate(number): # Taking 1st two fibonacci numbers as 0 and 1 FibArray = [0,1] # Here we append number on the list on the array while len(FibArray) < number + 1: FibArray.append(0) # here we return the number if it less than or equal to 1. if number <= 1: return number else: # Here we check for list value contain 0 or not # if it contain 0 then we call the recursive method to reduce the size of the number # This allow us to collect first number if FibArray[number - 1] == 0: FibArray[number - 1] = FibEfCalculate(number - 1) # Here we compare the value from list number # Simlar to above number we call the recursive method to reduce number in size # This allow us to collect second number if FibArray[number - 2] == 0: FibArray[number - 2] = FibEfCalculate(number - 2) # Then we add first and second number to appropriate index number FibArray[number] = FibArray[number - 2] + FibArray[number - 1] return FibArray[number] # Driver code print(FibEfCalculate(9)) #https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
true
642fe00d7ebcade604de37a6c2e67c80e0773ff4
ss2576/Interview
/Lesson_2/task_1.py
1,191
4.1875
4
""" Проверить механизм наследования в Python. Для этого создать два класса. Первый — родительский (ItemDiscount), должен содержать статическую информацию о товаре: название и цену. Второй — дочерний (ItemDiscountReport), должен содержать функцию (get_parent_data), отвечающую за отображение информации о товаре в одной строке. Проверить работу программы. """ class ItemDiscount: def __init__(self, name, price): self.name = name self.price = price class ItemDiscountReport(ItemDiscount): def get_parent_data(self): return f'Наименование товара: {self.name}. Цена товара: {self.price} рублей.' def main(): name = input('Введите наименование товара:\n') price = int(input('Введите цену товара\n')) item_rep = ItemDiscountReport(name, price) print(item_rep.get_parent_data()) if __name__ == '__main__': main()
false
8db434a7005d40751cdf84db5a06917fe8e8b305
ss2576/Interview
/Lesson_1/task_3.py
1,944
4.25
4
""" Задание 3. Разработать генератор случайных чисел. В функцию передавать начальное и конечное число генерации (нуль необходимо исключить). Заполнить этими данными список и словарь. Ключи словаря должны создаваться по шаблону: “elem_<номер_элемента>”. Вывести содержимое созданных списка и словаря. Пример: ( [18, 22, 21, 23, 18, 21, 19, 16, 18, 8], {'elem_18': 18, 'elem_22': 22, 'elem_21': 21, 'elem_23': 23, 'elem_19': 19, 'elem_16': 16, 'elem_8': 8} ) """ import random def random_number_generator(start, end, number_of_digits): result = [] if start > end: start, end = end, start for digit in range(number_of_digits): number = random.randint(start, end) if (number == 0) or (number in result): continue result.append(number) sort_result = sorted(result) return sort_result def creating_dictionary(sort_result): dictionary = {} for number in range(len(sort_result)): key = f'elem_{sort_result[number]}' dictionary[key] = sort_result[number] return dictionary def main(): try: start = int(input('Введите начальное число:\n')) end = int(input('Введите конечное число: \n')) number_of_digits = int(input('Введите количество случайных цифр: \n')) sort_result = random_number_generator(start, end, number_of_digits) dictionary = creating_dictionary(sort_result) print(sort_result) print(dictionary) except ValueError: print('Необходимо ввести натуральное число!') main() if __name__ == '__main__': main()
false
cfd2cc81cc9e04c64b16f0a01c17c9c01da54143
quanlidavid/top50pythoninterviewquestions
/Q49.py
386
4.15625
4
# 49. What is the output of following code in Python? # >>>name = 'John Smith' # print name[:5]+name[5:] """ John Smith This is an example of Slicing. Since we are slicing at the same index, the first name[:5] gives the substring name upto 5th location excluding 5th location. The name[:5] gives the rest of the substring of name from the 5th location. So we get the full name as output. """
true
b3ae13465e597c61dc648a0d91bfb527fdd10ba1
Daymond-Blair/picking-up-python
/55_oo_inheritance_basics_overriding methods_and_str_special_method_default_values_for_methods.py
1,995
4.125
4
# 55 56 57 OO Inheritance Basics, Overriding Methods, Overriding __str__ special_method_default_values_for_methods # Python conventions: # 2. Class names should use CapWords convention. # 3. Variables should use thisStyle convention. # 4. Always use self for the first argument to instance methods. # 5. When writing method prototypes, use the pass keyword as placeholder # 6. Multiline comments should use the # symbol for each line. Don't use docstring. class Automobile: ''' -> Automobile base / parent class''' model_year = "2010" def start(self): print("Automobile is starting.....skrrt skrrt skrrt") def turn_off(self): '''-> Shut off Automobile...''' print("Click, sput, sput.......Vehicle is now off.") class Truck(Automobile): '''-> Truck is a type of automobile. Inherits from Automobile and has all methods''' def __init__(self, year=None): if year is None: self.year = 2019 else: self.year = year def __str__(self, year=None): return "2019 Truck sold by StudioWeb." def dumpLoad(self, load=None): if load is None: print("Truck has nothing to dump!!!!") else: print("Truck is dumping " + str(load) + " plumbusses!!!") print("Yeah straight dumpin dem loads!!!") def start(self): # overriding method print("Truck is starting.......puta puta puta boom!!!!!") def turn_off(self): # overriding method print("......Truck cut off without any noise!") def truckYear(self): print("This truck was built in " + str(self.year)) myTruck = Truck("2022") myTruck.truckYear() myTruck.start() myTruck.turn_off() print(myTruck) # normally prints location in RAM but with __str__ it returns something instead anotherTruck = Truck() anotherTruck.truckYear() emptyDumpTruck = Truck() emptyDumpTruck.dumpLoad() fullDumpTruck = Truck() fullDumpTruck.dumpLoad(15000) print(type(anotherTruck))
true
237598368af3a1fb9f7ef1058419b1ff5cbc8e71
Daymond-Blair/picking-up-python
/48_49_tkinter_gui.py
1,098
4.125
4
# 48 49 tkinter gui from tkinter import * # MODULE/PACKAGE that contains many many classes - * means import ALL OF THESE CLASSES FOR USE root = Tk() # instance of Class Tk() from MODULE TKINTER aka OBJECT!!! pythonCourseLogo = PhotoImage(file="giphy-downsized.gif") # photo image function grabs image file rightLabel = Label(root, image=pythonCourseLogo) rightLabel.pack(side="right") myText = ''' With tkinter, YOU CAN ONLY USE GIF IMAGES. There are other, more powerful Python packages that allow you to use other image types.''' myOtherText = "LOOK AT DAT PUG!!!" # call title method (from class Tk()) - title of python window at very top root.title("Our amazing Python window!!") leftLabel = Label(root, justify=RIGHT, padx=10, text=myOtherText).pack(side="left") '''w = Label(root, text = "Hello Tkinter - one of Python's tools for creating GUIs!") # instance of Class Label() aka Label OBJECT!!! w.pack() # call pack method (from class Label()) - packs label text into window''' print("launching window ...") root.mainloop() # mainloop() keeps code running until window is closed
true
146fc2c4c3f535a6dc977ba40f0bd6110b582f1e
SuperCXW/byte_of_python_demos
/return.py
534
4.21875
4
# def maxium(x, y): # # return # # if x > y: # # x == 1 # # elif x == y: # # x == 1 # # # return 'The numbers are equal' # # else: # # x == 1 # # # return y # '''ghfvjhgjhk # ''' # print(1) # # # # print(maxium(3, 1)) # print(maxium(3, 4).__doc__) def print_max(x, y): """This is the function docstring.""" x = int(x) y = int(y) if x > y: print(x) else: print(y) # print_max(1, 5) print(print_max.__doc__) help(print)
false
ced51dfc8fe013921040fb178e64d9edae42ee3e
dvishnu/py_basics
/classes.py
1,851
4.59375
5
# basics on python classes # __init_() is always executed when a class is being initiated class student: def __init__(self,name,age): self.name = name # self reference self.age = age print("Hi My name is {} and i am {} years old".format(name,age)) s1 = student("Vishnu", 28) print("My age is {}".format(s1.age)) print("My name is {}".format(s1.name)) # classes with methods # # class emp: # def __init__(self,empid,dept): # self.empid = empid # self.dept = dept # def dept_name(self): # if self.dept == '10': # print("dept name is Sales") # elif self.dept == '20': # print("dept name is Accounts") # else: # print("emp belongs to unknown department") # e1 = emp(1,10) # # # # calling the methods in the class from the object created # e1.dept_name() class student1: def __init__(self,name,section,school): self.name = name self.section = section self.school = school def std_details(self): print("student name from student details method is {} ".format(self.name)) s2 = student1("robo","A","loyolla") s2.std_details() # Inheritance classes class car: def __init__(self,car_name,model): self.car_name = car_name self.model = model def car_details(self): print("Car name is {} and model is {}".format(self.car_name,self.model)) c = car("hyundai","nios") # calling the car details method c.car_details() Now defining Child class class maruti(car): def __init__(self,car_name,model): # init fun overrides the init def from the parent class super().__init__(car_name, model) self.car_color = "blue" print("Inherited props i.e car name is {} and model is {}".format(car_name,model)) c2 = maruti("mar","baleno") print(c2.car_color)
true
3e8922eb850931e0ef6b64ca092e497e11f2d668
NCPlayz/screen
/screen/utils/math.py
792
4.125
4
import math def distance(*pairs): """ Calculates euclidean distance. Parameters ---------- *pairs: Tuple[:class:`int`, :class:`int`] An iterable of pairs to compare. Returns ------- :class:`float` The euclidean distance. """ return math.sqrt(sum((p[0] - p[1]) ** 2 for p in pairs)) def interpolate(v1, v2, p): """ Calculates linear interpolation. Parameters ---------- v1: :class:`float` The start value. v2: :class:`float` The end value. p: :class:`float` The point along the line in the range ``[0, 1]``. Returns ------- :class:`float` The interpolated value. """ return (1 - p) * v1 + p * v2 __all__ = [ "distance", "interpolate", ]
true
2dea1231a318718f498a34f7515905ac2ea10241
Cryafonic/ConsoleCalculator
/Calculator.py
707
4.125
4
def subtract(): return num1 - num2 def multiply(): return num1 * num2 def devide(): return num1 / num2 def add(): return num1 + num2 stop = "quit" stop += input("Type quit to exit:") for x in stop: if x == stop: break else: num1 = int(input('Choose a number: ')) num2 = int(input('Choose another number: ')) choice = str(input('Type: subtract, multiply, devide or add: ')) if choice == 'subtract' or "-": print(subtract()) elif choice == 'multiply' or "*": print(multiply()) elif choice == 'devide' or "/": print(devide()) elif choice == "add" or "+": print(add())
false
312a93a4d26a775412c1be13455ec503f6fc1f16
dbhoite/LearnPython
/DataStructures.py
2,199
4.25
4
def findFirstDuplicate(numlist): """Returns the first duplicate number in a given list, None if no duplicate Arguments: numlist {list[integer]} -- input list of integers Returns: integer -- first duplicate number """ # set operations numset = set() for num in numlist: if not num in numset: numset.add(num) else: return num return None def mostFrequentNum(numlist): """Returns the most frequent number in the list Arguments: numlist {list[integer]} -- input list of integers Returns: integer -- most frequent number """ # dictionary operations numdict = {} for num in numlist: numdict[num] = numdict.get(num, 0) + 1 maxval = None maxkey = None for k, v in numdict.items(): if maxkey is None or v > maxval: maxkey = k maxval = v return maxkey def listOperations(numlist): """Random list operations Arguments: numlist {list[integer]} -- input list of integers """ # list operations print("original list = {}".format(numlist)) count = len(numlist) print("number of elements = {}".format(count)) uniqlist = set(numlist) print("unique elements = {}".format(uniqlist)) sortedList = sorted(numlist) print("sorted list = {}".format(sortedList)) print("lowest 3 = {}".format(sortedList[:3])) print("highest 3 = {}".format(sortedList[-3:])) def min_max(numlist): """Returns the smallest and the largest number from a numeric list Arguments: numlist {integer} -- input list of integers Returns: (integer, integer) -- a tuple containing (min,max) numbers from the list """ maxNum = max(numlist) minNum = min(numlist) return minNum, maxNum numlist = [5, 3, 4, 4, 5, 1, 2, 5] listOperations(numlist) dupeNum = findFirstDuplicate(numlist) print("first duplicate number = {}".format(dupeNum)) freqNum = mostFrequentNum(numlist) print("most frequent number = {}".format(freqNum)) min, max = min_max(numlist) print("max number in list = {}".format(max)) print("min number in list = {}".format(min))
true
d1962c1a9a3a1bbb97a7ab9bd7567f4638230674
dsabalete/binutils
/lpthw/ex15.py
617
4.15625
4
# -*- coding: utf-8 -*- # http://learnpythonthehardway.org/book/ex15.html # import feature argv from package sys from sys import argv # extract values packed in argv script, filename = argv # open file which name is in filename var txt = open(filename) # Nice output print "Here's your file %r:" % filename # File content output print txt.read() txt.close() # Nice output again #print "Type the filename again:" # Asking the name of the file to the user #file_again = raw_input("> ") # Open the file named by user #txt_again = open(file_again) # File content output #print txt_again.read() #txt_again.close()
true
0b374c001ff08647d818d6f3f3f7b88719b0384a
scumroe/aws-dump
/03DataTypes/pythag.py
1,416
4.28125
4
import math def get_sides(a=0, b=0, c=0, o=1): if o == 1: c = round(math.sqrt(a**2+b**2), 2) print("The hypotenuse (side c )is:\nThe square root of: %s^2 + %s^2 = %s" % (a , b, c)) elif o == 2: a = round(math.sqrt(c**2-b**2), 2) print("Side a is:\n The square root of %s^2 - %s^2 = %s" % (c, b, a)) print(a) elif o == 3: b = round(math.sqrt(c**2-a**2), 2) print("Side b is:\n The square root of %s^2 - %s^2 = %s" % (c, a, b)) else: print("No can do.") return def Menu(): menu = ['Pythagoras','1. Find side c','2. Find side a', '3. Find side b'] for menu in menu: print(menu) option = int(input("Choose an option:")) if option == 1: side_a = int(input("Enter side a: ")) side_b = int(input("Enter side b: ")) get_sides(side_a, side_b, 1) elif option == 2: side_b = int(input("Enter side b: ")) side_c = int(input("Enter side c: ")) get_sides(0, side_b, side_c, 2) elif option == 3: side_a = int(input("Enter side a: ")) side_c = int(input("Enter side c: ")) get_sides(side_a, side_c, 3) else: print("Bad choice.") return def main(): try: Menu() except ValueError: print("Bad value.") if __name__ == "__main__": main()
false
29ea7e14f93cd6270cdc8d491d11f5c23f93d6cb
temaari/PyCode
/Ch2/variables.py
203
4.125
4
f = 0 # print(f) # f = "abc" # print(f) # print("this is a string" + str(123)) def someFunction(): global f f="def" print(f) someFunction() print(f) del f print(f) # Global name 'f' is not defined
false
f1d72706672bca03e29324ee53d0218eaaabe5aa
likendero/SGE
/python/ejercicios3JavierGonzalezRives/calculos.py
1,936
4.15625
4
from math import log10 # metodo que sirver para introducir dos numeros def introducir_numeros(): # bloque try que controla los posibles errores que hallan sucedido try: numero1 = int(input("introduzca el primer numero: ")) numero2 = int(input("introduzca el segundo numero: ")) except ValueError: print("se ha introducido un valor distinto a un numero") return 0,0 return numero1,numero2 #funcion que suma dos numeros pasados por teclado def sumar(): # introduccion de los numeros numero1,numero2 = introducir_numeros() # realizacion de la suma print("suma {} + {} = {}".format(numero1,numero2,(numero1 + numero2))) # caso de restar def resta(): # introduccion de los numeros numero1,numero2 = introducir_numeros() # realizacion de la suma print("resta {} - {} = {}".format(numero1,numero2,(numero1 - numero2))) # caso de dividir # el segundo numero no puede ser 0 def division(): # introduccion de los numeros numero1,numero2 = introducir_numeros() # realizacion de la suma if numero2 != 0: print("division {} / {} = {}".format(numero1,numero2,(numero1 / numero2))) else: print("error, division por 0") # caso de multiplicacion def multiplicar(): # introduccion de los numeros numero1,numero2 = introducir_numeros() # realizacion de la suma print("multiplicacion {} * {} = {}".format(numero1,numero2,(numero1 * numero2))) # caso de exponente def exponente(): # introducir numeros numero1,numero2 = introducir_numeros() # salida de la potencia print("potencia {} ^ {} = {} ".format(numero1,numero2,(numero1**numero2))) # caso de logaritmo def logaritmo(): try: numero1 = input("introduce un numero") except ValueError: print("solo se pueden introducir numeros") # salida de la potencia print("logaritmo base 10 de {} es {}".format(numero1,log10(2)))
false
cf7cab61cb8c1c793f29736da9cf655d086fe804
Ziaulhaq11/pythontim
/overloading.py
562
4.125
4
class Point(): def __init__(self, x =0, y=0): self.x = x self.y = y self.coords = (self.x, self.y) def move(self,x,y): self.x += x self.y += y return x,y def __add__(self, p): return Point(self.x+ p.x,self.y + p.y) def __sub__(self,p): return Point(self.x - p.x,self.y - p.y) def __mul__(self,p): return self.x * p.x+self.y * p.y def __str__(self): return "(" + str(self.x) + ',' + str(self.y) + ')' p1 = Point(3,4) p2 = Point(2,5) p3 = Point(1,3) p4 = Point(0,1) p5 = p1+p2 p6 = p4-p1 p7 = p2*p3 print(p1.move) print(p5,p6,p7)
false
85a41b62ec3f79d1243a852f3f88fa1a0900d328
pbchandra/cryptography
/cryptography/Python/caesar_crack.py
869
4.3125
4
#we need the alphabet because we convert letters into numerical values to be able to use #mathematical operations (note we encrypt the spaces as well) ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' #cracking the caesar encryption algorithm with brute-force def caesar_crack(cipher_text): #we try all the possible key values so the size of the ALPHABET for key in range(len(ALPHABET)): #reinitialize this to be an empty string plain_text = '' #we just have to make a simple caesar decryption for c in cipher_text: index = ALPHABET.find(c) index = (index-key)%len(ALPHABET) plain_text = plain_text + ALPHABET[index] #print the actual decrypted string with the given key print('With key %s, the result is: %s'%(key,plain_text)) if __name__ == "__main__": encrypted = 'VJKUBKUBCBOGUUCIG' caesar_crack(encrypted)
true
a43ebcb53a12fcd8d75c04cbea2197586d5660c7
suchismitarout/tt
/pallin.py
247
4.125
4
def pallindrome_num(num): num2 = "" for i in str(num): num2 = i + num2 if int(num2) == int(num): print("it is a pallindrome number") else: print("it is not a pallindrome number") n = 150 pallindrome_num(n)
false
c6130096fc3a581323001dcea1f2c9fb696adab7
piyushPathak309/100-Days-of-Python-Coding
/Area of a Circle.py
489
4.46875
4
# Write a Python program that finds the area of a circle from the value of the diameter d. # # The value of d should be provided by the user. # # The area of a circle is equal to pi*(radius)^2. The radius is the value of the diameter divided by 2. # # Round the value of the area to two decimal places. # # You may assume that the value of the diameter will be non-negative integer. import math as m R = float(input("Enter a Radius :")) Area = (m.pi*R**2) print(Area)
true