blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
21f2bdac93a5c5e47e27bb2017448539be3930b7
Lindisfarne-RB/GUI-L3-tutorial
/Lesson7.py
1,689
4.15625
4
'''Adding a multiline label using \n We will be building the GUI for our banking app in stages during these first 10 lessons, and we'll add the functionality in the second 10 lessons. We now have a welcome message label and an image label, but this part of the GUI will need one more label to show us our account balances. So let's get one more bit of practice adding a label with a textvariable. This time, instead of using wraplength we're going to split the label onto 2 lines using \n, which is the newline character.''' '''Under the relevant comment, create a StringVar() called account_details. Set account_details to: Savings: $500 - 25% of $2000 goal \nTotal balance: $500 Create a label called details_label and set the textvariable to account_details. Pack the details label into the GUI. ''' from tkinter import * root = Tk() root.title("Goal Tracker") # Create and set the message text variable message_text = StringVar() message_text.set("Welcome! You can deposit or withdraw money and see your progress towards your goals.") # Create and pack the message label message_label = Label(root, textvariable=message_text, wraplength=250, justify="center") message_label.pack() # Create the PhotoImage and label to hold it neutral_image = PhotoImage(file="call.png") image_label = Label(root, image=neutral_image, justify="center") image_label.pack() # Create and set the account details variable account_details = StringVar() account_details.set("Savings: $500 - 25% of $2000 goal \nTotal balance: $500") # Create the details label and pack it into the GUI details_label = Label(root, textvariable=account_details) details_label.pack() # Run the mainloop root.mainloop()
true
e35c5a2d3cf0b9b35f0527d1c1468331aa67d760
Lindisfarne-RB/GUI-L3-tutorial
/Lesson47OOPS.py
1,296
4.71875
5
'''11.2 Giving a class attributes What do we mean when we say classes group related data and functions? Well, if we think of a user of, say, a gaming or social networking site, there are a bunch of pieces of information we would need to store for all users such as: Username Actual name Date of birth Password And so on. You might recognise these as things we might usually use variables for. By putting them in a class, we can create an object for each user, and then we can store their own details without having to rewrite all of the code for every user. Variables like this inside a class are called attributes. They are set the same way as normal variables, but are accessed by using dot notation: print(bob.name) CREATE Inside the class, delete the pass keyword. Add an attribute to the class called code_name and set it to D-Bug. Add another attribute for real_name and set it to your own name or a name of your choice. Underneath the line where avenger1 is instantiated, print avenger1.code_name. Click RUN to see the output. Now below that, print out the real name too. ''' class Avenger: code_name = "D-Bug" real_name = "RB" # Create an instance of the Avenger class avenger1 = Avenger() # Print out some attributes print(avenger1.code_name) print(avenger1.real_name)
true
690d49ab54f48b05a48068f51cac3655765c34ae
wahmed555/flask-Django
/app.py
919
4.15625
4
# importing Flask (class) from flask.py (file) , so we get all methods and attributes of Flask class from flask import Flask #instantiating : creating an instance namely 'app' from class Flask, having a function Flask same as Flask class name # this special case is called as constructor because when ever function(method) name= class name, # argument passed __name__ is a global variable what ever name your file has will be printed # now all the methods and attributes of flask will be in instance app app = Flask(__name__) # now we are making route of our instance 'app' by placing @ before our instance name # and then useing '.route' method with argument('/') showing current directory @app.route('/') # every route has a function , here index function will return hello world def index(): return "Hello Wasim" #app.run is method to run server /run this function app.run(debug=True)
true
8cdada9f62c75dbadaccb41b4f555f8cc869e9fe
GainAw/CIS104
/Assignment1/H1P1.py
304
4.15625
4
print("What is you first name: ") first_name = input() print("What is you last name: ") last_name = input() print("What is you age name: ") age = int(input()) dage = age*7 print("Hello {} {}, nice to meet you! You might be {} but in dog years you are {}.".format(first_name, last_name, age, dage))
true
81db9bbc574c44aee44831e11b5e329a9e9d0292
kaiyiyu/DSA1002
/Practicals/P02/fibonacci.py
606
4.28125
4
# Find the nth term in the Fibonacci sequence def calc_fibonacci(n): if type(n) != int: raise TypeError('This function only accepts integers as input.') elif n < 0: raise ValueError('This function does not accept negative integers.') print('The %dth term in the Fibonacci sequence is %d.' % (n, _calc_fibonacci(n))) def _calc_fibonacci(n): fib_value = 0 if (n == 0): fib_value = 0 elif (n == 1): fib_value = 1 else: fib_value = _calc_fibonacci(n - 1) + _calc_fibonacci(n - 2) return fib_value calc_fibonacci(17)
true
aff92ddac2c36650355d37a7ab09555f95040117
nairitya03/Python
/Src/Octal To binary.py
434
4.1875
4
while(True): octal = input("Enter any number in Octal Format: ") #Takes an Octal Input print("Enter 'x' for exit.") #Press X to Exit Loop if octal == 'x': #Condition To Break exit() else: decimal =int(octal,8) #input Of Decimal Number print(octal,"in Binary = ",bin(decimal)) #output of decimal Number
true
f28aa0ef58ff0116b987bebd461a1f7c773e92c9
CarlVs96/Curso-Python
/Curso Python/2 Condicionales/Video 11 - Condicionales ELSE/Condicionales_else.py
775
4.125
4
print("Verificación de acceso") edadUsuario = int(input("Introduce tu edad: ")) if edadUsuario < 18: print("No puedes acceder") elif edadUsuario > 100: print("Edad incorrecta") else: print("Puedes acceder") print ("El programa ha finalizado") print("---------------------------------------------") print("Verificación de notas") notaUsuario = float(input("Introduce tu nota: ")) if notaUsuario >= 0 and notaUsuario < 5: print("Insuficiente") elif notaUsuario >= 5 and notaUsuario < 6: print("Suficiente") elif notaUsuario >= 6 and notaUsuario < 7: print("Bien") elif notaUsuario >= 7 and notaUsuario < 9: print("Notable") elif notaUsuario >= 9 and notaUsuario <= 10: print("Sobresaliente") else: print("Nota incorrecta") print ("El programa ha finalizado")
false
600bca01cdd95caed48fca8cd55bbedc9360faae
WHJR-G8/G8-C7_SAA_1
/Sol_SAA_1.py
487
4.3125
4
import turtle n = int(input('Enter the value for number of sides of polygon: ')) side = int(input('Enter the length of side of polygon: ')) color1 = input('Enter the color polygon 1: ') color2 = input('Enter the color polygon 2: ') def draw_polygon(): for variable in range(0, n): turtle.forward(side) turtle.right(360 / n) turtle.pencolor(color1) draw_polygon() turtle.penup() turtle.goto(80, 40) turtle.pendown() turtle.pencolor(color2) draw_polygon()
true
62f2e8896d000f9ba89f278ff2dd973ca48c560c
JustinClark2k3/BeginnerPythonProjects
/calculator.py
827
4.3125
4
# Input definitions def Calc(): print("Enter num") num1 = input("Enter first number\n") num1 = int(num1) op = input("Enter operation (+, -, /, ^, * or x)\n") num3 = input("Enter second number\n") num3 = int(num3) # Calculations if op == "-": # Subtraction both = num1-num3 if op == "+": # Addition both = num1+num3 if op == "*" or "x": # Multiplication both = num1*num3 if op == "/": # Division if num1 > 0 and num3 > 0: both = num1/num3 else: print ("Cannot divide by zero") exit() if op == "^": # Powers both = num1**num3 # Output output = both print("Your anwser is " + str(output))
true
c4d5e9d61e2b16fa4246a76df06fd36383e3961a
ishangurung1/python-
/factorial.py
219
4.15625
4
a=int(input("enter the number")) f=1 i=1 while i<=a: f=f*i i=i+1 print("factorial in ascending order"+str(f)) f=1 while a>=1: f=f*a a=a-1 print("factorial in decending order"+str(f))
false
b31dc121707cda54b6e80c32fa2d1a02111246c7
MaximJoinedGit/Python-basics
/lesson_1/homework_1.6.py
1,166
4.1875
4
""" 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. """ a = input('Какой результат у спортсмена в первый день? ') b = input('Какого результата он должен достичь? ') i = 1 if a.isdigit() and b.isdigit(): a, b = int(a), int(b) while a < b: a *= 1.1 i += 1 print(f'Если спортсмен будет прибавлять каждый день по 10%, то он достигнет результата на {i}-й день')
false
7492a32c7b510f2620aa5240318ccdf4cfd06da6
MaximJoinedGit/Python-basics
/lesson_5/homework_5.2.py
534
4.53125
5
""" 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ line = 0 with open('homework_5.2.txt', 'r', encoding='utf-8') as r: for n in r: words = n.split() line += 1 print(f'Строка №{line} содержит {len(words)} слов.') print(f'Всего строк в файле: {line}')
false
9c3cfd744be18540876733aad7301586562fbcc3
zxj16152/PythonExercise
/Demal2HexConversion.py
503
4.15625
4
def decimalToHex(decimalValue): hex="" while decimalValue!=0: hexValue=decimalValue%16 hex=toHexChar(hexValue)+hex decimalValue=decimalValue//16 return hex def toHexChar(hexValue): if 0<=hexValue<=9: return chr(hexValue+ord('0')) else: return chr(hexValue-10+ord('A')) def main(): decimalValue=eval(input("Enter a decimal number :")) print("The hex number for decimal",decimalValue," is ",decimalToHex(decimalValue)) main()
false
cc5a05688541c7ce7ae7c876ae773153757e0d61
DRC-AI/code-wars
/ten_min_walk.py
1,144
4.125
4
#You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise. def is_valid_walk(walk): x = 0 y = 0 for steps in walk: if 'n' in steps: y += 1 if 's' in steps: y -= 1 if 'e' in steps: x += 1 if 'w' in steps: x -= 1 return True if len(walk) == 10 and x + y == 0 else False print(is_valid_walk(['n','s','n','s','n','s','n','s','n','s']))
true
747402d068e463615624867b6a0aabb1b7904c6a
ruhsane/Technical-Interview-Practice
/SPD2.4/assignment5/middleOfLL.py
1,494
4.25
4
''' Given a singly-linked list, find the middle value in the list. Example: If the given linked list is A → B → C → D → E, return C. Assumptions: The length (n) is odd so the linked list has a definite middle. ''' # Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list. # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, items=None): self.head = None # Append given items if items is not None: for item in items: self.push(item) def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Function to get the middle of the linked list def printMiddle(self): slow_pointer = self.head fast_pointer = self.head if self.head is not None: while (fast_pointer is not None and fast_pointer.next is not None): fast_pointer = fast_pointer.next.next slow_pointer = slow_pointer.next print("The middle element is: ", slow_pointer.data) # Driver code list1 = LinkedList([5, 4, 3, 2, 1]) list1.printMiddle() list2 = LinkedList(["A", "B", "C", "D", "E"]) list2.printMiddle()
true
58a2bebe3bb5b750e3cd700b1009829567ae192a
knmarvel/backend-nested-brackets
/nested.py
1,609
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This program checks a text filefor invalid brackets. If an invalid bracket exists, the program returns "Yes" + the index of the invalid bracket. If not, the program returns "No". """ import sys if sys.version_info[0] < 3: raise Exception("Need Python 3") __author__ = "github.com/knmarvel" def is_nested(line): index = 0 brac_types = { "parasts": ["(*", "*)"], "parens": ["(", ")"], "squares": ["[", "]"], "curlies": ["{", "}"], "alligators": ["<", ">"] } answer = "YES" bracs_used = [] while line: if line[:2] == "(*" or line[:2] == "*)": token = line[:2] else: token = line[0] for brac in brac_types: if token == brac_types[brac][0]: bracs_used.append(token) if token == brac_types[brac][1]: if bracs_used[-1] != brac_types[brac][0]: answer = "NO " + str(index + 1) token = line else: bracs_used.pop() line = line[len(token):] index += 1 if len(bracs_used) > 0: answer = "NO " + str(index) return (answer) def main(args): line_count = 0 answer = "" with open("input.txt", "r") as f: for line in f: answer += is_nested(line) + "\n" line_count += 1 with open("output.txt", "w") as f: f.write(answer) with open("output.txt", "r") as f: print(f.read()) if __name__ == '__main__': main(sys.argv[1:])
true
7ed85c42ebfce9acc5032edf95a8090e1a074024
rahulsingh9878/Daily_Assignments
/assignment-2.py
859
4.34375
4
# Q.1- Print anything you want on screen. print("Welcome in the world of python") # Q.2- Join two strings using '+'. # E.g.-"Acad"+"View” print("Rahul "+"Singh") #Q.3- Take the input of 3 variables x, y and z . Print their values on screen. x = int(input('Enter a number')) y = float(input('Enter a float number')) z = input('Enter your name') print('Value of x = ',x) print('Value of y = ',y) print('Value of z = ',z) # Q.4- Print “Let’s get started” on screen. print("Let’s get started") # Q.5- Print the following values using placeholders. # s=”Acadview” # course=”Python” # fees=5000 s="Acadview" course="Python" fees=5000 print('%s %s %d'%(s,course,fees)) #Q.6- Find the area of circle '''pi = 3.14 Take radius as input from user Print the area of circle : ''' pi = 3.14 rad = int(input('Enter Radius ')) print(pi*rad*rad)
true
ccb3b4697a1f0eaf37d67070ec7a363b546311ac
Madhu-Kumar-S/Python_Basics
/Stringprograms/remove ith char.py
358
4.25
4
# Python3 program for removing i-th # indexed character from a string # Removes character at index i def remove(string, i): for j in range(len(string)): if j == i: string = string.replace(string[i], "", 1) return string string = "geeksFORgeeks" # Remove nth index element i = 5 # Print the new string print(remove(string, i))
true
6a326949c90c3f33117bca7b77516f2bb26377b8
Madhu-Kumar-S/Python_Basics
/Data_Structures/Sorting Techniques/SelectionSort.py
517
4.25
4
# Selection sort using array array import array print("................Selection Sort...............") elements = [int(x) for x in input("enter the elements:").split()] arr = array.array('i', elements) print("array is:", *elements) def ss_sort(a): n = len(a) for i in range(n): min_pos = i for j in range(i+1, n): if a[min_pos] > a[j]: min_pos = j a[i], a[min_pos] = a[min_pos], a[i] return a result = ss_sort(arr) print("Sorted array: ", *result)
true
8f6ebe9737ebb043ef3a603ac5505bba3a10add5
Madhu-Kumar-S/Python_Basics
/Array programs/monotonic array.py
543
4.34375
4
# Python Program to check if given array is Monotonic from array import * print("Method 1") def isMonotonic(A): return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or all(A[i] >= A[i + 1] for i in range(len(A) - 1))) A = array('i', [6, 5, 4, 4]) print("monotonic condition of an given array is {}".format(isMonotonic(A))) print("Method 2") c1 = [] c2 = [] for i in range(len(A)-1): c1.append(A[i] >= A[i + 1]) c2.append(A[i] <= A[i + 1]) print("monotonic condition of an given array is {}".format(all(c1) or all(c2)))
false
8ed9f676ae845bac6d1d8def22ef1c2a89ecd2b2
Madhu-Kumar-S/Python_Basics
/List/positive_negtive no.py
974
4.125
4
# Python program to print positive and negative numbers in a list def p_n(l): p = [] n = [] for i in l: if i > 0: p.append(i) elif i < 0: n.append(i) return p, n lst = eval(input("enter a list:")) print("positive and negative numbers in a list") p1, n1 = p_n(lst) print("positive no's in list are:") for i in p1: print(i, end=' ') print() print("negative no's in list are:") for i in n1: print(i, end=' ') print("\n.........................................................") print("positive and negative numbers in a range") start = int(input("enter starting no of the range:")) end = int(input("enter ending no of the range:")) p2 = [] n2 = [] for i in range(start,end+1): if i > 0: p2.append(i) elif i < 0: n2.append(i) print("positive no's in range are:") for i in p2: print(i, end=' ') print() print("negative no's in range are:") for i in n2: print(i, end=' ')
false
44a661e4e8435a22abfedb47e9a200d3700aeeef
Madhu-Kumar-S/Python_Basics
/Basic Programs/find fib1.py
667
4.3125
4
# Python Program for How to check if a given number is Fibonacci number? import math # A utility function that returns true if x is perfect square def isPerfectSquare(x): s = int(math.sqrt(x)) return s * s == x # Returns true if n is a Fibinacci Number, else false def isFibonacci(n): # n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both # is a perferct square return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4) # A utility function to test above functions for i in range(1, 11): if (isFibonacci(i) == True): print(i, "is a Fibonacci Number") else: print(i, "is a not Fibonacci Number ")
true
291447f16f9249f39cdfd515b27de4654ecc2dba
Madhu-Kumar-S/Python_Basics
/Matrix Programs/add_sub_matrix.py
899
4.25
4
# Python program to add and sub two Matrices from numpy import* r1, c1 = [int(x) for x in input("enter no of rows and columns of 1st matrix:").split()] str1 = input("enter matrix elements:\n") a = reshape(matrix(str1), (r1, c1)) print(a) r2, c2 = [int(x) for x in input("enter no of rows and columns of 2nd matrix:").split()] str2 = input("enter matrix elements:\n") b = reshape(matrix(str2), (r2, c2)) print(b) print() if (r1 == r2) and (c1 == c2): print("addition of two matrices using operator:") c = a + b print(c) print("subtraction of two matrices using operator:") d = a - b print(d) print("addition of two matrices using add() method:") print(add(a, b)) print("subtraction of two matrices using subtract() method:") print(subtract(a, b)) else: print("rows and coloumns of both the arrays should be equal for adding two matrices")
true
40f8f3ce548fca6594bcafcc2085507e6ca9a405
Madhu-Kumar-S/Python_Basics
/Stringprograms/check bin.py
295
4.25
4
# Python | Check if a given string is binary string or not s = input("enter a string:") t = {'0','1'} t1 = [] for i in s: if i in t: t1.append(True) else: t1.append(False) if all(t1): print("given string is binary") else: print("given string is not binary")
false
dfd27a0c5854139013c5d9216052ec8dd7d5d757
Madhu-Kumar-S/Python_Basics
/Stringprograms/accept vowel string.py
299
4.3125
4
# Python program to accept the strings which contains all vowels s = input("enter a string:") s = s.lower() if ('a' and 'e' and 'i' and 'o' and 'u') in s: print("your string is accepted as it contains vowels!") else: print("your string not is accepted as it does not contains vowels!")
true
1874986db113312590190cb4dc36bde48d737e3d
Madhu-Kumar-S/Python_Basics
/Stringprograms/find substring.py
957
4.40625
4
# Python | Check if a Substring is Present in a Given String import re main_string = input("enter a main string:") sub_string = input("enter a sub string:") print("method 1") if sub_string in main_string: print("{:s} is found in {:s}".format(sub_string, main_string)) else: print("{:s} is not found in {:s}".format(sub_string, main_string)) print("method 2") if re.search(sub_string, main_string): print("{:s} is found in {:s}".format(sub_string, main_string)) else: print("{:s} is not found in {:s}".format(sub_string, main_string)) print("method 3") if main_string.count(sub_string) > 0: print("{:s} is found in {:s}".format(sub_string, main_string)) else: print("{:s} is not found in {:s}".format(sub_string, main_string)) print("method 4") if main_string.find(sub_string) != -1 : print("{:s} is found in {:s}".format(sub_string, main_string)) else: print("{:s} is not found in {:s}".format(sub_string, main_string))
false
928a22773fe1d9d543e8f3bbeb114e2a24f53220
Madhu-Kumar-S/Python_Basics
/Tuple/add tuple_list.py
246
4.28125
4
# Python – Adding Tuple to List and vice – versa # tuple to list l = [1, 2, 3] t = (4, 5) res =l + list(t) print(res) # another way using assignment operator l += t print(l) # list to tuple tup = tuple(list((1, 2)) + [3, 4, 5]) print(tup)
false
b242964977ae33a2628bfa66bedb1ddf48f8a37b
Madhu-Kumar-S/Python_Basics
/Basic Programs/fib_recursion.py
441
4.3125
4
# Python Program for n-th Fibonacci number using Recursion & memoization from functools import lru_cache #least recently used cache @lru_cache(maxsize=1000) # memoization concept def fibonacci(n): if n == 1: return 0 elif n == 2: return 1 elif n > 2: return fibonacci(n - 1) + fibonacci(n - 2) no = int(input("enter upto how many terms:")) for i in range(1, no + 1): print(i, ":", fibonacci(i))
false
db340c3a019329188a70357f12bc5fdf0c58370a
Madhu-Kumar-S/Python_Basics
/OOPS/classes and objects/c8.py
819
4.59375
5
# python program on inner classes class Person: def __init__(self, name): self.name = name # self.dob = self.DOB() --creating inner class object def display(self): print("Dear {} !".format(self.name)) # self.dob.display() --calling inner class instance method class DOB: def __init__(self, dd, mm, yr): self.dd = dd self.mm = mm self.yr = yr def display(self): print("your DOB is {}/{}/{}".format(self.dd, self.mm, self.yr)) p = Person("Kalki") p.display() # way 1 -- creating object to inner class and calling its instance method dob = Person.DOB(18, 2, 2000) dob.display() # way 2 # db = p.dob --creating inner class object outside the main class # db.display() --calling inner class instance method
false
62ece557569054f42db592a006ffcb25254cd021
Madhu-Kumar-S/Python_Basics
/List/reverse.py
280
4.34375
4
# Python | Reversing a List def rev(l): print("method 1 using reverse function:") l.reverse() print(l) l.reverse() print("method 2 using slicing") print(l[::-1]) lst = [1, 2, 3, 4, 5] print("before reversing") print(lst) print("after reversing") rev(lst)
true
a48c406c53026cddbc9c0af9628bced72ad91a7e
thephong45/student-practices
/15_Nguyen_Tu_Giang/bai-1.3.py
250
4.25
4
# Modify the previous program such that only the users Alice and Bob are greeted with their names. print('What is your name?') value = input() if value == 'Alice' or value == 'Bob': print('Hello,', value) else: print("Hello guest!")
true
a24bdd84e876af58a8c9dc7ec9b4ff4e463367c0
michalfoc/python
/python/ex13.2.2.py
750
4.15625
4
# Ex13.2 from sys import argv script, car_make, car_model = argv #note, that argument script DOES NOT HAVE TO be printed out or even used. print("Ordered car make is: ", car_make) print(f"Unfortunately, {car_model} is currently unavailable.") car_model_alt = input("Would you like to choose a different model?") # going a bit ahead, we ask user to input alternative argument, which is tested in if statement and depending on user input, it gives appropriate answer if car_model_alt == 'S60' or car_model_alt == 'S80' or car_model_alt == 'XC60': print(f"We are happy to confirm that {car_model_alt} is currently in stock and can be modified to your liking before order") else: print(f"Unfortunately, {car_model_alt} is also unavailable.")
true
4c5fa22d0b458711e63a690e0fe0dbcb10df7b19
michalfoc/python
/python/ex12.py
309
4.25
4
# Ex12 PROMPTING PEOPLE # compresing previous exercise # declare some variables age = input("How old are you?") height = input("How tall are you?") weight = input("How much do you weigh?") # print out a string using f-string command print(f"So, you are {age} years old, {height} tall and {weight} heavy.")
true
5bc64cc362d13bb9dc749edddfd6b693b167af96
JimWeisman/PRG105
/7.1 Rainfall Statistics.py
882
4.21875
4
"""jim weisman spring 2019 prg 105""" print("This program will calculate total rainfall and average monthly rainfall for a period of years.") years = int(input("How many years would you like to collect data for? ")) total_months = 0 total_rain = 0 for current_year in range(years): print("Year number " + str(current_year + 1)) for current_month in ['January', 'February', 'March', "April", 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']: monthly_rainfall = float(input("How much rain fell in the month of " + str(current_month) + ": ")) total_months += 1 total_rain += monthly_rainfall average_rain = total_rain / total_months print("Total amount of rainfall was: " + format(total_rain, ".2f") + " inches.") print("Average monthly rainfall was: " + format(average_rain, ".2f") + " inches.")
true
9fbf035522ee4e93aab567e5aec8fe7d76a9a34e
ashrithathmaram/Python
/primes_between_inputs.py
1,102
4.15625
4
print "Enter any two whole numbers to find all prime numbers between them" repeat = True while repeat: y_or_n_repeat = True try: n = int(raw_input("Starting Number: ")) end = int(raw_input("Ending Number: ")) if n > end: print "Your first number should be smaller than your second number" else: no_prime = True while n <= end: no_factors = True for factor in range(2, n): y = float(n)/factor if y == int(y): no_factors = False break if no_factors and n > 1: print n no_prime = False n += 1 if no_prime: print "There are no prime numbers between your two inputs" except ValueError: print "Please enter a valid number" while y_or_n_repeat: ans = str(raw_input("Restart? Enter yes or no: ")) if ans == "yes": repeat = True y_or_n_repeat = False else: if ans == "no": repeat = False y_or_n_repeat = False print "Goodbye!" else: print "Wrong input. Please enter yes or no" repeat = False
true
8ca9e1671fdfbbaac7b5703b893d97cb75ea6106
MrElectro1/Python_Class
/6.1Functions.py
729
4.3125
4
#Eric Hayden 04/24/2021 #greeting and gathering name Name=input('Please enter your name here:') print('Welcome '+Name+'. This program will gather your driven miles and calculate the total and give you the total miles you have driven in miles and kilometers.') #gathering miles driven try: miles=int(input('Please enter the total number of miles driven:')) kilometers=float(1.60934) #miles to kilometers function def conversion_function(): return miles*kilometers print(f"Hello {Name}. Your total miles driven is {miles}. That is also {conversion_function()} kelometers.") except: print(f"We are sorry {Name} but we where not able to convert the muber of miles you have driven to kelometers. Please try again.")
true
7d95dd31441399dd29d4336040449c0edcc83a0e
elandt/devTools
/python/python_essential_training/Chap08/sets.py
805
4.25
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # Sets are MUTABLE - add, delete, or change values # They use {}, and unordered list of UNIQUE values # Typically used for checking set membership def main(): a = set("We're gonna need a bigger boat.") b = set("I'm sorry, Dave. I'm afraid I can't do that.") print_set(a) # you can sort using sorted() print_set(sorted(b)) # in set a, but not set b print_set(a - b) # in set b, but not set a print_set(b - a) # in set a, set b, or both print_set(a | b) # in set a, set b, but NOT both print_set(a ^ b) # in set a AND set b print_set(a & b) def print_set(o): print('{', end='') for x in o: print(x, end='') print('}') if __name__ == '__main__': main()
true
4a41566fdc398fa0d2cf22a01bbf9c27380b6662
ElJayRight/Sorting-algorithms
/insertion.py
524
4.21875
4
def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): print(arr) key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key arr = [64, 34, 25, 12, 22, 11, 90, 38, 86, 56] if __name__ =="__main__": insertionSort(arr)
true
c560a56564db27b1cc249480181d645c7fbb1dc3
midathanapallivamshi/pythonproject
/Lists.py
338
4.3125
4
#to create a list fruits=["apple","banana","cherry"] print(fruits) #to print the element using index value fruits=["apple","banana","cherry"] print(fruits[0]) print(fruits[1]) print(fruits[2]) #to change the specfic element on the lsit fruits=["apple","banana","cherry"] fruits[1]="mango" print(fruits) #add print(fruits.append(fruits))
true
8b9c12c4e339a8ec4e0a13679712a230e2565c50
makuznet/hse
/lesson-1_swap_letters/lesson_1_dz_1.py
1,050
4.25
4
user_input = input('Введите число или текст: ') # любой ввод — это строка try: value = int(user_input) # если с клавиатуры вводить a = 5, Питон сразу преобразует тип переменной в int print(value, '— целое число!') print('+, -, х, % — да! Конкатенация — нет!') except ValueError: try: value = float(user_input) # если c клавиатуры вводить b = 2.66, Питон сразу преобразует тип во float print(value, '— число с дробной частью?!') print('+, -, х, % — да! Конкатенация — нет!') except ValueError: print('Это текст! Его можно конкатенировать с другим текстом.') print('Например, трехкратно повторить:', user_input * 3) # трехкратно конкатенируем введенную строку
false
11088ff20473f154ddcfb0ed887a49b5210ecd93
jeremypedersen/pythonBootcamp
/code/class5/list_methods.py
726
4.21875
4
myList = ['Glenn', 'Sarah', 'Elizabeth'] # Add one thing to the list myList.append('Frank') print(myList) # Add more than one thing to the list myList.extend(['Carl', 'Sandy', 'Ralph']) print(myList) # Reverse all the items in the list myList.reverse() print(myList) # Sort the list (from biggest to smallest for numbers, from A-Z for words) myList.sort() print(myList) # Remove the last item from the list, and return it (so we can save it into a variable) print( myList.pop() ) print (myList) # Remove a specific thing myList.remove('Ralph') print(myList) # Insert something at a specific spot myList.insert(1, 'Bob') print(myList) # Find how many times something is in the list print( myList.count('Sandy') )
true
adfa48a60c1c3b4638f77800053b529bf813f3fd
mohsenabedelaal/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/1-normalize.py
596
4.1875
4
#!/usr/bin/env python3 """ Normalize """ import numpy as np def normalize(X, m, s): """ Normalizes (standardizes) a matrix: Args: - X is the numpy.ndarray of shape (d, nx) to normalize - d is the number of data points - nx is the number of features - m is a numpy.ndarray of shape (nx,) that contains the mean of all features of X - s is a numpy.ndarray of shape (nx,) that contains the standard deviation of all features of X Return: The normalized X matrix """ z = (X - m) / s return z
true
e256b488bdbe782abe8fad1aed6e5bd66c56a65a
mwcz/euler
/py/q1b.py
343
4.34375
4
#!/usr/bin/python # Problem 1 # If we list all the natural numbers below 10 # that are multiples of 3 or 5, we get 3, 5, # 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or # 5 below 1000. sum = 0 for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: sum += i print( "sum: %d" % sum )
true
e4b3bc6bf643441f4e3ea3c6afcd17ccd741ee32
lee-taekgyu/total_review
/12_if_while_for.py
253
4.21875
4
condition = True if condition == True: print('condition : True\n') elif condition == False: print('condition : False\n') else: print('condition : ???\n') while (condition): print('while\n') break for i in range(0,3): print(i)
true
da2feaaf4ef06774b938bac19c9f42a829bd85fd
Drorasor/net4_exercise
/targil4.py
1,755
4.1875
4
def menu(): while(True): choice=input("Menu:\n1.serch for URL \n2.add URL and IP \n3.delete IP from URL\n4.update the ip address of a specific URL\n5. print dict\n") if(choice=="1"): serch_url() elif(choice=="2"): add_url_ip() elif(choice=="3"): delete_url() elif(choice=="4"): update_ip() elif(choice=="5"): print_dict() else: print("Enter 1-5 only!!!\n") continue if(input("\nDo you want to exit? y/n\n")=="y"): break print("\nThanks and bye bye...\n")\ def serch_url(): serch= input("please serch for a URL\n") if serch in url_dict: print("This URL is in the list") else: print("This URL is not in the list") def add_url_ip(): x = input("please enter URL\n") y = input("please enter IP address\n") url_dict[x] = y print("your new URL dict is\n" + str(url_dict)) def delete_url(): print("this is the URE list\n ") print(url_dict) x = input("please choose one URL to delete from the dict above\n") url_dict.pop(x) print("new dict:\n" + str(url_dict)) def update_ip (): print("let's update the IP add to your choosen URL, this is the dict: \n" + str(url_dict)) x = input("choose URL") url_dict.update({x: input("writ a new IP add")}) print("new dict\n" + str(url_dict)) def print_dict(): print(url_dict) url_dict={ "www.ynet.co.il" : "192.168.1.1", "www.google.com" : "192.168.1.2", "www.one.com" : "192.168.1.3" , "www.calcalist.co.il" : "192.168.1.4", "www.mako.com" : "192.168.1.5" } menu()
true
b5e951004903aa5293ad27b4f8da7626a6ab1494
PolymerLiu/python-flask
/ppt3/3.2/list.py
472
4.15625
4
if __name__ == '__main__': # list = [1,2,'3',3.5,'abc'] # tinylist = ['a',1] # tinylist.append(456) # print(list) # print(list[0:-1]) # print(list[0]) # print(list[2:5]) # print(list*2) # print(list+tinylist) tuple = (1,2,'3',3.5,'abc') tuplelist = ('a',1) # tuple里面的元素一经赋值就不能改变 # tuplelist[2] = '456' print(tuple) print(tuple[0:-1]) print(tuple[0]) print(tuple[2:5]) print(tuple*2) print(tuple+tuplelist)
false
bc273570f33fa94b848a2fb3f68fd28585ccaf79
szenius/find-todos
/find_todos.py
1,435
4.125
4
from os import listdir, getcwd from os.path import isfile, join, isdir def find_todos(dir_path): ''' Recursively finds files in the given dir_path and its sub-directories. When a file with the keyphrase TODO is found, print its file path. This is done regardless of case or usage. Input Arguments: dir_path: the directory in which we look for files with the keyphrase TODO. ''' for f in listdir(dir_path): file_path = join(dir_path, f) if isfile(file_path) and has_todo(file_path): print(file_path) elif isdir(file_path): find_todos(file_path) def has_todo(file_path): ''' Returns True if the given file_path corresponds to a file with the keyphrase TODO in its content. Otherwise return False. If any Exception is raised, it is assumed that there is no TODO in the content, and False is returned. Input Arguments: file_path: corresponds to a file which we want to check the content for TODO. ''' try: with open(file_path, 'r', encoding="utf8") as f: content = f.read() return 'todo' in content.lower() except Exception as e: return False def run(): ''' Find the TODO keyphrase in files in the current working directory and its sub-directories. Print the file paths of such files. ''' cwd = getcwd() find_todos(cwd) if __name__ == '__main__': run()
true
aa396ec3663fe65339f8ea4205ba03e679f1bf2f
YuriiGl/Hillel_home_work_1
/lesson_5/lesson_5-5.py
526
4.375
4
# 5. Написать функцию square, принимающую 1 аргумент — сторону квадрата, # и возвращающую 3 значения (с помощью кортежа): периметр квадрата, площадь квадрата и диагональ квадрата. a = float(input('Введите величину стороны квадрата: ')) def square (a): p = a * 4 s = a ** 2 d = (2*a**2)**0.5 result = (p, s, d) return result print(square(a))
false
920220e7bb7813a7736eb5e0b98fb9e5fc992e7f
yiwang0601/survmeth895
/exercises/assignment4_catalog_updated.py
1,054
4.1875
4
# open the txt file file_name = "rj.txt" my_file = open("rj.txt", "r") # create a dictionary word_counts = {} # define what is punctuation for later use punc = set('!@#$%^&*()_-+={}[]:;"\|<>,.?/~`') # loop over text to capture words for line in my_file: # Take words out of lines and put it in a new list named words word_list = line.split() # Loop over word list for word in word_list: # For each word change all characters to lower case # to make words in consistant word = word_list.lower() # Remove all punctuation for consistancy word = ''.join((x for x in word if x not in punc)) # Is the word present in the dictionary? if word in word_counts: # if yes then add 1 to the frequency of the word word_counts[word] = word_counts[word] + 1 # if the word not present in the dictionary else: # add the word in the dictionary and set the frequency to be 1 word_counts[word] = 1 # for each word in the dictionary for i in word_counts: # print the word and its frequency with the word print(i, counts[i])
true
18d198e72ed9a132a5a1c428eafbffaa255c5465
SomethingRandom0768/PythonBeginnerProgramming2021
/Chapter 6 ( Dictionaries )/Exercises/6-11cities.py
942
4.21875
4
cities = {'Gaborone' : { 'Country' : 'Botswana', 'Population' : "208,411", 'Fact' : "Home to the world's largest concentration of African elephants", }, 'Vilnius' : { 'Country' : 'Lithuania', 'Population' : "540,000", 'Fact' : "8% of all white storks in the world breed here ", }, 'Caracas' : { 'Country' : 'Venezuela', 'Population' : "2,946,000", 'Fact' : "Home to one of the largest financial districts in South America", } } for name, info_group in cities.items(): print(f"\nThe city's name is {name} and has the following information:") for label, info in info_group.items(): print(f"{label} : {info}")
false
159119e169c4be4a8f3eafb3931ae5f4f736d6e4
SomethingRandom0768/PythonBeginnerProgramming2021
/Chapter 4 ( Working With Lists )/Exercises/4-10slices.py
450
4.15625
4
# Reusing a list from 4-2 but just adding more animals to fit the exercise animals = ['dog', 'cat', 'ferret', 'jaguars', 'lions', 'boars', 'pigs'] first_three = animals[ : 3 ] middle_three = animals[ 3 : 4] last_three = animals[-3 : ] # print statements print(f"The first three items in the list are: {first_three}") print(f"Three items from the middle of the list are: {middle_three}") print(f"The last three items in the list are: {last_three}")
true
9677c8b50af2ffdc4faea164d22001e4711bcabb
SomethingRandom0768/PythonBeginnerProgramming2021
/Chapter 3 ( Introducing Lists )/Exercises/3-7shrinking_guest_list.py
1,971
4.28125
4
guest_list = ["shishkebab", "SomethingDeliberate", "SomethingRandom"] print("It turns out that we've found a bigger table so we can invite more people!\n") guest_list.insert(0, "Kitty") guest_list.insert(1, "Oh Deer") guest_list.append("Pusheen") message1 = f"Hi {guest_list[0]}, would you like to come for dinner tonight?" message2 = f"Hi {guest_list[1]}, would you like to come for dinner tonight?" message3 = f"Hi {guest_list[2]}, would you like to come for dinner tonight?" message4 = f"Hi {guest_list[3]}, would you like to come for dinner tonight?" message5 = f"Hi {guest_list[4]}, would you like to come for dinner tonight?" message6 = f"Hi {guest_list[5]}, would you like to come for dinner tonight?" print(message1) # Pretty much a copy and paste print(message2) print(message3) print(message4) print(message5) print(message6) # Using the same program from 3-6 above print("\nOh no! The table won't arrive in time so we'll have to remove a few people :( \n") # We've got 6 people in the list right now, so we should remove 4 of them first_person = guest_list.pop(0) second_person = guest_list.pop(0) third_person = guest_list.pop(0) fourth_person = guest_list.pop(0) goodbye1 = f"Sorry {first_person}, but you can't come :( Come back whenever we get the bigger table!" goodbye2 = f"Sorry {second_person}, but you can't come :( Come back whenever we get the bigger table!" goodbye3 = f"Sorry {third_person}, but you can't come :( Come back whenever we get the bigger table!" goodbye4 = f"Sorry {fourth_person}, but you can't come :( Come back whenever we get the bigger table!\n" print(goodbye1) # Printing all the sorry messages print(goodbye2) print(goodbye3) print(goodbye4) coming1 = f"{guest_list[0]}, you can come since there's only 2 spots left!" coming2 = f"{guest_list[1]}, you can come since there's only 2 spots left!" print(coming1) print(coming2) del guest_list[0] # Deleting the two people that are left in the list. del guest_list[0]
true
72cef646b56af41d67d0227047144bfa85e197ec
monjurul003/algorithm-problems
/checkForPalindrome.py
1,079
4.25
4
# Algorithm to check if a given string can be converted to a palindrome. # A string can be converted to a palindrome if it contains at most one character that # occurs odd number of times and all other characters occur even number of times def checkIfStringIsPalindrome(s): if s == None: return False n = len(s) if n == 0: return True ## empty string is palindrome hashmap = {} for c in s: if hashmap.get(c) == None: hashmap[c] = 1 else: hashmap[c] = hashmap[c] + 1 oddcount = 0 oddchar = None for key in hashmap.keys(): if hashmap[key] % 2 != 0: oddcount = oddcount + 1 oddchar = key if oddcount == 0 or oddcount == 1: front = []; back = [] for key in hashmap.keys(): if key != oddchar: front.append(key); back.append(key) newS = "" for i in front: newS = newS + i if oddchar != None: newS = newS + oddchar for i in reversed(back): newS = newS + i return True, newS else: return False, None if __name__ == '__main__': s = raw_input() print "Can be palindrome: ", checkIfStringIsPalindrome(s)
true
f4dd03434e6ce383d3a346499f5d118a720eaeb4
DebbyMurphy/debbys-python-projects
/wk4-exercise_booleans-and-if-statements/booleans-and-if-statements.py
1,930
4.375
4
# Q1) Kate’s cat, Roary, loves catching moths. Write a program that determines whether or not it is time for Roary catch moths. # print() # moths_in_house = True # if moths_in_house is True: # print("Get the moths!") # if not moths_in_house is True: # print("No threat detected.") # print() # Q2) Kate’s cat, Roary, loves catching moths. Write a program that determines whether or not it is time for Roary catch moths. print() moths_in_house = False mitch_is_home = True if moths_in_house == True and mitch_is_home == True: print("Hoooman! Help me get the moths!") if moths_in_house == False and mitch_is_home == False: print("No threat detected.") if moths_in_house == True and mitch_is_home == False: print("Meooooooooooooow! Hissssss!") if moths_in_house == False and mitch_is_home == True: print("Climb on Mitch.") print() # Q3) Write a program that implements the algorithm for Red Light Cameras. print() light_colour = "Red" car_detected = True if light_colour == "Red" and car_detected == False: print("Do nothing.") if light_colour == "Red" and car_detected == True: print("Flash!") if light_colour == "Green" and car_detected == False: print("Do nothing.") if light_colour == "Green" and car_detected == True: print("Do nothing.") if light_colour == "Amber" and car_detected == False: print("Do nothing.") if light_colour == "Amber" and car_detected == True: print("Do nothing.") # Q4) Write a program that asks the user for their height, and determine whether or not they are tall enough to ride the rollercoaster, which has a height requirement of 120cms. height = 119 if height >=120: print("Hop on!") else: print("Sorry, not today :(")
true
9ef09744ea53b5cd0639054893262f137dd79de3
Garlinsk/Kata
/fun-calctype/run.py
1,056
4.5625
5
# You have to create a function calcType, which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them(also a number). # Based on those 3 values you have to return a string, that describes which operation was used to get the given result. # The possible return strings are: "addition", "subtraction", "multiplication", "division". ##BDD ##create a function # eg-def calcType(a,b,c): ## use if statements ##to check for addition; if(a+b)== c result be addition ##Return the results ## #pseudocode #define function #assign variables value to be input #print strings results def calcType(): a = int(input("Enter number\n")) b = int(input("Enter another number\n")) c = int(input("Enter a third number\n")) if a + b == c: results = "addition" elif a - b == c: results = "substraction" elif a * b == c: results = "multiplication" elif a / b == c: results = "division" else: results = "Check your inputs " print(results) calcType()
true
8c37962ee323ef3bf45e9bfd938308cc0a179c62
ashfakshibli/python_everyday
/Regular Expression/metacharacters.py
1,153
4.65625
5
""" Metacharacters are what make regular expressions more powerful than normal string methods. They allow you to create regular expressions to represent concepts like "one or more repetitions of a vowel". The existence of metacharacters poses a problem if you want to create a regular expression (or regex) that matches a literal metacharacter, such as "$". You can do this by escaping the metacharacters by putting a backslash in front of them. However, this can cause problems, since backslashes also have an escaping function in normal Python strings. This can mean putting three or four backslashes in a row to do all the escaping. To avoid this, you can use a raw string, which is a normal string with an "r" in front of it. We saw usage of raw strings in the previous lesson. """ import re pattern = r"gr.y" if re.match(pattern, "grey"): print("Match 1") if re.match(pattern, "gray"): print("Match 2") if re.match(pattern, "blue"): print("Match 3") pattern = r"^gr.y$" if re.match(pattern, "grey"): print("Match 4") if re.match(pattern, "gray"): print("Match 5") if re.match(pattern, "stingray"): print("Match 6")
true
20cc3faaaac7c935d39b29d9d73551e1430157af
ashfakshibli/python_everyday
/Functional Programming/recursion.py
1,175
4.5
4
# recursive implementation of the factorial function. def factorial(x): if x == 1: return 1 else: return x * factorial(x-1) num = int(input("Enter number to factorial: ")) print(factorial(num)) """ Recursion can also be indirect. One function can call a second, which calls the first, which calls the second, and so on. This can occur with any number of functions. """ def is_even(x): if x == 0: return True else: print (x) return is_odd(x-1) def is_odd(x): return not is_even(x) print(is_odd(17)) print(is_even(24)) """ Fibonacci """ def fib(x): if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2) print(fib(4)) # 5 # """ fib(4) ¡----------------^----------------¡ fib(3) + fib(2) ¡------^------¡ ¡--------^-----¡ fib(2) + fib(1) fib(1) + fib(0) ¡----^----¡ | | | fib(1)+ fib(0) | | | | | | | | 1 + 1 + 1 + 1 + 1 """
true
6ff6c435ff332d89c70ebc390109abb1138fe733
UltimateBlue/Python
/008-average-calculator/main.py
379
4.125
4
nums = input('Enter numbers to calculate their average: ') temp = nums.split(',') sum = 0 maxim = int(temp[0]) for x in temp: sum += int(x) if maxim<int(x): maxim = int(x) print(f"Average is {sum/len(temp)}") print(f"maximum value is {maxim}") # write a program which add up even numbers between 1 to 100 sum = 0 for i in range(2,101,2): sum+=i print(sum)
true
5c6e7c87e6c90cb99f8277badce7b8fc04690214
mcrrobinson/Python-Maths-Examples
/Strings and Files (practP4)/formal_name.py
436
4.28125
4
# Write a formalName function which asks the user to input his/her given name and # family name, and then outputs a more formal version of their name. E.g. on input # Sam and Brown, the function should output S. Brown (again note the spacing and # punctuation). def formalName(): fullname = input("Please enter your full name: ") return (fullname.split()[0][0]).title() + ". " + (fullname.split()[1]).title() print(formalName())
true
34941736be3c9d73a39978056ee487be3c3ba67e
dansoh/python-intro
/python-crash-course/exercises/chapter-10/10-7-addition-calculator.py
459
4.15625
4
""" Prompt for two numbers, add them together, and print the result """ print("Provide two numerical values and I'll print the sum.") print("(enter q to exit)") while True: try: number1 = input("Value 1: ") if number1 == 'q': break number2 = input("Value 2: ") if number1 == 'q': break result = int(number1) + int(number2) print("Sum: " + str(result)) except ValueError: print("Please only enter numerical values!")
true
c2fd3126b3bfdd1005df0b7ef46a5d668e0caee2
dansoh/python-intro
/python-crash-course/exercises/chapter-9/9-12/admin.py
994
4.28125
4
"""A set of classes that is used to represent an Admin user""" from user import User class Privileges(): """ A separate class for different user privileges """ def __init__(self): """Initialize privilege atributes""" self.privileges = ['can add post', 'can delete post' , 'can ban user'] def show_privileges(self): """ Show the list of privileges a user has """ print('The user has the following privileges: ') for privilege in self.privileges: print('\t' + str(privilege)) class Admin(User): """Represents an Admin, a subset of User""" def __init__(self, first_name, last_name, age, gender, location): """ Initialize attributes of the parent class. Then initalize attributes of an Admin user """ super().__init__(first_name, last_name, age, gender, location) self.privileges = Privileges()
true
c7930bba26fb578109e0dd48ac5457ebc5474d8c
vitorvicente/LearningPython
/Basics/BasicStringManipulation.py
1,578
4.1875
4
# String manipulation print("Basic String Manipulation:") print("s1 = 'Hello World'\n") s1 = "Hello World" print("s1[0] =", s1[0]) print("len(s1) =", len(s1)) print("s1.count('l') =", s1.count('l')) print("s1.find('e') =", s1.find('e')) print("s1[:-5] =", s1[:-5]) print("s1.split(' ') =", s1.split(' ')) print("s1*2 =", s1*2) # Caps String manipulation print("\nCaps String Manipulation:") print("s2 = 'hello there' AND s3 = 'HEY' AND s4 = 'hEy' \n") s2 = "hello there" s3 = "HEY" s4 = "hEy" print("s2.upper() =", s2.upper()) print("s3.lower() =", s3.lower()) print("s2.title() =", s2.title()) print("s4.swapcase() =", s4.swapcase()) print("s2.capitalize() =", s2.capitalize()) # String Content manipulation print("\nString Content Manipulation:") print("s5 = '01234' AND s6 = '56789' \n") s5 = "01234" s6 = "56789" print("s5.replace('1', '0') =", s5.replace('1', '0')) print("''.join(reversed(s5)) =", ''.join(reversed(s5))) print("s5.strip() =", s5.strip()) print("s5.lstrip() =", s5.lstrip()) print("s5.rstrip() =", s5.rstrip()) print("s5 + s6 =", s5 + s6) print("' '.join(s5) =", ' '.join(s5)) # String Content manipulation print("\nString Testing:") print("s7 = 'Complete String' \n") s7 = "Complete String" print("s7.startswith('H') =", s7.startswith('H')) print("s7.endswith('g') =", s7.endswith('h')) print("s7.isalnum =", s7.isalnum()) print("s7.isalpha =", s7.isalpha()) print("s7.isdigit =", s7.isdigit()) print("s7.istitle =", s7.istitle()) print("s7.isupper =", s7.isupper()) print("s7.islower =", s7.islower()) print("s7.isspace =", s7.isspace())
false
29fccebc4a879a2e171bdcb7200e5c01565fc439
ishantk/JPMorganAdvancePythonJuly2021
/S1DataTypes.py
2,316
4.3125
4
""" Data Types Containers -> They hold Data and the type of data which they hold is basically data type 1 Single Value Container which holds only 1 value 2 Multi Value Container which holds multiple values Homogeneous Hetrogeneous """ # Numbers # int float and complex # a = 10 # a = 10.55 a = 1+5j print("a is:", a, "TYPE", type(a)) print("a is instance of complex", isinstance(a, complex)) # Textual message = "Please Connect to Internet and Try Again" # Boolean is_internet_connected = True # Data Types which are Multi Value Containers # List, Tuple, String, Set, Dictionary, Arrays # These are Sequences # List | Mutable # its an ordered sequence. # Hetrogeneous data = [10, 20, "Hello", 2.2, 10] print(data, type(data), hex(id(data))) print(data[0], type(data[0]), hex(id(data[0]))) print(data[1], type(data[1]), hex(id(data[1]))) print(data[2], type(data[2]), hex(id(data[2]))) print(data[3], type(data[3]), hex(id(data[3]))) print(data[4], type(data[4]), hex(id(data[4]))) age = 10 print(age, type(age), hex(id(age))) del age # removes only age reference variable data[1] = 100 # Tuple # menu = "File", "Edit", "View", "Navigate", "Help" menu = ("File", "Edit", "View", "Navigate", "Help") print(menu, type(menu), hex(id(menu))) # menu[1] = "MyFile" print(menu[1]) # Strings s1 = 'John\'s Cafe' s2 = "John's Cafe" s3 = """This is first line This is second line This is third line """ s4 = "Pay \u20b9 2000" s5 = r"John\'s \n Cafe" # Set -> Unordered But Unique | Hashing data = {10, 20, 10, 20, 30, 50, 70, 70} print(data, type(data), hex(id(data))) # error -> Set works with Hashing and Not Indexing # print(data[0]) # data[0] = 100 # Exploration -> Can we manipulate content in Set ? # Dictionary covid_cases = { "country": "India", "active": 1000, "confirmed": 20000, "recovered": 95000 } print(covid_cases, type(covid_cases), hex(id(covid_cases))) covid_cases['active'] = 3450 covid_cases['vaccinated'] = 750 del covid_cases['recovered'] print(covid_cases['active']) print(covid_cases) # Arrays in Python # import array as arr import array # Homogeneous election_results = array.array('i', [10, 20, 30, 40, 50]) print(election_results, type(election_results), hex(id(election_results)))
true
9ae917d5a156a3becd3b037c920930321dab4c12
ishantk/JPMorganAdvancePythonJuly2021
/S3Documentation.py
1,614
4.28125
4
""" This script is about demo of how we document the code This file can be imported in other modules * main - the script has a main function * Dish - This class will have information about how we can do OOPS on Dish * create_dish_lost - The function creates a list of dishes """ class Dish: """ This is Dish Class, use to hold information and processing for Dish Attributes ---------- code: int This is a unique code to the dish title: str This is the title of the dish. Cannot be greater than 10 characters Methods ------- show_dish() Prints the Details of the Dish """ def __init__(self, code, title, price, category): """ init function will write the initial attributes with data in the object Parameters ----------- :param code: int this is to hold a unique code :param title: str :param price: float :param category: str """ self.code = code self.title = title self.price = price self.category = category print("__init__ executed and self is:", self) def show_dish(self): """ :return: None """ print("^"*20) print("DISH DETAILS") print("^" * 20) print("{} | {} \n{} | {}".format(self.code, self.title, self.price, self.category)) print() print(Dish.__doc__) print(Dish.__init__.__doc__) print(Dish.show_dish.__doc__) print(help(Dish))
true
8ceab4efbb036b66747f540c6834c16f8d83f4b1
ishantk/JPMorganAdvancePythonJuly2021
/S2Functions1.py
981
4.21875
4
print("__name__ in S2Functions1.py is:", __name__) """ Function Piece of code which can be executed again and again as we need it """ message = "Hello All" my_message = message # Copy Operation -> Shallow Copy # Definition of Function def hello(name): """ this is a hello function to demonstrate how function works :param name: takes the name of person as input :return: None """ print("Hello,", name) # Terminating Statement for a function # return # return None hi = hello # Shallow Copy -> Copy from 1 reference to another # Execution of Function hello("John") hello("Jennie") hello("Fionna") result = hello("George") print("result is:", result) print("message is: ", message, type(message), hex(id(message))) print("my_message is: ", my_message, type(my_message), hex(id(my_message))) print("hello is: ", hello, type(hello), hex(id(hello))) print("hi is: ", hi, type(hi), hex(id(hi))) hi("Sia") print(hello.__doc__)
true
641fd7fd5834367778a2121edcdf82bd25849f1d
ishantk/JPMorganAdvancePythonJuly2021
/S4MagicMethods.py
1,788
4.375
4
""" Magic Methods in Python """ import datetime today = datetime.datetime.today() print(today) # whenever we print reference variable we get the string representation print(str(today)) print(repr(today)) class Product: def __init__(self, pid, name, price): self.pid = pid self.name = name self.price = price # string is to give the representation of the state of an object # informal information def __str__(self): return "{} | {} | {}".format(self.pid, self.name, self.price) def __repr__(self): return "Product({}, {}, {})".format(self.pid, self.name, self.price) # Operator Overloading :) def __add__(self, other): price = self.price + other.price return Product(pid=None, name=None, price=price) def __lt__(self, other): return self.price < other.price def to_csv(self): return "{}, {}, {}\n".format(self.pid, self.name, self.price) # If we wish to make objects iterable def __next__(self): pass def __iter__(self): pass p1 = Product(pid=101, name="LED TV", price=30000) p2 = Product(pid=201, name="AlphaBounce Shoe", price=8000) p3 = Product(pid=301, name="iphone", price=80000) p4 = Product(pid=401, name="Football", price=250) p5 = Product(pid=501, name="Tshirt", price=200) products = [p1, p2, p3, p4, p5] print(p1) print(str(p1)) print(repr(p1)) shopping_cart = [p1, p3, p5] final_product = p1 + p3 + p5 print("Total Amount:", final_product.price) print("Validating which product has lesser price: ") if p1 < p2: print(p1) else: print(p2) # with open("products.csv", "a") as file: # file.write() file = open("products.csv", "a") for product in products: file.write(product.to_csv()) print("File Written")
true
ec735769521da48d7f16ca714d38cce5ac25fb63
REGENTMONK97/Python-
/Control Statements/Fibonacci.py
204
4.125
4
a = int(input("Enter an integer: ")) f = 0 i = 1 j = 0 print("The fibonacci numbers up till ",a," is: 0,",end = "") while f<=a: f = i+j i = f j = i if f<a: print(f, end=",")
false
a3938a90c84920ce04118b3097147326f66749a7
REGENTMONK97/Python-
/Lists and Tuples/Lists/test.py
804
4.21875
4
#You have a record of students. #Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. #The marks can be floating values. #The user enters some integer followed by the names and marks for students. #You are required to save the record in a dictionary data type. #The user then enters a student's name. #Output the average percentage marks obtained by that student, correct to two decimal places. name = [] m1 = [] m2 = [] m3 = [] d = {} n = int(input("Nos: ")) for i in range(n): name1 = input("Name: ") name.append(name1) m11 = float(input("M1")) m1.append(m11) m21 = float(input("M2")) m2.append(m21) #m31 = float(input("M3:")) #m1.append(m31) #m41 = float(input("M4:")) #m1.append(m41) d = zip(name,m1,m2) print(d)
true
010357a788d195726f238caa462e6b4095269aa7
ereynolds123/introToProgramming
/gradient.py
1,105
4.4375
4
#Create a color gradient #Import graphics library from graphics import * #Create the window win=GraphWin("Color Gradient", 400, 250) #Declare window variables windowWidth = 400 #Accumulator Variables gradientsAccumulator=0 numberOfGradients =1 #Set up the gradient width gradientWidth = windowWidth/12 #Color Variables red=0 green =0 blue=0 #Loop to draw the rectangles for gradient in range(12): #Accumulate the amount of gradients gradientsAccumulator= gradientsAccumulator + 1 #Set the amount of gradients to the accumulated gradients value numberOfGradients= gradientsAccumulator #Change the color for every rectangle a small increment green = green +8 #Draw a Rectangle gradientRectangle = Rectangle(Point(gradientWidth-33.33, 0), Point(gradientWidth, 250)) #Eliminate the width of the the rectangle gradientRectangle.setWidth(0) #Fill in the color of the rectangle gradientRectangle.setFill(color_rgb(red,green,blue)) gradientRectangle.draw(win) #Accumulate the gradient width gradientWidth =gradientWidth +33.33
true
d469ffc3f06c6e5cd7de6bf30dc9842fa768ba38
ereynolds123/introToProgramming
/ball_filler.py
853
4.21875
4
# A program to calculate the amount of filler in a bowling ball import math # User imputs number of bowling balls bowlingBallNumber= int(input("How many bowling balls will be manufactured? ")) # User inputs the diameter of the ball diameterBowlingBall = float(input("What is the diameter of each ball in inches? ")) #User inputs the core volume in inches coreVolume = float(input("What is the core volume in inches cubed? ")) # Calculate the radius of the ball radiusBowlingBall = diameterBowlingBall /2 #Calculating the total volume of the ball volume = (4/3) * math.pi * ((radiusBowlingBall)**3) #Calculating the filler required filler = volume - coreVolume #Calculate total filler totalFiller = filler * bowlingBallNumber #Print the amount of total filler to make all bowling balls print("You will need", totalFiller, "inches cubed of filler")
true
70f0fe71248636d66d25f4b45360060f64810a13
MuSaCN/PythonLearning
/Learning_Basic/老男孩Python学习代码/day2-基本数据结构/names.py
1,954
4.125
4
# Author:Zhang Yuan names = 'A1 A2 A3 A4' print(names) names=['A1','A2','A3','A4'] print(names[0],names[2]) print(names[1]+' '+names[2]) #切片(顾头不顾尾) print(names[1:3]) print(names[0:2]) print(names[3:]) #取后面的 print(names[-2:]) names.append("A5") #追加一个到最后 print(names) names.insert(1,"A1.5") #插入到指定位置 print(names) names[1]='A1.55' #修改 print(names) #delete names.remove("A2") print(names) del names[1] print(names) names.pop(2) print(names) #查找元素 print(names.index("A5")) print(names[names.index("A5")]) #列表有相同元素 names.append("A3") #追加一个到最后 print(names) print(names.count("A3")) #返回列表中多少个指定元素 names.reverse() #列表翻转 print(names) names.sort() #排序列表 names2=[1,2,3,4] names.extend(names2) #合并列表name2到name1末尾 #del names2 #删除列表name2 #列表中可以再追加列表,追加列表本质是追加指针 names.append(["B1","B2"]) names2 = names.copy() #普通copy只能复制第一层 import copy names3=copy.deepcopy(names) #深度copy相当于重新建立内存 names[-1].append("B3") #指针指向的列表追加的数据,所以下面names,names2两个变量都显示变化 print(names,names2,names3) #不同于c++数组,python内存和变量的关系与c++不同!!! a=[1,2,3] #分配内存,a指向数据 b=a #b也指向a指向的数据 c=a.copy()#复制,新增加内存储存数据 a[-1]=66 #通过a修改内存数据 print(a,b,c) #所以b变化,c不变 a[0]=66 #通过a修改内存数据 print(a,b,c) #所以b变化,c不变 a=[1,2,3] #a重新赋值,相当于重新分配内存,但是b指向的内存依然不变 print(a,b,c) #所以b不变,c不变 #列表的有步长的切片 print(names,names[0::2]) #从开始到末尾,包括末尾 print(names,names[::2]) #0可以省略 #列表的循环 for i in names: print(i) #清空列表 #names.clear() #print(names)
false
5ec727a975c3dd5707c44d21da1913d88980b76f
MuSaCN/PythonLearning
/Learning_Basic/老男孩Python学习代码/day1-介绍与循环/interaction.py
498
4.15625
4
# Author:Zhang Yuan name = input("name:"); age = int(input("age:")) print(type(age), type(str(age))) job = input("job:"); info = ''' ------- info of %s ------ Name:%s Age:%d Job:%s ''' % (name, name, age, job) print("info=", info) info2 = ''' ------- info of {_name} ------ Name:{_name} Age:{_age} Job:{_job} '''.format(_name=name, _age=age, _job=job) print("info2=", info2) info3 = ''' ------- info of {0} ------ Name:{0} Age:{1} Job:{2} '''.format(name, age, job) print("info3=", info3);
false
f1e4029ec2d85729bfd44356ce90eb499b7e157b
Krathinavada15/krathinavada
/ASSIGNMENT_PYTHON/M1/Q5.py
355
4.34375
4
"""5. Write a program to print the Fibonacci series up to the number 34. (Example: 0,1,1,2,3,5,8,13,… The Fibonacci Series always starts with 0 and 1, the numbers that follow are arrived at by adding the 2 previous numbers.)""" a = 0 b = 1 c = 0 print(a,b,end=" ") while not c==34: c=a+b print(c,end=" ") a,b=b,c
true
cce3dbb1053c14712c41bb22e445e7f4ac37a0fd
Luis-Felipe-N/curso-em-video-python
/modulo-2/exercicios/042-analisando_triangulos_2.py
829
4.34375
4
'''Como no desafil 035 vamos ler três retas, e além de mostrar a existencia de um triangulo Mostrar se o tipo dos triangulos. - Equilátero: todos os lados iguais - Isósceles: dois lados iguais - Escaleno :todos lados diferentes''' reta1 = float(input('Qual o comprimento da primeira reta: ')) reta2 = float(input('Qual o comprimento da segunda reta: ')) reta3 = float(input('Qual o comprimento da terceira reta: ')) if reta1 < reta2 + reta3 and reta2 < reta1 + reta3 and reta3 < reta2 + reta1: if reta1 == reta2 == reta3: print('Pode existir um triâgulo Equilátero.') elif reta1 == reta2 or reta1 == reta3 or reta2 == reta3: print('Pode existir um triângulo Isósceles.') else: print('Pode existir um triâgulo Ecaleno') else: print('Não piode existir um triângulo')
false
291ce1b97e78ac1d72966094637d5be26773024e
CoitThomas/Milestone_5
/convert_odd_input.py
1,554
4.375
4
"""Convert input in the form: <positive_integer>,<string> If the positive integer is odd, print the name in all capital letters. Otherwise, print the name as it was entered. """ def validate(some_list): """Return True if the given input is a list of two strings, the first string only contains a number, and the second string only contains letters. Otherwise, return False. """ assert isinstance(some_list, list), "The given parameter needs to be a list." for element in some_list: assert isinstance(element, str), "Both elements in the list needs to be a string." return len(some_list) == 2 and some_list[0].isdigit() and some_list[1].isalpha() def is_odd(integer): """Return True if a given integer is odd. Otherwise, return False.""" assert isinstance(integer, int), "The given parameter needs to be an integer." return integer%2 == 1 def convert(some_string): """Parse a string into a list of two strings. Convert the first string into an integer. If the integer is an odd number, capitalize all the letters in the second string and return it. Otherwise, just return the second string. """ assert isinstance(some_string, str), "The given parameter needs to be a string." parse_input = some_string.split(',') assert validate(parse_input), "Input needs to follow the format: positive_integer,name" number = int(parse_input[0]) name = parse_input[1] if is_odd(number): name = name.upper() repackage = str(number)+','+name return repackage
true
a67f45a5cc0a7358aca42cabb486357e115cb54d
szbalazs0221/udemy_python
/Iterators_Generators_Homework.py
1,168
4.46875
4
# Iterators and Generators Homework # Problem 1 # Create a generator that generates the squares of numbers up to some number N. def gensquares(N): for i in range(N): yield i**2 for x in gensquares(10): print(x) print('\n') # Problem 2 # Create a generator that yields "n" random numbers between a low and high number (that are inputs). # Note: Use the random library. For example: import random def rand_num(low, high, n): for i in range(n): yield random.randint(low, high) for num in rand_num(1, 10, 12): print(num) print('\n') # Problem 3 # Use the iter() function to convert the string below into an iterator: s = 'hello' print(next(iter(s))) print('\n') # s = iter(s) # print(next(s)) # Problem 4 # Explain a use case for a generator using a yield statement where you # would not want to use a normal function with a return statement. # Extra Credit! # Can you explain what gencomp is in the code below? # (Note: We never covered this in lecture! You will have to do some Googling/Stack Overflowing!) my_list = [1,2,3,4,5] gencomp = (item for item in my_list if item > 3) for item in gencomp: print(item)
true
adf76ea55425a885e6d9e267af4d09648c8b83d7
paulsatish/IGCSECS
/15May-1d-hightempwithdate.py
408
4.40625
4
#replace (1,3) with (1,7) later TempMidday=[] DayMax=-999 DateMax=0 for i in range(1,3): temp1=float(input("Please enter the Temperature for MidDay")) TempMidday.append(temp1) print(TempMidday) if temp1>DayMax: DayMax=temp1 DateMax=i print("The day with maximum Mid-day temperatureis: " + str(DayMax)) print("The date of Maximum temperature recorded is on: " + str(DateMax))
true
f625a22135936ed7ff4ec31ebf38f809f85e9506
daminiamin/Calculator1
/arithmetic.py
1,644
4.375
4
"""Math functions for calculator.""" # Errors # "Those aren't numbers" message when no space between first two numbers..? + 12 # "Not enough inputs" message when no space between + and proceeding numbers +12 # Prints 10 every time regardless of which numbers are used # Error message "enter operator followed by two ints" when we have +1 2 # If input is not a number or symbol then it says "not enough inputs" # num1 = int(input("Enter a first number: ")) # num2 = int(input("Enter a second number: ")) def add(num1, num2): """Return the sum of the two inputs.""" addition = num1 + num2 return addition # return 5 def subtract(num1, num2): """Return the second number subtracted from the first.""" subtraction = num1 - num2 return subtraction def multiply(num1, num2): """Multiply the two inputs together.""" multiplication = num1 * num2 return multiplication def divide(num1, num2): """Divide the first input by the second and return the result.""" division = num1/num2 return division def square(num1): """Return the square of the input.""" square_num = num1**2 return square_num def cube(num1): """Return the cube of the input.""" cube_num = num1**3 return cube_num def power(num1, num2): """Raise num1 to the power of num2 and return the value.""" power_num = num1 ** num2 return power_num def mod(num1, num2): """Return the remainder of num1 / num2.""" modulo_nums = num1 % num2 return modulo_nums print(add(2,2)) print(subtract(2,2)) print(multiply(2,3)) print(divide(3,2)) print(square(2)) print(power(2, 3)) print(cube(2))
true
5e274b30b312654794653e0a6c7b0ae3e86bc245
josd/josd.github.io
/temp/python/easter.py
702
4.5
4
# See https://en.wikipedia.org/wiki/List_of_dates_for_Easter # Original code from http://code.activestate.com/recipes/576517-calculate-easter-western-given-a-year/ from datetime import date def easter(year): "Returns Easter as a date object." a = year % 19 b = year // 100 c = year % 100 d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30 e = (32 + 2 * (b % 4) + 2 * (c // 4) - d - (c % 4)) % 7 f = d + e - 7 * ((a + 11 * d + 22 * e) // 451) + 114 month = f // 31 day = f % 31 + 1 return date(year, month, day) if __name__ == "__main__": for y in range(2021, 2050): print('[] :python-result "easter(%d) = %s".' % (y, easter(y)))
false
373f943beabbbbc6e1274d73d772559e6504a79e
pankaj-cloud/Python_Essentials
/Operators and expressions.py
809
4.25
4
""" Your task is to prepare a simple code able to evaluate the end time of a period of time, given as a number of minutes (it could be arbitrarily large). The start time is given as a pair of hours (0..23) and minutes (0..59). The result has to be printed to the console. For example, if an event starts at 12:17 and lasts 59 minutes, it will end at 13:16. Don't worry about any imperfections in your code - it's okay if it accepts an invalid time - the most important thing is that the code produce valid results for valid input data. Test your code carefully. """ hour = int(input("Starting time (hours): ")) mins = int(input("Starting time (minutes): ")) dura = int(input("Event duration (minutes): ")) a = ((mins + dura) // 60) b = ((mins + dura) % 60) c = (hour + a) print(c, b, sep=":" )
true
dae03807bf2933970098894d972e16518bcd4091
aadishsamir123/Roller-Coaster
/main.py
218
4.21875
4
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height >= 120: print("You can ride the Roller Coaster") else: print("Sorry you have to grow taller before you can ride")
true
f5b0969167695a2c6963996349223953109fda94
edsu/inst126
/modules/04/examples/comments.py
685
4.21875
4
# Antonio # Prompt and gather user input hrs = input("Enter hours: ") hrsRate = input("Enter rate: ") # Convert hours and hourly rate to float newHr = float(hrs); newRt = float(hrsRate) minWage = 17.50 # Pay ONLY calculated if hourly rate >= minWage; Otherwise error string is printed if newRt >= minWage: # Multiply hour and hourly rate ratePay = newHr * newRt # Convert the ratePay to String; Creates new string that combines "$" and ratePay convertRt = str(ratePay) rtString = "$" + convertRt # Final result print("Pay:", rtString, "\n") else: print("I'm sorry", hrsRate, "is lower than the minimum wage " + str(minWage))
true
e5c5031c0dc788b0b9bdb7a59f501996f1583673
Codeless10010/Sort
/three_Way_Merge_Sort/three_way_merge_sort.py
2,516
4.4375
4
# This function will handle the splitting of the data into 3 pieces # The base case for the recursion to stop is if the length of the array is less than 3. # In normal merge sort since we split by 2 the base case becomes if the array is less than 2. def three_way_merge_sort(a): if(len(a)>1): f_third=int(len(a)//3) s_third=(f_third*2)+1 L=a[:f_third] M=a[f_third:s_third] R=a[s_third:] three_way_merge_sort(L) three_way_merge_sort(M) three_way_merge_sort(R) merge(a,L,M,R) # The merge function will handle the three way merge. This is more intense than the regualr merge sort # due to the introduction of a third list/splice. The logic is as follows: compare the three splices and order # them from lowest to highest once one of them runs out you then compare the other two and finally fill in the leftover. def merge(arr,L,M,R): i,j,k,l=0,0,0,0 temp=[0]*(len(L)+len(R)+len(M)) while(i<len(L) and j<len(M) and k<len(R)): if(L[i]<M[j] and L[i]<R[k]): temp[l]=L[i] i+=1 l+=1 elif(M[j]<R[k]): temp[l]=M[j] l+=1 j+=1 else: temp[l]=R[k] k+=1 l+=1 #Compare the left over first and second slices while(i<len(L) and j<len(M)): if(L[i]<M[j]): temp[l]=L[i] i+=1 l+=1 else: temp[l]=M[j] j+=1 l+=1 #Compare the leftovers from the second and third slices while(j<len(M)and k<len(R)): if(M[j]<R[k]): temp[l]=M[j] j+=1 l+=1 else: temp[l]=R[k] k+=1 l+=1 #Compare the left over from the first and third slices while(i<len(L)and k<len(R)): if(L[i]<R[k]): temp[l]=L[i] i+=1 l+=1 else: temp[l]=R[k] k+=1 l+=1 #fill in the leftovers starting from the left segement (will always be smaller) while(i<len(L)): temp[l]=L[i] i+=1 l+=1 #fill in the leftovers starting from the middle segement while(j<len(M)): temp[l]=M[j] j+=1 l+=1 #fill in the leftovers starting from the left segement (will always be smaller) while(k<len(R)): temp[l]=R[k] k+=1 l+=1 for f in range(len(temp)): arr[f]=temp[f]
true
79b9fc5558697729e6605a329b46c3055c904232
parkerjgit/algorithms
/python/recursion_and_dynamic/find_magic.py
1,836
4.125
4
""" question: A magic index in an array A [1... n-1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. follow up: What if the values are not distinct? source: McDowell, Gayle Laakmann., Cracking the Coding Interview: 189 Programming Questions and Solutions 6th Edition (2015) 346. """ def find_magic(arr): """ Solution: For given sorted distinct-valued array, the following conditions must be met for magic value to possibly exist: 1. the lowest value must be less than or equal to the lowest index. 2. the highest value must be greater than or equal to the highest index. If those conditions are met AND there is only one value, then it must be the magic index. Otherwise, recurse on left or right half of array if middle value is not magic. time: O(logn) - we are essentially searching a binary tree of depth log(n). space: O(1) - by passing input array down recursion stack search uses constant aux space """ def find(arr, lo, hi): # base cases if arr[lo] > lo: return None if arr[hi] < hi: return None if lo == hi: return lo # must be more than 1 item, so find middle mid = lo + ((hi - lo) // 2) # recurse left or right if not mid if arr[mid] == mid: return mid elif arr[mid] > mid: return find(arr, lo, mid-1) else: return find(arr, mid+1, hi) return find(arr, 0, len(arr)-1) """ test """ if __name__ == '__main__': assert find_magic([0, 2, 3, 5, 6, 7, 9]) == 0 assert find_magic([-1, 1, 3, 5, 6, 7, 9]) == 1 assert find_magic([-3, -1, 2, 5, 6, 7, 9]) == 2 assert find_magic([-3, -2, -1, 0, 3, 4, 6]) == 6
true
46c9f8a9df75d208ef8afab334ba1d0384a535ab
parkerjgit/algorithms
/python/arrays_and_strings/spiral_ordering.py
1,668
4.375
4
""" question: Write a program which takes an n x n 2d array and returns the spiral ordering. For example, the following 2d array representation of 3 x 3 matrix has spiral ordering is [1,2,3,6,9,8,7,4,5] [[1 2 3] [4 5 6] [7 8 9]] source: EPI 5.18: compute the spiral ordering of a 2d array """ def spiral_ordering(matrix): """ Solution: todo... :param matrix: :return: """ # size of matrix n = len(matrix) def _get_layer_at_depth(i): # size of sub matrix m = n - 2 * i # sides of sub-matrix in clockwise order (non-overlapping) top = matrix[i][i: i + m - 1] right = [row[i + m - 1] for row in matrix[i: i + m - 1]] bottom = list(reversed(matrix[i + m - 1][i + 1: i + m])) left = [row[i] for row in reversed(matrix[i + 1: i + m])] return top + right + bottom + left # get the spiral ordering from depth i inward recursively. def _get_layers_from_depth(i): # size of sub matrix m = n - 2 * i # odd number of layers, return middle cell. if (m == 1): return [matrix[i][i]] # even number of layers. done. if (m == 0): return [] return _get_layer_at_depth(i) + _get_layers_from_depth(i + 1) return _get_layers_from_depth(0) # test def test_spiral_ordering(): assert spiral_ordering( [[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [1, 2, 3, 6, 9, 8, 7, 4, 5] assert spiral_ordering( [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) == [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
true
73fd482e924db7add582a93cf09e84c92397d36a
parkerjgit/algorithms
/python/recursion_and_dynamic/recursive_multiply.py
1,162
4.40625
4
""" question: Write a recursive function to multiply two positive integers without using the * operator (or / operator). You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations. source: McDowell, Gayle Laakmann., Cracking the Coding Interview: 189 Programming Questions and Solutions 6th Edition (2015) 350. """ import math def recursive_multiply(multiplier, multiplicand): """ multiply two integers recursively """ # base cases if multiplier == 0: return 0 if multiplier == 1: return multiplicand # subdivide multiplier by largest power of 2 n = math.floor((math.log(multiplier, 2))) # update multiplier as remaining remaining = multiplier - (1 << n) # calculate partial products p1 = (multiplicand << n) p2 = recursive_multiply(remaining, multiplicand) # return sum of partial products return p1 + p2 def multiply(a, b): """ multiply two integers using recursive helper function """ return recursive_multiply(min(a, b), max(a, b)) if __name__ == '__main__': assert multiply(15000000000,30000000000) == 450000000000000000000
true
945259dc4b0e279ef3a56874451f3ba04caecde1
Analova/Python
/classes2.py
931
4.15625
4
class Vehicle: def __init__(self,wheels,windows,seat): self.wheels=wheels self.windows=windows self.seats=seat def printWheels(self): print(f"This vehicles has {self.wheels} wheels") return self.wheels class Car(Vehicle): def __init__(self,model,maker,wheels,windows,seats): super().__init__(wheels,windows,seats) self.model=model self.maker=maker def __repr__(self): return f"This is a car by {self.maker} with wheels:{self.wheels}" class Motor(Vehicle): def __init__(self,model,maker,wheels,windows,seats): super().__init__(wheels,windows,seats) self.model=model self.maker=maker def __repr__(self): return f"This is a Motorcycle by {self.maker}" car1=Car( "GL359","Benz", 4, 6,5) motor1=Motor("SP1000", "BMW", 2, 1,2) # print(car1.printWheels()) # print(motor1.printWheels()) print(car1)
false
a2ff84ab15d397091c0ab8168c5fd52a03c84e1a
linhaidong/linux_program
/container_ssl/python_test/pytool-master/datastruct/byte-to-hex.py
1,472
4.25
4
# coding=utf-8 """ handle byte string and hex. :copyright: (c) 2016 by fangpeng(@beginman.cn). :license: MIT, see LICENSE for more details. """ import struct def byte_string_to_hex(bstr): """ Convenience method for converting a byte string to its hex representation `%02x` means print at least 2 digits, prepend it with 0's if there's less. pythond standlib: >>>import binascii >>>binascii.a2b_hex() ref:https://github.com/BeginMan/pythonStdlib/blob/master/binascii.md """ if not isinstance(bstr, str): bstr = bstr.encode("utf-8") return ''.join(['%02x' % i for i in struct.unpack('%iB' % len(bstr), bstr)]) def byte_string_from_hex(hstr): """ Convenience method for converting a byte string from its hex representation pythond standlib: >>>import binascii >>>binascii.b2a_hex() """ byte_array = [] # Make sure input string has an even number of hex characters # (2 hex chars = 1 byte). Add leading zero if needed. if len(hstr) % 2: hstr = '0' + hstr for obj in range(0,len(hstr), 2): byte = int(hstr[obj: obj+2], 16) byte_array.append(byte) return ''.join(struct.pack('%iB' % len(byte_array), *byte_array)) if __name__ == "__main__": s2 = u'中国' t = byte_string_to_hex(s2) print byte_string_from_hex(t) # In the same way, set `%x` to `%o` and set `int(xx, 16)` to `int(xx, 8)` # we can get methods to handle Octal
true
68c33e392aee74af93debfb7f77db08ceb1a1885
linhaidong/linux_program
/container_ssl/python_test/pytool-master/iterator_and_generators/delegating_iteration.py
810
4.15625
4
# coding=utf-8 """ 代理迭代 在任何可迭代对象中执行迭代操作只需要定义一个 __iter__() 方法,将迭代操作代理到容器内部的对象上去 :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/9/16' class Node(object): def __init__(self, name): self.name = name self._children = [] def __repr__(self): return '<Node: %r>' % self.name def __iter__(self): # 将迭代请求传递给内部的 _children 属性。 return iter(self._children) def __add__(self, other): self._children.append(other) root = Node('root') child_a = Node('a') child_b = Node('b') root + child_a root + child_b for obj in root: print obj # outputs: # <Node: 'a'> # <Node: 'b'>
false
0e50150116b7e238267f024f6e645593314b0cf3
anagrzesiak/metody-numeryczne
/metody geometryczne całkowania.py
1,416
4.21875
4
def function(x): f = x * x # f = 2 * x + 3 # f = 4 ** x - x return f def print_function(): s = "y = x^2" # s = "y = 2x + 3" # s = "y = 4^x - x" return s def rectangle(first_interval, second_interval, intervals_number): step = (second_interval - first_interval) / intervals_number integral = 0 for i in range(intervals_number): integral += step * function(first_interval + (i - 1) * step) return integral def trapezoid(first_interval, second_interval, intervals_number): step = (second_interval - first_interval) / intervals_number integral = 0.5 * (function(first_interval) + function(second_interval)) for i in range(intervals_number): integral += function(first_interval + step * i) integral *= step return integral f_interval: float = float(input("ENTER THE BEGINNING OF THE INTERVAL: ")) s_interval: float = float(input("ENTER THE END OF THE INTERVAL: ")) i_number: int = int(input("ENTER THE NUMBER OF INTERVALS (NUMBER OF ITERATIONS): ")) print("FUNCTION: ", print_function()) print("The given interval is [%s, %s]" % (f_interval, s_interval)) print("The given number of intervals (number of iterations) is", i_number) print("Rectangular method: ", rectangle(f_interval, s_interval, i_number)) print("Trapezoidal method: ", trapezoid(f_interval, s_interval, i_number))
true
4d1d00edc6e48c39f0de1ecc68b2cbe4f01d823d
hamburgcodingschool/L2C-Python-1804
/Lesson 3/01_prime_numbers.py
463
4.15625
4
number = 8 # this will change to input later test = 2 divCounter = 0 while test < number: if number % test == 0: print("{} is a divisor of {}".format(test, number)) divCounter = divCounter + 1 else: print("{} is NOT a divisor of {}".format(test, number)) test = test + 1 print("-------------") if divCounter == 0: print("{} is a prime number".format(number)) else: print("{} is NOT a prime number".format(number))
true
b036c5af73ebad770ab6fa8814a50bfa16a4910e
ebaek/Data-Structures-Algorithms
/LeetCode/right_side_view.py
1,334
4.28125
4
# 199. Binary Tree Right Side View # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Given a binary tree, imagine yourself standing on the right side of it, # return the values of the nodes you can see ordered from top to bottom. # Example: # Input: [1,2,3,null,5,null,4] # Output: [1, 3, 4] # Explanation: # 1 <--- # / \ # 2 3 <--- # \ \ # 5 4 <--- # Approach: BFS and for each level replace the value if value exists with value of node, # otherwise, create a key with the value pointing to the nodes value # iterate through the values of the dictionary and append the values to a list from collections import deque class Solution: def rightSideView(self, root: TreeNode) -> List[int]: if not root: return [] q = deque([(root, 0)]) dict = {} while q: node, level = q.popleft() dict[level] = node.val if node.left: q.append((node.left, level+1)) if node.right: q.append((node.right, level+1)) rightSides = [] for nodeVal in dict.values(): rightSides.append(nodeVal) return rightSides
true
06bff8aa71117b81e9e9af72e326b2468a6656e4
ebaek/Data-Structures-Algorithms
/LeetCode/validate_bst.py
2,224
4.125
4
# 98: Validate Binary Search Tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Given a binary tree, determine if it is a valid binary search tree (BST). # Assume a BST is defined as follows: # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the left and right subtrees must also be binary search trees. # 2 # / \ # 1 3 # Input: [2,1,3] # Output: true # Approach: Post Order because checking left child and right child before root # Check if only left child: max would be root value # Check if only right child: min would be root value # If not children check if min < root value < max # Recursive Approach class Solution: def isValidBST(self, root: TreeNode) -> bool: def helper(root, Min, Max): if root is None: return True if not root.left and not root.right: if Min < root.val < Max: return True else: return False # only right leaf if not root.left and root.right: return root.val < root.right.val and helper(root.right, root.val, Max) # only left leaf elif root.left and not root.right: return root.val > root.left.val and helper(root.left, Min, root.val) # both right and left leaves else: return root.left.val < root.val < root.right.val and helper(root.left, Min, root.val) and helper(root.right, root.val, Max) return helper(root, float('-inf'), float('inf')) class Solution: def isValidBST(self, root: TreeNode) -> bool: stack = [(root, float("-inf"), float("inf"))] while stack: root, Min, Max = stack.pop() if root: if not (Min < root.val < Max): return False stack.append((root.left, Min, root.val)) stack.append((root.right, root.val, Max)) return True
true
cffff0ea8d75e775c07a0682d04dd07e67e1331d
Jivitesh2001/Hangman_Game
/main.py
1,281
4.1875
4
#Step 5 import random import hangman_art #OR WE CAN Use #from hangman_art import word_list import hangman_words #OR WE CAN Use #from hangman_words import stages chosen_word = random.choice(hangman_words.word_list) word_length = len(chosen_word) end_of_game = False lives = 6 print(hangman_art.logo) display = [] for _ in range(word_length): display += "_" guesslist=[] while not end_of_game: guess = input("Guess a letter: ").lower() if guess in chosen_word: if guess in guesslist: print(f"You have already guessed {guess}") for position in range(word_length): letter = chosen_word[position] if letter == guess: display[position] = letter guesslist+=guess #Check if user is wrong. if guess not in chosen_word: print(f"You guessed {guess}, thats not int the word. You lose a life.") lives -= 1 if lives == 0: end_of_game = True print("You lose.") #Join all the elements in the list and turn it into a String. print(f"{' '.join(display)}") #Check if user has got all letters. if "_" not in display: end_of_game = True print("You win.") print(hangman_art.stages[lives])
true
4162bdeaca889a730fca4aecd92f800f9b077f7c
mariia-iureva/python_crash_course
/name_cases.py
421
4.15625
4
name = "John" message = f"Hi, {name}, how is Python study going?" print(message) name2 = "mersedez" print(name2.title()) print(name2.lower()) print(name2.upper()) famous_name = "Alexandr Pushkin" quote = "Надежды юношей питают" message2 = f'{famous_name} once wrote,"{quote}."' print(message2) name3 = " John Dow " print(name3) print(name3.lstrip()) print(name3.rstrip()) print(name3.strip())
false
56ce05a4b94e105c81d217504a66c07cc0450dd2
pratik-chaudhari-883/problem-statments-on-python
/prog3.py
299
4.46875
4
#Program to print reverse order numbers on screen. def PrintNumbers(iNo): while iNo!=0: print("",iNo) iNo=iNo-1 def main(): print("Enter number to print in reverse order") iValue=int(input()) ret=PrintNumbers(iValue) if __name__ =="__main__": main()
true
a72e4cb42cbf882dac80098ab94bb21017220c0d
RonjasJ/rj
/kthsmallnum.py
307
4.1875
4
num_arr = list() number = input("Enter the number of elements you want:") print ('Enter numbers in array: ') for i in range(int(number)): n = int(input("number :")) num_arr.append(int(n)) print ('ARRAY: ',num_arr) num_arr.sort() k = int(input("Enter the kth number")) print ('element',num_arr[k-1])
true
6a7db4a502b571c7563ca509e1b81771fe99d115
cole-k/advent-of-code-2017
/original/3_1.py
1,502
4.125
4
import sys import math def spiral_memory(num): sqrt = math.floor(math.sqrt(num)) # Find the first odd square less than the number first_odd_square = sqrt - ((sqrt % 2) == 0) # We will traverse the spiral starting from the coordinates of this odd # square. start = (first_odd_square - 1)/2 x, y = start, -start # The number at (x,y) is the odd number squared. We will traverse past it # until we reach num. num -= first_odd_square**2 # Debug print statements. # print(x,y) # print('num: {}, first_odd_square: {}'.format(num, first_odd_square)) if num: # The first traversal is moving 1 unit to the right. x += 1 num -= 1 if num: # The next traversal is moving odd_square units up. diff = min(first_odd_square, num) y += diff num -= diff if num: # The third traversal is moving odd_square + 1 units to the left. diff = min(first_odd_square + 1, num) x -= diff num -= diff if num: # The fourth traversal is moving odd_square + 1 units down. diff = min(first_odd_square + 1, num) y -= diff num -= diff if num: # The final traversal is moving odd_square units to the right. diff = min(first_odd_square, num) x += diff num -= diff return abs(x) + abs(y) while True: try: inp = int(input('Integer: ')) print(spiral_memory(inp)) except: exit(0)
true
a9c90972c7da997f4467002cbd912404ae541326
ReadMyCourseOfficial/PythonForBeginnersStudyMaterials
/codes/Day9/school_database.py
549
4.1875
4
#application of list students=["Anand","Pankaj","Manoj"] # student_to_check=input("please enter the student name to check:") # is_student_present=student_to_check in students # print(is_student_present) # stundent_to_store=input("please enter the student name") # students.append(stundent_to_store) # print(students) #to get only unique students in the database students=["Anand","Pankaj","Manoj","Manoj"] print("Our school database is ",students) unique_students=set(students) print("Unique students present in the databse is: ",unique_students)
true
aa3e685b8ee676dd869564d629c500420aa3e6a2
ReadMyCourseOfficial/PythonForBeginnersStudyMaterials
/codes/Day10/elif_example.py
824
4.1875
4
# if <condition1>: # #do something if the condition1 is true # elif <condition2>: # #do something if the condition2 is true and condition1 is false # else: # #do if condition1 and condition2 are false # marks #<80 C grade # >80 and <90: B # >90 and <95: A # >95: A+ # marks=int(input("please enter the marks: ")) # if marks>95: # print("A+ grade") # elif marks>90 and marks<95: # print("A grade") # elif marks>80 and marks<90: # print("B grade") # else: # print("C grade") students={ "Anand":78, "Mohit":52, "Shreya":99 } student_name=input("please enter the student name") marks=students[student_name] if marks>95: print("A+ grade") elif marks>90 and marks<95: print("A grade") elif marks>80 and marks<90: print("B grade") else: print("C grade") if
false