blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
44be8c3c7f6920bdb8329af683afa045634d682e
ajakaiye33/pythonic_daily_capsules
/concatenate_string.py
602
4.34375
4
def concatenate_string(stringy1, stringy2): """ A function that receives two strings and returns a new one containing both strings cocatenated """ return "{} {}".format(stringy1, stringy2) print(concatenate_string("Hello", "World")) print(concatenate_string("Hello", "")) # some other way... def concatenate_string(string1, stringy2): """ A function that receives two strings and returns a new one containing both strings cocatenated """ return string1 + " " + stringy2 print(concatenate_string("Hello", "World")) print(concatenate_string("Hello", ""))
true
7ba818effcd4db9905ca6814f4679184224e9d27
ajakaiye33/pythonic_daily_capsules
/color_mixer.py
970
4.25
4
def color_mixer(color1, color2): """ Receives two colors and returns the color resulting from mixing them in EITHER ORDER. The colors received are either "red", "blue", or "yellow" and should return: "Magenta" if the colors mixed are "red" and "blue" "Green" if the colors mixed are "blue" and "yellow" "Orange" if the color mixed are "yellow" and "red" """ if (color1 == "red" and color2 == "blue") | (color2 == "red" and color1 == "blue"): res = "Magenta" elif (color1 == "blue" and color2 == "yellow") | (color2 == "blue" and color1 == "yellow"): res = "Green" elif (color1 == "yellow" and color2 == "red") | (color2 == "yellow" and color1 == "red"): res = "Orange" return res print(color_mixer("red", "blue")) print(color_mixer("blue", "red")) print(color_mixer("blue", "yellow")) print(color_mixer("yellow", "red")) print(color_mixer("red", "yellow")) print(color_mixer("yellow", "blue"))
true
195b3d1288769e60d0aa6d0023f308a6e0675523
ajakaiye33/pythonic_daily_capsules
/make_number_odd.py
288
4.25
4
def make_number_odd(num): """ Receives a number, adds 1 to that number if it's even and returns the number if the original number passed is odd, just return it """ if num % 2 == 0: num += 1 return num print(make_number_odd(2)) print(make_number_odd(5))
true
d46bd897ee359b69d2f3fc29d7d6803883590c23
rhydermike/PythonPrimes
/primes.py
1,641
4.40625
4
#Prime number sieve in Python MAXNUMBER = 1000 #Total number of numbers to test results = [] #Create list to store the results for x in range (1,MAXNUMBER): #Begin outer for loop to test all numbers between 1 and MAXNUMBER isprime = True #Set boolean variable isprime to True for y in range (2, x - 1): #Begin inner for loop. The divisiors shall be every number between (but not including) 1 and the number itself if x % y == 0: #Check to see if the remainder of x divided by y is 0. If so, carry out next bit of code. isprime = False #If so, set isprime to False. It's not a prime, in other words. break #Break out of the loop if the number isn't prime. There's no point of continuing to test this number. if isprime == True: #Following the tests, if x/y was never found to have a remainder of 0, set isprime to True results.append(x) #If so, add the prime number to the list message = str(x) + " is a prime"; #Create notification string that current number is prime print (message) #Print notification that current number is prime def show_results(): #Define a funtion to show the results print ("The complete list of primes between 1 and "+str(MAXNUMBER)) # Print text explaining what the list is for x in results: #Begin a for loop that visits every result in the list print (x), #Print current entry in the list show_results() #Call the function that shows the results that are stored in the list
true
7a02905d8b244c6e96eb871ff8099d6c0db26e03
SamJ2018/LeetCode
/python/python语法/pyexercise/Exercise04_11.py
1,309
4.125
4
# Prompt the user to enter input month = eval(input("Enter a month in the year (e.g., 1 for Jan): ")) year = eval(input("Enter a year: ")) numberOfDaysInMonth = 0; if month == 1: print("January", year, end = "") numberOfDaysInMonth = 31; elif month == 2: print("February", year, end = "") if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): numberOfDaysInMonth = 29; else: numberOfDaysInMonth = 28; elif month == 3: print("March", year, end = "") numberOfDaysInMonth = 31; elif month == 4: print("April", year, end = "") numberOfDaysInMonth = 30; elif month == 5: print("May", year, end = "") numberOfDaysInMonth = 31; elif month == 6: print("June", year, end = "") numberOfDaysInMonth = 30; elif month == 7: print("July", year, end = "") numberOfDaysInMonth = 31; elif month == 8: print("August", year, end = "") numberOfDaysInMonth = 31; elif month == 9: print("September", year, end = "") numberOfDaysInMonth = 30; elif month == 10: print("October", year, end = "") numberOfDaysInMonth = 31; elif month == 11: print("November", year, end = "") numberOfDaysInMonth = 30; else: print("December", year, end = "") numberOfDaysInMonth = 31; print(" has", numberOfDaysInMonth, "days")
true
be6bed1c6c15377c1bd5d78c321d8413fcb85bf5
SamJ2018/LeetCode
/python/python语法/pyexercise/Exercise06_17.py
643
4.28125
4
import math def main(): edge1, edge2, edge3 = eval(input("Enter three sides in double: ")) if isValid(edge1, edge2, edge3): print("The area of the triangle is", area(edge1, edge2, edge3)) else: print("Input is invalid") # Returns true if the sum of any two sides is # greater than the third side. def isValid(side1, side2, side3): return (side1 + side2 > side3) and \ (side1 + side3 > side2) and (side2 + side3 > side1) # Returns the area of the triangle. def area(side1, side2, side3): s = (side1 + side2 + side3) / 2 return math.sqrt(s * (s - side1) * (s - side2) * (s - side3)) main()
true
5a326e8c133c4fb3fc2d0581f1c8d6c7feb72376
Ayman-M-Ali/Mastering-Python
/Assignment_015.py
2,725
4.15625
4
#-------------------------------------------------------- # Assignment (1): # Write the following code to test yourself and do not run it # After the last line in the code write a comment containing the Output that will come out from your point of view # Then run Run to see your result sound or not # Make a comment before each of the lines in the code to explain how this result appeared #-------------------------------------------------------- # var => Type of value is Tuple values = (0, 1, 2) # if statement : any of values is True: if any(values): # Create new var => give value => Zero my_var = 0 # Create List That contains True Type Element my_list = [True, 1, 1, ["A", "B"], 10.5, my_var] # If All values into List (with Index) Is True : if all(my_list[:4]) or all(my_list[:6]) or all(my_list[:]): # Give Result "Good" print("Good") else: # Give Result "Bad" print("Bad") # The result is Good print("##### End Assignment (1) #####") #------------------------------------------------------- # Assignment (2): # What is the value of v that causes the print to output the number 820 #------------------------------------------------------- v = 40 my_range = list(range(v)) print(sum(my_range, v) + pow(v, v, v)) # 820 print("##### End Assignment (2) #####") #------------------------------------------------------- # Assignment (3): # What is the value of the variable n #------------------------------------------------------- n = 20 l = list(range(n)) if round(sum(l) / n) == max(0, 3, 10, 2, -100, -23, 9): print("Good") print("##### End Assignment (3) #####") #------------------------------------------------------- # Assignment (4): # Create a function that does the same thing as all and call it my_all # Create a function that does the same as any and call it my_any # Create a function that does the same as the min and call it my_min # Create a function that does the same as the max and call it my_max # Make sure my_min + my_max accepts List or Tuple #------------------------------------------------------- # func all() def my_all(nums): for n in nums : if not n : return False return True print(my_all([1, 2, 3])) print(my_all([1, 2, 3, []])) # func any() def my_any(nums): for n in nums : if n : return True return False print(my_any([1, 2, 3])) print(my_any([0, (), False, []])) # func min() def my_min(nums): for n in nums : if n == min(nums): return n print(my_min([1, 2, 3, -10, -100])) print(my_min((1, 2, 3, -10, -100))) # func max() def my_max(nums) : for n in nums : if n == max(nums) : return n print(my_max([10, 20, -50, 700])) print(my_max((10, 20, -50, 700)))
true
694a06ab8f7ca681fb5b16f273cb2be1f725abbd
Lydia-Li725/python-basic-code
/排序.py
369
4.1875
4
def insertion_sort(array): for index in range(1,len(array)): position = index temp_value = array[index] while position > 0 and array[position - 1] > temp_value: array[position] = array[position-1] position -= 1 array[position] = temp_value return array a = [1,7,6,3,2,4] print(insertion_sort(a))
true
acbf854d06bfa1e458cf65cca8af844fb40cd094
swavaldez/python_basic
/01_type_and_statements/04_loops.py
620
4.21875
4
# student_names = [] student_names = ["Mark", "Katarina", "Jessica", "Sherwin"] print(len(student_names)) # for loops for name in student_names: print("Student name is {0}".format(name)) # for range x = 0 for index in range(10): x += 10 print("The value of x is {0}".format(x)) # start in 5 and ends in 9 for index in range(5, 9): x += 10 print("The value of x is {0}".format(x)) # index increase by 2 for index in range(5, 9, 2): x += 10 print("The value of x is {0}".format(x)) for index in range(len(student_names)): print("Student name is {0}".format(student_names[index]))
true
a1ba2026687b109cdd7c72113cc222d4cffdd804
cassandraingram/PythonBasics
/calculator.py
1,427
4.1875
4
# calculator.py # Cassie Ingram (cji3) # Jan 22, 2020 # add function adds two inputs def add(x, y): z = x + y return z #subtract function subtracts two inputs def subtract(x, y): z = x - y return z # multiply function multiplies two inputs def multiply(x, y): z = x * y return z # divide function divides two inputs def divide(x, y): z = x / y return z # modulee calls each function using the numbers 47 and 7 and # then prints the results of each function a = add(47, 7) print("47 + 7 = {}" .format(a)) s = subtract(47, 7) print("47 - 7 = {}" .format(s)) m = multiply(47, 7) print("47 * 7 = {}" .format(m)) d = divide(47, 7) print("47 / 7 = {}" .format(d)) ###### additional practice # prompt user to enter two numbers and the operation they # want to perform n1, n2, opp = input("Enter two integers and an operation, separated by a comma: ").split(", ") # converet input numbers to integer type variables n1 = int(n1) n2 = int(n2) # perform action based on what was entered if opp == "add": solution = add(n1, n2) print("{} + {} = {}" .format(n1, n2, solution)) elif opp == "subtract": solution = subtract(n1, n2) print("{} - {} = {}" .format(n1, n2, solution)) elif opp == "multiply": solution = multiply(n1, n2) print("{} * {} = {}" .format(n1, n2, solution)) elif opp == "divide": solution = divide(n1, n2) print("{} / {} = {}" .format(n1, n2, solution)) else: print("Not a valid operation.")
true
9527efcef31dba3ca25ec33f2115ebfc5ec1d53a
snowpuppy/linux_201
/python_examples/example1/guessnum.py
855
4.21875
4
#!/usr/bin/env python #Here we import the modules we need. import random random.seed() #We need to seed the randomizer number = random.randint(0,100) #and pull a number from it. trys = 10 #We're only giving them 10 tries. guess = -1 #And we need a base guess. while guess != number and trys != 0: #So, we need to let them guess if they haven't guessed and if they have tries left guess = int(raw_input("Guess a number from 0 to 100: ")) #Get the input from them. if guess < number: #Yell at them that they're wrong. print "Guess Higher!" elif guess > number: print "Guess Lower!" trys = trys - 1 #Decrease the number of tries. if guess == number: #Once we break out of the while, if they were right, tell them so, otherwise tell them they were wrong. print "Congratulations! You guessed correcty!" else: print "The answer was " + number
true
26f06216b4cf66c2bb236dccb89ae7cf0d7b2713
rchristopfel/IntroToProg-Python-Mod07
/Assignment07.py
2,304
4.125
4
# ------------------------------------------------------------------------ # # Title: Assignment 07 # Description: using exception handling and Python’s pickling module # ChangeLog (Who,When,What): # Rebecca Christopfel, 11-18-19, test pickle module # Rebecca CHristopfel, 11-20-19, create try/except block for script # ------------------------------------------------------------------------ # # Pickling Example # To store user demographic data import pickle # create some data to be pickled strFirstName = str(input("Enter your first name: ")) strLastName = str(input("Enter your last name: ")) strAge = str(input("Enter your age: ")) strNumber = str(input("Enter your phone number: ")) demoData = [strFirstName, strLastName, strAge, strNumber] print(demoData) # store the data with the pickle.dump method file = open("Demo.dat", "ab") pickle.dump(demoData, file) file.close() # read the data back with the pickle.load method file = open("Demo.dat", "rb") fileData = pickle.load(file) file.close() print(fileData) # Exception Handling # To show calculation of age in years (and fraction of years) based on user's birthday print("\n_____________________________________\n") print("Now we'll do the exception handling...\n") print("_____________________________________\n") import datetime today = datetime.date.today() userBirthMonth = 0 userBirthDay = 0 userBirthYear = 0 while 1 > userBirthMonth or 12 < userBirthMonth: try: userBirthMonth = int(input("\nEnter your birth month (1-12): ")) except ValueError: print("Oops! That is not a valid number. Try 1-12...") while 1 > userBirthDay or 31 < userBirthDay: try: userBirthDay = int(input("\nEnter your birth day (1-31): ")) except ValueError: print("Oops! That is not a valid number. Try 1-31...") while True: try: userBirthYear = int(input("\nEnter your birth year: ")) break except ValueError: print("Oops! That is not a valid number. Try format (yyyy) ...") userBirthDate = datetime.date(userBirthYear, userBirthMonth, userBirthDay) dateDiff = (today - userBirthDate) userAge = round(float(dateDiff.days / 365.25), 2) print("\n\tRounding to the nearest hundredth of a decimal, you are " + str(userAge) +" years old!")
true
919d4323cdb5dd99e5aff75710d00fe279bbf712
XavierKoen/lecture_practice_code
/guessing_game.py
254
4.125
4
question = input("I'm thinking of a number between 1 and 10, what is it? ") ANSWER = '7' print(question) while question != ANSWER: question = input("Oh no, please try again. ") print (question) print("Congrtulations! You were correct, it was 7!")
true
1a8f986972d5f0ec326aaeb3f901cc259bf47ecd
XavierKoen/lecture_practice_code
/name_vowel_reader.py
786
4.125
4
""" Asks user to input a name and checks the number of vowels and letters in the name. """ def main(): name = input("Name: ") number_vowels = count_vowels(name) number_letters = count_letters(name) print("Out of {} letters, {}\nhas {} vowels".format(number_letters, name, number_vowels)) def count_vowels(string): number_of_vowels = 0 vowels = "AaEeIiOoUu" for char in string: if char in vowels: number_of_vowels = number_of_vowels + 1 return number_of_vowels def count_letters(string): number_of_letters = 0 letters = "abcdefghijklmnopqrstuvwxyz" string = string.lower() for char in string: if char in letters: number_of_letters = number_of_letters + 1 return number_of_letters main()
true
04cb412cecc6d49bd15ebde03cc729f51d1e19aa
milanvarghese/Python-Programming
/Internshala/Internshala Assignments/W5 Assignment - Connecting to SQLite Database/insert_data.py
1,124
4.28125
4
#Importing Necessary Modules import sqlite3 #Establishing a Connection shelf=sqlite3.connect("bookshelf.db") curshelf=shelf.cursor() #Creating a table with error check try: curshelf.execute('''CREATE TABLE shelf(number INT PRIMARY KEY NOT NULL ,title TEXT NOT NULL, author TEXT STRING, price FLOAT NOT NULL);''') shelf.commit() print("Table Created SUCCESSFULLY!") except: print("ERROR in Creating a New Table!") shelf.rollback() cont="y" #Accepting the variables from the USER while cont=="y": number=input("Enter Book Index: ") title=str(input("Title: ")) author=str(input("Author: ")) price=int(input("Price: ")) #Inserting the values into the records try: curshelf.execute("INSERT INTO shelf(number,title,author,price) VALUES(?,?,?,?)",(number,title,author,price)) shelf.commit() print("Record ADDED SUCCESSFULLY!") except: print("ERROR in INSERT query!") shelf.rollback() cont=input("Add More Records? Y/N: ") if cont=="n" or cont=="N": print("DATA Entry Complete") break; #Closing the Connection shelf.close()
true
dc73601bced9a16c9b52abdb42a53b04df5da287
Ktheara/learn-python-oop
/advaced-review/2.tuple.py
959
4.5625
5
# A tuple is a collection of objects which is ordered and immutable(unchangeable). # https://www.python-engineer.com/courses/advancedpython/02-tuples/ # So similar to list but elements are protected mytuple = ('a', 'p', 'p', 'l', 'e') #create a tuple print(mytuple) # number of elements print(len(mytuple)) # number of x element print(mytuple.count('p')) # index of first item that equal to x print(mytuple.index('p')) # repetition yourtuple = ('a', 'b') * 5 print('Your tuple is :', yourtuple) # concatenation ourtuple = mytuple + yourtuple print('Our tuple is: ', ourtuple) # convert list to tuple mylist = ['a', 'b', 'c', 'd'] list2tuple = tuple(mylist) print('Converted list to tuple: ', list2tuple) # convert string to tuple str2tuple = tuple("Hello") print('Converted string to tuple: ', str2tuple) # unpacke tuple myinfo = ('Theara', 25, 'Mechatronics Engineer') name, age, job = myinfo print('Name: ', name, ' age: ', age, ' and job: ', job)
true
d7948b4af779d68ed87af1d832c4cf6c558ec274
cuongv/LeetCode-python
/BinaryTree/PopulatingNextRightPointersInEachNode.py
2,802
4.21875
4
#https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ """ You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Follow up: You may only use constant extra space. Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem. Example 1: Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. Constraints: The number of nodes in the given tree is less than 4096. -1000 <= node.val <= 1000 #Solution 1: BFS travel tree by levels -> O(n) #Solution 2: We only move on to the level N+1 when we are done establishing the next pointers for the level N. Since we have access to all the nodes on a particular level via the next pointers, we can use these next pointers to establish the connections for the next level or the level containing their children. # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ from collections import deque class Solution(object): #O(1) solution def connect(self, root): if not root: return None leftMost = root node = leftMost while leftMost.left: node.left.next = node.right if node.next: node.right.next = node.next.left node = node.next else: leftMost = leftMost.left node = leftMost return root #My O(n) solution """ def connect(self, root): if not root: return None q = deque([root]) while q: prev = None count = len(q) for i in range(count): node = q.popleft() if prev: prev.next = node prev = node if node.left: q.append(node.left) q.append(node.right) prev = None return root """ """ :type root: Node :rtype: Node """
true
1dfcc2fe5bcac12d235391d073b5991fca58960b
sudhamshu091/Daily-Dose-of-Python-Coding
/Qsn_21/string_punctuation.py
232
4.25
4
from string import punctuation string = "/{Python @ is actually an > interesting //language@ " replace = '#' for char in punctuation: string = string.replace(char, replace) print("String after replacement is: ", string)
true
88fa596a897959b76862605be56a153b606f4555
devil-cyber/Data-Structure-Algorithm
/tree/count_node_complete_tree.py
643
4.125
4
from tree import Tree def height_left(root): hgt = 0 node = root while node: hgt += 1 node = node.left return hgt def height_right(root): hgt = 0 node = root while node: hgt += 1 node = node.right return hgt def count_node(root): if root is None: return 0 lh = height_left(root) rh = height_right(root) if rh==lh: return (1 << rh) -1 return 1 + count_node(root.left) + count_node(root.right) if __name__ == "__main__": t = Tree() root = t.create_tree() print('the number of node in complete binary tree is:', count_node(root))
true
9179d31d9eeda1d0767924c0714b62e22875fb34
MeeSeongIm/trees
/breadth_first_search_02.py
611
4.1875
4
# find the shortest path from 1 to 14. # graph in list adjacent representation graph = { "1": ["2", "3"], "2": ["4", "5"], "4": ["8", "9"], "9": ["12"], "3": ["6", "7"], "6": ["10", "11"], "10": ["13", "14"] } def breadth_first_search(graph, start, end): next_start = [(node, path + "," + node) for i, path in start if i in graph for node in graph[i]] for node, path in next_start: if node == end: return path else: return breadth_first_search(graph, next_start, end) print(breadth_first_search(graph, [("1", "1")], "14"))
true
21ef42736c7ef317b189da0dc033ad75615d3523
LiloD/Algorithms_Described_by_Python
/insertion_sort.py
1,505
4.1875
4
import cProfile import random ''' this is the insertion sort Algorithm implemented by Python Pay attention to the break condition of inner loop if you've met the condition(the key value find a place to insert) you must jump out of the loop right then Quick Sort is Moderately fast for small input-size(<=30) but weak for Large Input by Zhizhuo Ding ''' class InsertionSort: "Algorithm---Insertion Sort" @staticmethod def execute(array): array = list(array) for i in xrange(1,len(array)): key = array[i] for j in range(0,i)[::-1]: if key < array[j]: array[j+1] = array[j] if key >= array[j]: array[j+1] = key break #return carefully at a right place return array @staticmethod def execute_ver2(array): '''donot use the additional key value, all elements in array rearrange where they're fairly effient in its usage of storage ''' array = list(array) for i in xrange(1,len(array)): for j in range(0,i)[::-1]: ''' here,because that we don't use additional varible to keep the key(which is array[i] on the beginning) the value will change in this case so we can only compare array[j+1] with array[j] not compare array[i] with [array[j]] ''' if array[j+1] < array[j]: array[j],array[j+1] = array[j+1],array[j] return array if __name__ == "__main__": list1 = [] for i in xrange(0,10000): list1.append(random.randint(0,10000)) cProfile.run("list1 = InsertionSort.execute_ver2(list1)", None, -1) print list1
true
bedf86dafe10f5dc96b2ebd355040ab2fdfbd469
jpacsai/MIT_IntroToCS
/Week5/ProblemSet_5/Problem1.py
1,832
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 6 16:04:29 2018 @author: jpacsai """ def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). ''' newDict = {} lower = string.ascii_lowercase upper = string.ascii_uppercase for char in lower: shifted = ord(char)+shift if shifted > 122: shifted -= 26 newDict[char] = chr(shifted) for char in upper: shifted = ord(char)+shift if shifted > 90: shifted -= 26 newDict[char] = chr(shifted) return newDict def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' newDict = self.build_shift_dict(shift) newStr = '' for char in self.message_text: try: newStr += newDict[char] except KeyError: newStr += char return newStr
true
5902f17e71a3630344ab79f9c22ee2985cb80d3e
GorTIm/DailyCoding
/2020-01-17-Medium-Google-DONE.py
987
4.21875
4
""" This problem was asked by Google. You are given an array of nonnegative integers. Let's say you start at the beginning of the array and are trying to advance to the end. You can advance at most, the number of steps that you're currently on. Determine whether you can get to the end of the array. For example, given the array [1, 3, 1, 2, 0, 1], we can go from indices 0 -> 1 -> 3 -> 5, so return true. Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false. """ false_set=set() def toTheEnd(L,start_index): if start_index==len(L)-1: return True elif L[start_index]==0: return False elif start_index in false_set: return False else: for steps in range(1,L[start_index]+1): new_index=start_index+steps if toTheEnd(L,new_index): return True false_set.add(new_index) return False if __name__=="__main__": L=[1, 0, 1, 1, 0] print(toTheEnd(L,0))
true
8e0f519ea8d1c1fb701a718929fb35e1319c2faf
pemburukoding/belajar_python
/part002.py
2,128
4.40625
4
# Get input from console # inputString = input("Enter the sentence : ") # print("The inputted string is :", inputString) # Implicit Type # num_int = 123 # num_flo = 1.23 # num_new = num_int + num_flo # print("Value of num_new : ", num_new) # print("datatype of num_new : ", type(num_new)) # num_int = 123 # num_str = "456" # num_str = int(num_str) # print(num_int+num_str) # print(type(5)) # print(type(5.0)) # c = 5 + 3j # print(type(c)) # Create List # my_list = [] # my_list = [1, 2, 3] # my_list = [1, "Hello", 3.4] # language = ["French","German","English","Polish"] # print(language[3]) # Create Tupple # language = ("French","German","English","Polish") # String Operator # my_string = 'Hello' # print(my_string) # my_string = "Hello" # print(my_string) # my_string = '''Hello''' # print(my_string) # my_string = """Hello, welcome to the world of Python """ # print(my_string) # str = "programiz" # print('str = ', str) # print('str[0] = ',str[0]) # print('str[-1] = ',str[-1]) # print('str[1:5] = ',str[1:5]) # print('str[5:-2] = ',str[5:-2]) # str1 = 'Hello' # str2 = 'World!' # print(str1 + str2) # print(str1 * 3) # Create Sets # my_set = {1, 2, 3} # print(my_set) # my_set = {1.0, "Hello", (1,2,3)} # print(my_set) # my_set = {1,2,3} # my_set.add(4) # print(my_set) # my_set.add(2) # print(my_set) # my_set.add([3, 4, 5]) # print(my_set) # my_set.remove(4) # print(my_set) # A = {1, 2, 3} # B = {2, 3, 4, 5} # print(A | B) # print(A & B) # print(A - B) # print(A ^ B) # my_dict = {} # my_dict = {1 : 'apple', 2: 'ball'} # my_dict = {'name': 'John', 1 : [2, 4, 3]} # person = {'name': 'Jack', 'age' : 26, 'salary' : 4534.2} # person['age'] = 36 # print(person) # person['salary'] = 100 # print(person) # del person['age'] # print(person) # del person # Create Range # numbers = range(1, 6) # print(list(numbers)) # print(tuple(numbers)) # print(set(numbers)) # print(dict.fromkeys(numbers, 99)) numbers1 = range(1, 6, 1) print(list(numbers1)) numbers2 = range(1, 6, 2) print(list(numbers2)) numbers3 = range(5, 0, -1) print(list(numbers3))
true
639934c70afa23f042371ce06b3ed89fdd6245ca
baluneboy/pims
/recipes/recipes_map_filter_reduce.py
1,824
4.53125
5
#!/usr/bin/env python """Consider map and filter methodology.""" import numpy as np def area(r): """return area of circle with radius r""" return np.pi * (r ** 2) def demo_1(radii): """method 1 does not use map, it fully populates in a loop NOT AS GOOD FOR LARGER DATA SETS""" areas = [] for r in radii: a = area(r) # populate list one-by-one in for loop areas.append(a) print a def demo_2(radii): """method 2 uses map to create iterator, which applies area function to each element of radii it can sometimes be better to use iterator, esp. for large lists""" area_iter = map(area, radii) # returns iterator over area applied to each radius for a in area_iter: print a def demo_one_map(): """compare with/out using map""" radii = [2, 5, 7.1, 0.3, 10] demo_1(radii) demo_2(radii) def demo_two_map(): """use map to convert temps en masse""" # example using map temps_c = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19), ("Los Angeles", 26), ("Tokyo", 27), ("New York", 28), ("London", 22), ("Beijing", 32)] # lambda to return tuple with calculated deg. F converted from deg. C c2f = lambda city_tmp: (city_tmp[0], (9.0/5.0)*city_tmp[1] + 32) print list(map(c2f, temps_c)) def demo_one_filter(): """use filter to keep only data from list that are strictly above average""" data = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1] avg = np.mean(data) print "average value is:", avg # create iterator that filters to keep only above average data above_avg_iter = filter(lambda x: x > avg, data) # returns iterator for data above the avg print "values strictly above average are:", list(above_avg_iter) if __name__ == '__main__': demo_one_filter()
true
1e6201d2f6f6df652f7ca66b1347c59c3121d067
ThoPhD/vt
/question_1.py
918
4.25
4
# Question 1. Given an array of integer numbers, which are already sorted. # E.g., A = [1,2,3,3,3,4,4,5,5,6] # • Find the mode of the array # • Provide the time complexity and space complexity of the array, and your reasoning # • Note: write your own function using the basic data structure of your language, # please avoid the provided available functions from external lib from collections import Counter def find_mode_of_array(input_array: list) -> list: """Find mode of the array.""" if not input_array: raise Exception('Cannot compute mode on empty array!') counter_set = Counter(input_array) counter_max = max(counter_set.values()) mode = [k for k, v in counter_set.items() if v == counter_max] return mode # time complexity = O(n) # space complexity = O(n) if __name__ == "__main__": n_num = [1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6] print(find_mode_of_array(n_num))
true
604be482da6a2aea20bf660763b23019eea9571f
cloudzfy/euler
/src/88.py
1,356
4.1875
4
# A natural number, N, that can be written as the sum and # product of a given set of at least two natural numbers, # {a1, a2, ... , ak} is called a product-sum number: # N = a_1 + a_2 + ... + a_k = a_1 x a_2 x ... x a_k. # For example, 6 = 1 + 2 + 3 = 1 x 2 x 3. # For a given set of size, k, we shall call the smallest N # with this property a minimal product-sum number. The # minimal product-sum numbers for sets of size, k = 2, 3, # 4, 5, and 6 are as follows. # k = 2: 4 = 2 x 2 = 2 + 2 # k = 3: 6 = 1 x 2 x 3 = 1 + 2 + 3 # k = 4: 8 = 1 x 1 x 2 x 4 = 1 + 1 + 2 + 4 # k = 5: 8 = 1 x 1 x 2 x 2 x 2 = 1 + 1 + 2 + 2 + 2 # k = 6: 12 = 1 x 1 x 1 x 1 x 2 x 6 = 1 + 1 + 1 + 1 + 2 + 6 # Hence for 2 <= k <= 6, the sum of all the minimal product-sum # numbers is 4 + 6 + 8 + 12 = 30; note that 8 is only counted # once in the sum. # In fact, as the complete set of minimal product-sum numbers # for 2 <= k <= 12 is {4, 6, 8, 12, 15, 16}, the sum is 61. # What is the sum of all the minimal product-sum numbers for # 2 <= k <= 12000? limit = 12000 ans = [2 * k for k in range(12001)] def get_product_sum(num, nprod, nsum, start): k = nprod - nsum + num if k <= limit: ans[k] = min(nprod, ans[k]) for i in range(start, limit / nprod * 2 + 1): get_product_sum(num + 1, nprod * i, nsum + i, i) get_product_sum(0, 1, 0, 2) print sum(set(ans[2:]))
true
03f028686704d0b223621546b04893a844ef9148
NathanJiangCS/Exploring-Python
/Higher Level Python Concepts/Closures.py
2,029
4.6875
5
#Closures ''' Closures are a record storing a function together with an environment: a mapping associating each free variable of the function with the value or storage location to which the name was bound when the closure was created. A closure, unlike a plain function, allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside their scope. ''' #Example 1 def outer_func(): message = 'Hi' def inner_func(): print message #this message variable is a free variable because #it is not actually defined within the scope of inner_func #but it is still able to be accessed return inner_func() # we are returning the executed inner function outer_func() #the result is it prints Hi #Example 2 def outer_func(): message = 'Hi' def inner_func(): print message return inner_func #This time, we will return inner_func without executing it my_func = outer_func() #Now, instead of printing hi, we get that the value of #my_func is the inner_func() my_func() #We can execute the variable as a function and it prints hi #This is interesting because we are done with the execution of the outer_func but it #still is able to access the value of what the message is. This is what a closure is ''' In simple terms, a closure is a function that has access to variables created in the local scope even after the outer function is finished executing. ''' #Example 3 #this time, let us give our functions parameters def outer_func(msg): message = msg def inner_func(): print message return inner_func hi_func = outer_func('Hi') #This time, the hi and hello func are equal to inner_func #which is ready to print the message hello_func = outer_func('Hello') hi_func() #Prints hi hello_func() #Prints hello #Notice that each of these functions remembers the values of their own msg variable
true
d3ea582ed28b3eaa9f7a0376c649bab202c94ffa
NathanJiangCS/Exploring-Python
/Higher Level Python Concepts/String Formatting.py
2,862
4.125
4
#String formatting #Advanced operations for Dicts, Lists, and numbers person = {'name':'Nathan', 'age':100} ####################### #Sentence using string concatenation sentence = "My name is " + person['name'] + ' and I am ' + str(person['age']) + ' years old.' print sentence #This is not readable as you have to open and close strings #You also have to remember to place spaces ####################### #Sentence using %s sentence = "My name is %s and I am %s years old." % (person['name'], person['age']) print sentence ####################### #Sentence using .format sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age']) #You can also explicitly number your placeholders #By doing this, your value at the specified index will replace that placeholder sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age']) #For example, we don't have to type the text value twice when using this formatting tag = 'h1' text = 'This is a headline' sentence = '<{0}>{1}</{0}>'.format(tag, text) print sentence #We can also specify specific fields from the placeholders themselves #Before we were doing this sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age']) #We can also do this. This method also works for a list or a tuple sentence = 'My name is {0[name]} and I am {0[age]} years old.'.format(person) print sentence #We can also access attributes in a similar way class Person(): def __init__(self,name,age): self.name = name self.age = age p1 = Person('Jack',33) sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1) print sentence #We can also pass in keyword arguments sentence = 'My name is {name} and I am {age} years old.'.format(name='Jen',age=30) #This means we can unpack a dictionary and format the sentence in a similar way #By unpacking the dictionary, it fills in the keyword arguments for us person = {'name':'Jen', 'age', 30} sentence = 'My name is {name} and I am {age} years old.'.format(**person) #By adding a colon in our placeholders, we can add formatting #For example, lets say we wanted to make all of our values 2 digits by padding a zero for i in range(1,11): sentence = 'The value is {:02}'.format(i) print sentence #This gives us 01, 02, 03, 04 ... 10, 11. We can change {:02} to {:03} and it gives us #001, 002, 003 .... 010, 011 #This is how we format decimal places pi = 3.14152965 sentence = 'Pi is equal to {:.2f}'.format(pi) #This rounds pi to 2 decimal places 3.14 #We can also chain formatting. For example, if we wanted to add commas to make a large #number more readable but also have the large number rounded to 2 decimal places sentence = '1MB is equal to {:,.2f} bytes'.format(1000**2) #See how we chained , which inserts the commas to make it more readable with .2f
true
616e0af829a12d78b50fdf016704bb179d2a721c
RonakNandanwar26/Python_Programs
/zip_enumerate.py
2,367
4.40625
4
# zip # zip returns iterator that combines multiple iterables into # one sequence of tuples # ('a',1),('b',2),('c',3) # letters = ['a','b','c'] # nums = [1,2,3] # lst = [4,5,6] # print(zip(nums,letters,lst)) # # # # for letters,nums,lst in zip(letters,nums,lst): # print(letters,nums,lst) # # unzip # lst = [('a',1),('b',2),('c',3)] # letter,num = zip(*lst) # print(letter,num) # print(num) # # for i in letter: # print(i) # Enumerate # Enumerator is a built in function that returns an generator # of tuples containing indices and value of list # letters = ['a','b','c','d','e','f'] # print(enumerate(letters)) # for i,letter in enumerate(letters): # print(i,letter) # use zip to write for loop that creates string specifying the label and # co-ordinates of each point and appends it to the list points. # each string should be formatted as 'label:x,y,z' # a:23,56,12 # x_coord = [23,4,5] # y_coord = [56,3,4] # z_coord = [12,5,6] # labels = ['a','b','c'] # # # points = [] # # # for point in zip(labels,x_coord,y_coord,z_coord): # print(point) # # for point in zip(labels,x_coord,y_coord,z_coord): # print('{}:{},{},{}'.format(*point)) # # # for making a list # for point in zip(labels,x_coord,y_coord,z_coord): # points.append('{}:{},{},{}'.format(*point)) # # print(points) # for i in points: # print(i) # # zip to create dictionary # cast_names = ['barney','Robin','Ted'] # cast_heights = [72,68,90] # cast = dict(zip(cast_names,cast_heights)) # print(cast) # print(cast.items()) # for k,v in cast.items(): # print(k,v) # # zip to create tuple # cast_names = ['barney','Robin','Ted'] # cast_heights = [72,68,90] # cast = tuple(zip(cast_names,cast_heights)) # print(cast) # print(zip(cast_names,cast_heights)) # for i in cast: # print(i) # # # zip to create list # cast_names = ['barney','Robin','Ted'] # cast_heights = [72,68,90] # cast = list(zip(cast_names,cast_heights)) # print(cast) # unzip cast tuple # cast = [('barney', 72), ('Robin', 68), ('Ted', 90)] # name,height = zip(*cast) # print(name,height) # names = ['barney','Robin','Ted'] # heights = [72,68,90] # # for i,name in enumerate(names): # print(i,name) # # for i,name in enumerate(names): # names[i] = name + " " + str(heights[i]) # # print(names)
true
9a84af3077b599c11231def2af09cb8ccf40141c
stavernatalia95/Lesson-5.3-Assignment
/Exercise #1.py
448
4.5
4
#Create a function that asks the user to enter 3 numbers and then prints on the screen their summary and average. numbers=[] for i in range(3): numbers.append(int(input("Please enter a number:"))) def print_sum_avg(my_numbers): result=0 for x in my_numbers: result +=x avg=result/len(my_numbers) print("Total: ", result, "Average: ", avg) total_of_numbers=numbers (print_sum_avg(total_of_numbers))
true
bcacc85fdc2fde42a3f3636cedd1666adaa24378
Chia-Network/chia-blockchain
/chia/util/significant_bits.py
991
4.125
4
from __future__ import annotations def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int: """ Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b011110101 and 2, returns -0b11000000. """ x = abs(input_x) if num_significant_bits > x.bit_length(): return input_x lower = x.bit_length() - num_significant_bits mask = (1 << (x.bit_length())) - 1 - ((1 << lower) - 1) if input_x < 0: return -(x & mask) else: return x & mask def count_significant_bits(input_x: int) -> int: """ Counts the number of significant bits of an integer, ignoring negative signs and leading zeroes. For example, for -0b000110010000, returns 5. """ x = input_x for i in range(x.bit_length()): if x & (1 << i) > 0: return x.bit_length() - i return 0
true
f3d569ebc4192a0e60d95944b91ac33bac1f17aa
chimaihueze/The-Python-Workbook
/Chapter 2/44_faces_on_money.py
1,118
4.1875
4
""" Individual Amount George Washington $1 Thomas Jefferson $2 Abraham Lincoln $5 Alexander Hamilton $10 Andrew Jackson $20 Ulysses S. Grant $50 Benjamin Franklin $100 Write a program that begins by reading the denomination of a banknote from the user. Then your program should display the name of the individual that appears on the banknote of the entered amount. An appropriate error message should be displayed if no such note exists. """ amount = int(input("Enter the denomination: ")) notes = [1, 2, 5, 10, 20, 50, 100] individual = {"George Washington": 1, "Thomas Jefferson": 2, "Abraham Lincoln": 5, "Alexander Hamilton": 10, "Andrew Jackson": 20, "Ulysses S. Grant": 50, "Benjamin Franklin": 100} if amount in notes: for k, v in individual.items(): if amount == v: print("The face of {} is printed on ${} note.".format(k, v)) else: print("This note does not exist! Please try again.")
true
87a475ae20b4dde09bc00f7ca8f0258ead316aa4
chimaihueze/The-Python-Workbook
/Chapter 1/exercise24_units_of_time.py
670
4.4375
4
""" Create a program that reads a duration from the user as a number of days, hours, minutes, and seconds. Compute and display the total number of seconds represented by this duration. """ secs_per_day = 60 * 60 * 24 secs_per_hour = 60 * 60 secs_per_minute = 60 days = int(input("Enter the number of days: ")) hours = int(input("Enter the number of hours: ")) minutes = int(input("Enter the number of minutes: ")) seconds = int(input("Enter the number of seconds: ")) total_seconds = (days * secs_per_day) + (hours * secs_per_hour) + (minutes * secs_per_minute) + seconds print("The total number of seconds represented by this duration is {}".format(total_seconds))
true
621e85bdd3efd63d3d3fccd18e6d77d83ef9d6f3
chimaihueze/The-Python-Workbook
/Chapter 1/exercise29_wind_mill.py
1,266
4.4375
4
""" When the wind blows in cold weather, the air feels even colder than it actually is because the movement of the air increases the rate of cooling for warm objects, like people. This effect is known as wind chill. In 2001, Canada, the United Kingdom and the United States adopted the following formula for computing the wind chill index. Within the formula Ta is the air temperature in degrees Celsius and V is the wind speed in kilometers per hour. A similar formula with different constant values can be used for temperatures in degrees Fahrenheit and wind speeds in miles per hour. Write a program that begins by reading the air temperature and wind speed from the user. Once these values have been read your program should display the wind chill index rounded to the closest integer. The wind chill index is only considered valid for temperatures less than or equal to 10 degrees Celsius and wind speeds exceeding 4.8 kilometers per hour. """ air_temp = float(input("Enter the air temperature (in degrees Celsius): ")) wind_speed = float(input("Enter the wind speed (k/hr): ")) wind_chill = 13.12 + (0.6215 * air_temp) - (11.37 * (wind_speed ** 0.16)) + (0.3965 * (air_temp * (wind_speed ** 0.16))) print("The wind chill is {}".format(round(wind_chill)))
true
420c2501440b97e647d1eff05559561e5c5b3869
chimaihueze/The-Python-Workbook
/Chapter 1/exercise23_area_of_a_regular-polygon.py
531
4.46875
4
""" Polygon is regular if its sides are all the same length and the angles between all of the adjacent sides are equal. Write a program that reads s and n from the user and then displays the area of a regular polygon constructed from these values. """ # s is the length of a side and n is the number of sides: import math s = float(input("Enter the length (s): ")) n = int(input("Enter the number of sides (n): ")) area = (n * (s ** 2)) / (4 * (math.tan(math.pi / n))) print("The area of the polygon os {:.2f}".format(area))
true
61628dc6e1c6d4ba2c8bdc112d25aa1b2d334f96
cheikhtourad/MLND_TechnicalPractice
/question2.py
1,628
4.125
4
# Question 2 # Given a string a, find the longest palindromic substring contained in a. # Your function definition should look like question2(a), and return a string. # NOTE: For quetions 1 and 2 it might be useful to have a function that returns all substrings... def question2(a): longest_pal = '' # Base Case: The initial string is a plindrome if isPalindrome(a): return a end = len(a) start = 0 # Get all the substrings and check if its a palindrome # if it is a palindrome and it's longer than longest_pal # make longest_pal the current substring while start != end: while end != start: if isPalindrome( a[start:end] ) and len( a[start:end] ) >= len( longest_pal ): longest_pal = a[start:end] end -= 1 start += 1 end = len(a) return longest_pal # Helper function for question 2 # Determine if a string s is a palindrome def isPalindrome(s): # Base Case: if s empty if not s: return True # Bsae Case: is s is a single character #print (len(s) == 1) if len(s) == 1: return True if s[0] == s[-1]: return isPalindrome(s[1:-1]) return False def test2(): print "Tests for Question 2: \n" a = "racecar" print "The longest palindrome in '" + a + "' is " + " " print question2(a) # Single character test a = "a" print "The longest palindrome in '" + a + "' is " + " " print question2(a) # Empty string test a = "" print "The longest palindrome in '" + a + "' is " + " " print question2(a) # Empty string test a = "I have a racecar" print "The longest palindrome in '" + a + "' is " + " " print question2(a) print "\n" if __name__ == '__main__': test2()
true
3c6a3ffb396896360f45c373f871e4e15fafc181
vivekinfo1986/PythonLearning
/Oops-Polymorphism_AbstractClass_Overwrite.py
530
4.46875
4
#Define a base class with abstract method and using inheritence overwrite it. class Animal(): def __init__(self,name): self.name = name #Testing abstract class def speak(self): raise NotImplementedError('Subclass must implement this abstract method') class Dog(Animal): def speak(self): return self.name + " Says woof!!" class Cat(Animal): def speak(self): return self.name + " Says MeaW!!" Pet1 = Dog('Tommy') Pet2 = Cat('Catty') print(Pet1.speak()) print(Pet2.speak())
true
cd4f7ca00ff3f3336e8899c75f10fc5d69fedc7e
AndyWheeler/project-euler-python
/project-euler/5 Smallest multiple/smallestMultiple.py
1,105
4.15625
4
import primeFactors #primePower(num) returns True if num is a prime power, False otherwise def primePower(num): factors = primeFactors.primeFactorsOf(num) #print "prime factors of " + str(num) + ": " + str(factors) isPrimePower = not factors or factors.count(factors[0]) == len(factors) return isPrimePower def smallestMultiple(upperBound): lim = upperBound powers = [] for n in range(lim, 1, -1): #check to see if it's a prime power, aka if its prime factors are all equal #check to see if it evenly divides an element of the list. if not, add to list isPower = primePower(n) if isPower: if powers: for p in powers: if p%n == 0: break else: powers.append(n) else: powers.append(n) print powers #multiply all the prime powers product = 1 for p in powers: product *= p return product n = 16 #print primeFactors.primeFactorsOf(n) #print primePower(n) print smallestMultiple(14)
true
4ca1429fa78294b81f05a18f22f23a5bad106c73
jammilet/PycharmProjects
/Notes/Notes.py
2,014
4.1875
4
import random # imports should be at the top print(random.randint(0, 6)) print('Hello World') # jamilet print(3 + 5) print(5 - 3) print(5 * 3) print(6 / 2) print(3 ** 2) print() # creates a blank line print('see if you can figure this out') print(5 % 3) # taking input name = input('What is your name?') print('Hello %s' % name) # print(name) age = input('What is your age?') print('%s you are old' % age) def print_hw(): print('Hello World') print_hw() def say_hi(name1): print('Hello %s.' % name1) print('I hope you have a fantastic day') say_hi('jamilet') def birthday(age1): age1 += 1 # age = age + 1 say_hi('John') print('John is 15. Next year:') birthday(16) # variables car_name = 'jamilet mobile' car_type = 'toyota' car_cylinders = 8 car_mpg = 900.1 # inline printing print('my car is the %s.' % car_name) print('my car is the %s. it is a %s' % (car_name, car_type)) def birthday(age1): age1 += 1 # age = age + 1 def f(x): return x**5 + 4 * x ** 4 - 17*x**2 + 4 print(f(3)) print(f(3) + f(5)) # if statements def grade_calc(percentage): if percentage >= 90: return "A" elif percentage >= 80: # else if return "B" if percentage >= 70: return "C" elif percentage >= 60: return "D" elif percentage >= 50: return "E" elif percentage >= 40: return "F" # loops # for num in range(5): # print(num + 1) # for letter in "Hello World": # print(letter) a = 1 while a < 10: print(a) a += 1 # response = "" # while response != "Hello": # response = input("Say \"Hello\"") print("Hello \nWorld") # \n means newline # comparisons print(1 == 1) # two equal signs to compare print(1 != 2) # one is not equal to two print(not False) print(1 == 1 and 4 <= 5) # recasting c = '1' print(c == 1) # false - c is a string, 1 is an integer print(int(c) == 1) print(c == str(1)) num = input("give me a number") # inputs are ALWAYS (!!!!!!!) of type string!!!
true
976d7a598201141e0a1b4ae033be763da80fd5b2
Genyu-Song/LeetCode
/Algorithm/BinarySearch/Sqrt(x).py
1,003
4.15625
4
# -*- coding: UTF-8 -*- ''' Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. ''' class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ def binarysearch(goal, start, end): m = start + (end - start) // 2 if round(m ** 2) > goal: if round((m-1)**2) < goal: return m-1 return binarysearch(goal, start, m-1) elif round(m ** 2) < goal: if round((m+1)**2) > goal: return m return binarysearch(goal, m+1, end) if round(m ** 2) == goal: return m if x < 2: return x return binarysearch(x, 0, x) if __name__ == '__main__': print(Solution().mySqrt(2147395600))
true
d188291d13c688c3fd3404e49c785336f160a075
Genyu-Song/LeetCode
/Algorithm/Sorting/SortColors.py
1,598
4.15625
4
# -*- coding: UTF-8 -*- ''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. ''' class Solution: def sortColors(self, nums): """ Do not return anything, modify nums in-place instead. """ """ TODO: ?? """ map_dict = {} for i in nums: map_dict[i] = map_dict.get(i, 0) + 1 max_times = max(map_dict.values()) res = [] for color in range(max(set(nums))+1): count = 0 while count < map_dict[color]: res.append(color) count += 1 return res import random class Solution2: def sortColors(self, nums): def swap(nums, index1, index2): nums[index1], nums[index2] = nums[index2], nums[index1] pivot = 1 lt, gt = 0, len(nums)-1 pointer = 0 while pointer <= gt: if nums[pointer] < pivot: swap(nums, pointer, lt) lt += 1 pointer += 1 elif nums[pointer] > pivot: swap(nums, gt, pointer) gt -= 1 elif nums[pointer] == pivot: pointer += 1; return nums if __name__ == '__main__': print(Solution2().sortColors(nums=[2,0,2,1,1,0,1,0]))
true
f13838e403245f0e5e00dd3db6d7cdd4a3425631
driscollis/Python-101-Russian
/code/Chapter 2 - Strings/string_slicing.py
248
4.25
4
# string slicing my_string = "I like Python!" my_string[0:1] my_string[:1] my_string[0:12] my_string[0:13] my_string[0:14] my_string[0:-5] my_string[:] my_string[2:] # string indexing print(my_string[0]) # prints the first character of the string
true
b7bdff3a5a9043d42ec3dd26c63c67c239f1b3cf
traj1593/LINEAR-PREDICTION-PROGRAM
/linearPrediction-tRaj-00.py
1,173
4.25
4
''' Program: LINEAR PREDICTION Filename: linearPrediction-tRaj-00.py Author: Tushar Raj Description: The program accepts two integers from a user at the console and uses them to predict the next number in the linear sequence. Revisions: No revisions made ''' ### Step 1: Announce, prompt and get response #Announce print("LINEAR PREDICTION"); print("predict the 3rd number in a sequence\n"); #Prompt user to get response first_number = input("Enter the 1st number: ") second_number = input("Enter the 2nd number: ") ###Step 2: Compute the next number in the linear sequence #convert the string into integer data type converted_first_number = int(first_number) converted_second_number = int(second_number) #Calculate the difference between the first number and second number and store in a variable difference = converted_first_number - converted_second_number #Subtract the difference from the second number to get the predicted number predicted_number = converted_second_number - difference ###Step 3: Print the linear sequence along with the predicted number print("The linear sequence is: ",first_number,second_number,predicted_number)
true
42fd723316a51442c22fb676a3ec9f12ae82056b
HeimerR/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
302
4.125
4
#!/usr/bin/python3 """module writes an Object to a text file """ import json def save_to_json_file(my_obj, filename): """ writes an Object to a text file, using a JSON representation""" with open(filename, encoding="utf-8", mode="w") as json_file: json_file.write(json.dumps(my_obj))
true
e5666f5f6d68cc0fbc6d57012f6b9c3e740a09a8
bmihovski/PythonFundamentials
/count_odd_numbers_list.py
429
4.15625
4
""" Write a program to read a list of integers and find how many odd items it holds. Hints: You can check if a number is odd if you divide it by 2 and check whether you get a remainder of 1. Odd numbers, which are negative, have a remainder of -1. """ nums_odd = list() nums_stdin = list(map(int, input().split(' '))) [nums_odd.append(item) for item in nums_stdin if item % 2 == 1 or item % 2 == -1] print(len(nums_odd))
true
d03229593c9e605f31320e0200b0b258e191acee
bmihovski/PythonFundamentials
/sign_of_int_number.py
581
4.25
4
""" Create a function that prints the sign of an integer number n. """ number_stdin = int(input()) def check_int_type(int_to_check): """ Check the type of input integer and notify the user :param int_to_check: Int :return: message_to_user: Str """ if int_to_check > 0: msg_to_user = f'The number {int_to_check} is positive.' elif int_to_check < 0: msg_to_user = f'The number {int_to_check} is negative.' else: msg_to_user = f'The number {int_to_check} is zero.' return msg_to_user print(check_int_type(number_stdin))
true
f6a011b92ee7858403ea5676b01610ff962e1c0d
bmihovski/PythonFundamentials
/wardrobe.py
2,079
4.21875
4
""" On the first line of the input, you will receive n - the number of lines of clothes, which came prepackaged for the wardrobe. On the next n lines, you will receive the clothes for each color in the format: " "{color} -> {item1},{item2},{item3}…" If a color is added a second time, add all items from it and count the duplicates. Finally, you will receive the color and item of the clothing, that you need to look for. Output Go through all the colors of the clothes and print them in the following format: {color} clothes: * {item1} - {count} * {item2} - {count} * {item3} - {count} … * {itemN} - {count} If the color lines up with the clothing item, print "(found!)" alongside the item. See the examples to better understand the output. Input 4 Blue -> dress,jeans,hat Gold -> dress,t-shirt,boxers White -> briefs,tanktop Blue -> gloves Blue dress Output Blue clothes: * dress - 1 (found!) * jeans - 1 * hat - 1 * gloves - 1 Gold clothes: * dress - 1 * t-shirt - 1 * boxers - 1 White clothes: * briefs - 1 * tanktop - 1 """ wardrobe = dict() input_clothes = list() input_checkouts = list() items_wardrobe = int(input()) printed = [] def _items_wardrobe(color, cloth): """ Prints the content of wardrobe by color and matches :param color: (Str) The color of clothes :param cloth: (Str) The kind of cloth :return: None """ print(f'{color} clothes:') for cloth in wardrobe[color]: if cloth in printed: continue print(f'* {cloth} - {wardrobe[color].count(cloth)}', end='') if color == input_checkouts[0] and cloth == input_checkouts[1]: print(f' (found!)', end='') print() printed.append(cloth) for item in range(items_wardrobe): input_clothes = input().split(' -> ') clothes = input_clothes[1].split(',') if input_clothes[0] in wardrobe: wardrobe[input_clothes[0]].extend(clothes) else: wardrobe.update({input_clothes[0]: clothes}) input_checkouts = input().split() {_items_wardrobe(key, input_checkouts[1]) for key in wardrobe.keys()}
true
b80cb0d8e3d127c6f859b761403cce0f9a9fcc0e
g423221138/chebei
/bs4_study.py
1,766
4.21875
4
#bs4官方文档学习 #例子文档 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ #实例编写 from bs4 import BeautifulSoup import re soup = BeautifulSoup(html_doc, 'html.parser') #让数据按照标准格式输出 print(soup.prettify()) #几个简单地浏览结构化数据的方法 print(soup.title) print(soup.title.name) print(soup.title.string) print(soup.title.parent.name) print(soup.p) print(soup.a) print(soup.find_all('a')) print(soup.find(id="link3")) #从文档中获取所有文字内容: print(soup.get_text()) #输出所有字符串 for string in soup.strings: print(repr(string)) #去除多余空白字符串 for string in soup.stripped_strings: print(repr(string)) #find_all用法举例 #从文档中找到所有<a>标签的链接: for link in soup.find_all('a'): print(link.get('href')) #查找匹配标签及属性 print(soup.find_all("p", "title")) #查找特定id属性 print(soup.find_all(id = "link2")) #可正则查找href属性 print(soup.find_all(href = re.compile("elsie"))) #正则可模糊查找匹配字符串 print(soup.find_all(string = re.compile("sisters"))) #同时查找匹配多个字符串 print(soup.find_all(string = ["Tillie", "Elsie", "Lacie"])) #limit参数,限制输出结果数量 print(soup.find_all("a", limit = 2))
true
c1279076e019dd32f1e2fd30c52d1831b9ffe504
NicsonMartinez/The-Tech-Academy-Basic-Python-Projects
/For and while loop statements test code.py
2,469
4.46875
4
mySentence = 'loves the color' color_list = ['red','blue','green','pink','teal','black'] def color_function(name): lst = [] for i in color_list: msg = "{0} {1} {2}".format(name,mySentence,i) lst.append(msg) return lst def get_name(): go = True while go: name = input('What is your name? ') if name == '': print('You need to provide you name!') elif name == 'Sally': print('Sally, you may not use this software.') else: go = False lst = color_function(name) for i in lst: print(i) get_name() """ **Notes by Nicson Martinez** The way the above code works is: 1. get_name() gets called, 2. Since the while condition is true, the computer waits for an input from the user after printing "What is your name? ". The While loop is used in a way to catch user input and if it meets the specific condition in a conditional statement inside of the loop, print specific message, else exit out of the loop and carry on with the rest of the instructions (While loop keeps running until go = False). 3. Now that we have the string value that the user entered on the screen stored in variable 'name', the function color_function(name) gets called and will eventually store what it returns to a local variable 'lst' (local to get_name()). 4. In color_function(name), an empty list is stored in local variable 'lst' (local to color_function(name)). the for loop iterates through global variable 'color_list' that contains a list of 6 color elements. So, a string consisting of 'name' (what the user imputed),'mySentence' (global variable containing a string), and 'i' which is the current iteration of elements in list 'color_list' get stored in variable 'msg' (which is a local variable to the for loop). Then lst.append(msg), adds each version of the 'msg' string to a the empty list 'lst' that we created earlier. So at the end, the list 'lst' will have 6 elements containing 6 different concatenation of strings differentiating in color because of the iteration of the 'color_list' using i. Lastly, it returns that newly created list containing 6 elements made up of previously concatenated string values. 5. In get_name(), now that we have the returned list in variable 'lst', a for loop is used to iterate through each of those 6 elements to print each of those elements (a string value made up of previously concatenated string values) one at a time. """
true
a59a8a3825c2b2d1c790e24f3fd2e7738b7b999d
veterinarian-5300/Genious-Python-Code-Generator
/Py_lab/Lab 1,2/plotting_a_line.py
345
4.375
4
# importing the module import matplotlib.pyplot as plt # x axis values x = [1,2,3,4,5] # corresponding y axis values y = [2,4,1,3,5] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('x - axis') # naming the y axis plt.ylabel('y - axis') # Title to plot plt.title('Plot') # function to show the plot plt.show()
true
41da6593087fa6ce2e17fff89aa8179832563cfb
prmkbr/misc
/python/fizz_buzz.py
536
4.125
4
#!/usr/local/bin/python """ Prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'. """ def main(): """ Main body of the script. """ for i in xrange(1, 101): if i % 5 == 0: print "FizzBuzz" if (i % 3 == 0) else "Buzz" elif i % 3 == 0: print "Fizz" else: print i if __name__ == "__main__": main()
true
5782fa59d65af071e8fb004f42c8321f17fb6fd3
mljarman/Sorting
/src/iterative_sorting/iterative_sorting.py
1,383
4.25
4
# TO-DO: Complete the selection_sort() function below arr = [5, 2, 1, 6, 8, 10] def selection_sort(arr): # loop through n-1 elements for i in range(len(arr)-1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) # iterate over list after initial loop: for x in range(cur_index, len(arr)): print(arr) # if value at index is smaller, it becomes smallest_index if arr[x] < arr[smallest_index]: smallest_index = x # swap index locations with smallest element: arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index] return arr selection_sort(arr) # TO-DO: implement the Bubble Sort function below def bubble_sort(arr): # loop through array: # first one will go through list once for i in range(len(arr)-1): # iterate over rest of list but don't # need last index because know those are largest elements. for x in range(len(arr)-i-1): # compare each element to its neighbor: # if element on the left is higher, switch places: if arr[x] > arr[x + 1]: arr[x], arr[x + 1] = arr[x +1], arr[x] return arr # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): return arr
true
de2c80883264b731c748c09d2a20c8c27995d03e
bjucps/cps110scope
/Lesson 2-3 String Processing/greeter.py
481
4.21875
4
# Demonstrates string processing full_name = input('Enter your first and last name:') if full_name == '': print('You did not enter a name!') else: space_pos = full_name.find(' ') if space_pos == -1: print('You did not enter your first and last name!') else: first_name = full_name[0:space_pos] print('Hello,' , first_name) last_name = full_name[space_pos + 1:len(full_name)] print('Or should I call you Mr.', last_name)
true
3d9018bea5f64544cb6abc8c06a27385262d73c3
bjucps/cps110scope
/Lesson 2-4 Unit Testing/addnums.py
409
4.1875
4
def addNums(num: str) -> int: """Adds up all digits in `num` Preconditions: `num` contains only digits Postconditions: returns sum of digits in `num` """ sum = 0 for digit in num: sum += int(digit) return sum def test_addNums(): assert addNums('123') == 6 if __name__ == "__main__": # Add this to use debugger to step through unit test code test_addNums()
true
09dcca918dee39291a7de4a3e15cbe89e3e7dfd6
vinayakentc/BridgeLabz
/AlgorithmProg/VendingMachine.py
1,042
4.3125
4
# 10. Find the Fewest Notes to be returned for Vending Machine # a. Desc ­> There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be # returned by Vending Machine. Write a Program to calculate the minimum number # of Notes as well as the Notes to be returned by the Vending Machine as a # Change # b. I/P ­> read the Change in Rs to be returned by the Vending Machine # c. Logic ­> Use Recursion and check for largest value of the Note to return change # to get to minimum number of Notes. # ------------------------------------------------------------------------------------ def vendingmachine(money): count2 = 0 for denomination in [1000, 500, 100, 50, 10, 5, 2, 1]: count = 0 while money // denomination != 0: count = count + 1 count2 = count2 + 1 money = money - denomination print(denomination, " ", count) return count2 if __name__ == '__main__': money = int(input("Enter amount to withdraw:")) print("No.of notes:", vendingmachine(money))
true
032e58342dd4dd263ae96aabb6563dad78d68b15
vinayakentc/BridgeLabz
/DataStructProg/Palindrome_Checker.py
1,363
4.46875
4
# Palindrome­Checker # a. Desc ­> A palindrome is a string that reads the same forward and backward, for # example, radar, toot, and madam. We would like to construct an algorithm to # input a string of characters and check whether it is a palindrome. # b. I/P ­> Take a String as an Input # c. Logic ­> The solution to this problem will use a deque to store the characters of # the string. We will process the string from left to right and add each character to # the rear of the deque. # d. O/P ­> True or False to Show if the String is Palindrome or not. # -------------------------------------------------------------------------------------- # importting required deque from DataStructProg.Deque import * # palindrom function def palindrome_checker(): # creating a Deque pali_deque = Deque() # taking an input string = input("Enter a string:") # inserting elements at rare for i in string: pali_deque.insertRare(i) # finding size of deque size = pali_deque.size() # take a empty string new_string = "" for i in range(size): new_string = new_string + pali_deque.removeRare() # comparing both strings if string == new_string: print("palindrome strings") else: print("Not palindrome strings") # driver program if __name__ == '__main__': palindrome_checker()
true
25fab75d27473ef6b0949ddcbb0a2678eefbf108
vinayakentc/BridgeLabz
/FunctionalProg/Factors.py
1,012
4.21875
4
# 6. Factors # a. Desc ­> Computes the prime factorization of N using brute force. # b. I/P ­> Number to find the prime factors # c. Logic ­> Traverse till i*i <= N instead of i <= N for efficiency . # d. O/P ­> Print the prime factors of number N # ---------------------------------------------------------------------- import math # Function on Factors def Factors(Number): while Number % 2 == 0: # prints 2 until num divided by 2 print(2) Number = Number // 2 for i in range(3, int(math.sqrt(Number)) + 1, 2): # using Brute force decreased iteration by i*i<=N while Number % i == 0: # for loop is for any odd number that gives remainder zero while dividing print(i) # prints number if remainder is 0 Number = Number // i if Number > 2: # this loop is for remaining numbers which not gives remainder zero print(Number) if __name__ == '__main__': Num = int(input("Enter number to find prime factors of it:")) Factors(Num)
true
8475bd109f4efb302b35f5d16ef5aaf358d43ad6
vinayakentc/BridgeLabz
/DataStructProg/UnOrderedList.py
1,985
4.28125
4
# UnOrdered List # a. Desc ­> Read the Text from a file, split it into words and arrange it as Linked List. # Take a user input to search a Word in the List. If the Word is not found then add it # to the list, and if it found then remove the word from the List. In the end save the # list into a file # b. I/P ­> Read from file the list of Words and take user input to search a Text # c. Logic ­> Create a Unordered Linked List. The Basic Building Block is the Node # Object. Each node object must hold at least two pieces of information. One ref to # the data field and second the ref to the next node object. # d. O/P ­> The List of Words to a File. # ------------------------------------------------------------------------------------------- import re from DataStructProg.LinkedList import * # function to read data from file def words_read(): file = open("DataStructWordsFile", "r") # created a linked list words_list = Linkedlist() # storing the elements into list for i in file: str_x = re.split(',| |\.|\n',i.lower()) for j in str_x: # STORING DATA into list words_list.append(j) file.close() return words_list # function for searching element in the list def searchList(doc_list): search_key = input("Enter a string to search:") search_key = search_key.lower() # seraching a key from using utility search function from linked list class sk=doc_list.search(search_key) # if found then # poping the element from list if sk == True: doc_list.pop(doc_list.indexOf(search_key)) # if word not found # adding word to the list else: doc_list.append(search_key) return doc_list # driver program if __name__ == '__main__': # calling function to read the words from a file a = words_read() # calling search function to search a element from list b = searchList(a) #a.printlist() # printing final list b.printlist()
true
7d46a845ad0bed2298511f782e37faee1f7701ac
afurkanyegin/Python
/The Art of Doing Code 40 Challenging Python Programs Today/2-MPH to MPS Conversion App.py
262
4.15625
4
print("Welcome to the MPH to MPS Conversion App") speed_in_miles=float(input("What is your speed in miles:")) speed_in_meters=speed_in_miles * 0.4474 rounded_speed_in_meters=round(speed_in_meters,2) print(f"Your speed in MPS is: {rounded_speed_in_meters}")
true
23a71da2a35150b6dd70cc4f5507cce6c37b87a6
TonyVH/Python-Programming
/Chapter 02/Calculator.py
541
4.25
4
# Calculator.py # This is a simple, interactive calulator program def calculator(): print('Calculator guide:') print('Use + to add') print('Use - to subtract') print('Use * to multiply') print('Use / to divide') print('Use ** for exponentials') print('Use // for floor division') print('Use % to find the remainder of two numbers that cannot divide equally') print() x = eval(input('Enter your equation here: ')) print (x) print() while 1 != 2: return calculator() calculator()
true
0c7a6dc53b0e75076918ef422b5cf3da28b052a1
TonyVH/Python-Programming
/Chapter 05/acronym.py
330
4.34375
4
# acronym.py # Program to create an acronym from a user given sentence/phrase def main(): print('This program will create an acronym from a word or phrase\n') phrase = input('Enter a sentence or phrase: ') phrase = phrase.split() for words in phrase: print(words[0].upper(), end='') print() main()
true
a0ee9db42b6a9cc7f4a423e2281a718a1789981f
DeepeshYadav/AutomationMarch2020
/PythonPractice/Lambda_function/practice/Decorator Introdcution.py
740
4.3125
4
""" Decorators 1. Need to take a function as parameters 2. Add Functionality to the function. 3. Function need to return another function. -> In general language a decorator means , the person who does decoration job. to make things more presentable. for examples i want to given gift to my friend like watch 1 -> I can give watch to friend 2 -> I can give watch to friend with gift wrapping, which is more presentable and good look. THERE ARE TWO TYPE DECORATORS: 1 -> Function Decorators 2 -> Class Decorators Following thing will learn in function decorators: 1 : Nested Function 2 : Function Return Function. 3 : Refrence of function it memory location of function. 4 : Use Function as parameter of another function. """
true
cde40dccf5ea9938c8572de56bb6de3a9f8d131e
DeepeshYadav/AutomationMarch2020
/PythonPractice/Decorators/property_decor_example1.py
544
4.28125
4
# In this class will how to set values using setter # and next example2 will explain how achieve this using @propert decorator class Student: def __init__(self, name, grade): self.name = name self.grade = grade def msg(self): return self.name +" got the grade "+self.grade def setter(self, msg): sent = msg.split(" ") self.name = sent[0] self.grade = sent[-1] obj = Student('Amey', 'A') obj.setter("Rahul got the grade B") print(obj.name) print(obj.grade) print(obj.msg())
true
0248a047a97752eb6028adf81022ad57b765e5e2
ahmed-t-7/Programming-Foundations-Fundamentals
/3. Variables and Data Types/Challenge_What_is_The_output.py
496
4.40625
4
print("Challenge 1:") # A message for the user message = "This is going to be tricky ;)" Message = "Very tricky!" print(message) # show the message on the screen this statement will print the first message variable # Perform mathematical operations result = 2**3 print("2**3 =", result) result = 5 - 3 #Change the value of variable from 8 To 2 #print("5 - 3 =", result) #This is a comment statement willn't print anything print("Challenge complete!") # This Will print Challenge complete
true
8bcdc627379f686bbc937d6c6c756cadd1d9cc75
JeffreyAsuncion/Study-Guides
/Unit_3_Sprint_2/study_part1.py
2,472
4.28125
4
import os import sqlite3 """ ## Starting From Scratch Create a file named `study_part1.py` and complete the exercise below. The only library you should need to import is `sqlite3`. Don't forget to be PEP8 compliant! 1. Create a new database file call `study_part1.sqlite3` """ DB_FILEPATH = os.path.join(os.path.dirname(__file__), "study_part1.sqlite3") """ 2. Create a table with the following columns ``` student - string studied - string grade - int age - int sex - string ``` """ connection = sqlite3.connect(DB_FILEPATH) cursor = connection.cursor() #Drop Table cursor.execute('DROP TABLE IF EXISTS students;') create_table_query = """ CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT ,student VARCHAR(30) ,studied TEXT ,grade INTEGER ,age INTEGER ,sex INTEGER ); """ cursor.execute(create_table_query) """ 3. Fill the table with the following data """ thundercats = [ ('Lion-O', 'True', 85, 24, 'Male'), ('Cheetara', 'True', 95, 22, 'Female'), ('Mumm-Ra', 'False', 65, 153, 'Male'), ('Snarf', 'False', 70, 15, 'Male'), ('Panthro', 'True', 80, 30, 'Male') ] for thundercat in thundercats: insert_query = f''' INSERT INTO students (student, studied, grade, age, sex) VALUES {thundercat} ''' cursor.execute(insert_query) connection.commit() """ 4. Save your data. You can check that everything is working so far if you can view the table and data in DBBrowser """ """ 5. Write the following queries to check your work. Querie outputs should be formatted for readability, don't simply print a number to the screen with no explanation, add context. """ query = 'SELECT AVG(age) FROM students;' results = cursor.execute(query).fetchone() print("What is the average age? Expected Result - 48.8", results) query = "SELECT student FROM students WHERE sex = 'Female';" results = cursor.execute(query).fetchall() print("What are the name of the female students? Expected Result - 'Cheetara'", results) query = """ SELECT count(student) FROM students WHERE studied = 'True'; """ results = cursor.execute(query).fetchone() print("How many students studied? Expected Results - 3", results) query = """ SELECT student FROM students ORDER BY student; """ results = cursor.execute(query).fetchall() print("Return all students and all columns, sorted by student names in alphabetical order.", results)
true
223b6e68740e9411f390b37869df3125c8fe49c0
usamarabbani/Algorithms
/squareRoot.py
996
4.15625
4
'''take user input number = int(input("Enter a number to find the square root : ")) #end case where user enter less than 0 number if number < 0 : print("Please enter a valid number.") else : sq_root = number ** 0.5 print("Square root of {} is {} ".format(number,sq_root))''' def floorSqrt(x): # Base cases if x<0: return "Please enter a positive number" if (x == 0 or x == 1): return x # Do Binary Search for floor(sqrt(x)) start = 1 end = x while (start <= end): mid = (start + end) // 2 # If x is a perfect square if (mid * mid == x): return mid # Since we need floor, we update # answer when mid*mid is smaller # than x, and move closer to sqrt(x) if (mid * mid < x): start = mid + 1 ans = mid else: # If mid*mid is greater than x end = mid - 1 return ans # driver code x = 9 print(floorSqrt(x))
true
f3e397a744558c935850f18001b4a5bf14e56ec6
usamarabbani/Algorithms
/mergeTwoSortedList.py
2,189
4.46875
4
# Defining class which will create nodes for our linked lists class Node: def __init__(self, data): self.data = data self.next = None # Defining class which will create our linked list and also defining some methods class LinkedList: def __init__(self): self.head = None def printList(self): # Method to print linked list temp = self.head while temp: print (temp.data) temp = temp.next def append(self, new_data): # Method to add node at the end of the linked list new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node # Defining function which will merge our linked lists def mergeLists(l1, l2): temp = None if l1 is None: return l2 if l2 is None: return l1 if l1.data <= l2.data: temp = l1 temp.next = mergeLists(l1.next, l2) else: temp = l2 temp.next = mergeLists(l1, l2.next) return temp # The main logic starts from here if __name__ == '__main__': list1 = LinkedList() # Creating linked list 1 list1.append(10) # Assigning values to linked list 1 in sorted manner list1.append(20) list1.append(30) list1.append(40) list1.append(50) list2 = LinkedList() # Creating linked list 2 list2.append(5) # Assigning values to linked list 2 in sorted manner list2.append(15) list2.append(25) list2.append(35) list2.append(45) print ("Printing Linked List 1") list1.printList() # Printing linked list 1 print ("Printing Linked List 2") list2.printList() # Printing linked list 2 list3 = LinkedList() # Creating linked list 3 # Merging linked list 1 and linked list 2 in linked list 3 list3.head = mergeLists(list1.head, list2.head) print ("Printing Linked List 3") list3.printList() # Printing linked list 3
true
970f23ef1afa5d5c2ae538b25c9c9fbc191745f9
BigThighDude/SNS
/Week3/Ch5_Ex2.py
1,133
4.34375
4
num = int(input("Enter integer to perform factorial operation:\n")) #prompt user to enter number, converts string to interger. program doesnt work if float is entered def fact_iter(num): #define iterative function product = 1 # define product before it is used for i in range(1,num+1): #count up from 1 (works with 0 as the product is just returned as 0 product = i*product #count up and multiply with each successive integer return product #return the product to the main script def fact_rec(num): if num==1: return 1 else: return num*fact_rec(num-1) # def fact_rec(num): #define recursive function # # product = product*fact_rec(num-1) #function calls itself # return product #function returns the final product ie. the factorial if num>1: #makes sure number is positive print("iterative ", fact_iter(num)) #run iterative program if input is valid print("recursive ", fact_rec(num)) #run recursive program if input is valid elif num==1 or num==0: print("1") else: #if number is negative print("Enter valid number") #return error message
true
dce29aacbef5e86574b300659dd52c9edb4868f5
waltermblair/CSCI-220
/random_walk.py
723
4.28125
4
from random import randrange def printIntro(): print("This program calculates your random walk of n steps.") def getInput(): n=eval(input("How many steps will you take? ")) return n def simulate(n): x=0 y=0 for i in range(n): direction=randrange(1,5) if direction==1: y=y+1 elif direction==2: x=x+1 elif direction==3: y=y-1 else: x=x-1 return x, y def printOutput(distance, n): print("You will be {0} steps away from origin after {1} steps" \ .format(distance, n)) def main(): printIntro() n=getInput() x, y =simulate(n) printOutput(abs(x)+abs(y), n) if __name__=='__main__': main()
true
ddb747b2b03438b099c0cf14b7320473be16888b
waltermblair/CSCI-220
/word_count_batch.py
404
4.28125
4
print("This program counts the number of words in your file") myfileName=input("Type your stupid ass file name below\n") myfile=open(myfileName,"r") mystring=myfile.read() mylist=mystring.split() word_count=len(mylist) char_count=len(mystring) line_count=mystring.count("\n") print("Words: {0}".format(word_count)) print("Characters: {0}".format(char_count)) print("Lines: {0}".format(line_count))
true
28f61625f6cc35e07557140465f6b2dcc3974d77
delgadoL7489/cti110
/P4LAB1_LeoDelgado.py
549
4.21875
4
#I have to draw a square and a triangle #09/24/13 #CTI-110 P4T1a-Shapes #Leonardo Delgado # #import the turtle import turtle #Specify the shape square = turtle.Turtle() #Draws the shape for draw in range(4): square.forward(100) square.right(90) #Specify the shape triangle = turtle.Turtle() #Draws the shape for draw in range(3): triangle.forward(50) triangle.left(120) #Imports the turtle to use #Specify the shape thats going to be drawn #Draw the shape #Specify the other shape #Draw the new shape
true
714c9c402b65cf3102425a3467c1561eaa20f2dd
delgadoL7489/cti110
/P3HW2_Shipping_LeoDelgado.py
532
4.15625
4
#CTI-110 #P3HW2-Shipping Charges #Leonardo Delgado #09/18/18 # #Asks user to input weight of package weight = int(input('Enter the weight of the package: ')) if weight <= 2: print('It is $1.50 per pound') if 2 < weight <=6: print('It is $3.00 per pound') if 6 < weight <=10: print('It is $4.00 per pound') if weight > 10: print('It is $4.75 per pound') #Prompts user to input weight of package #Saves value #Calculates if value is over certain value #Outputs the specific value for the inputed weight
true
05be92d0a985f8b51e2478d52d0d476539b1f96c
delgadoL7489/cti110
/P5T1_KilometersConverter_LeoDelgado.py
659
4.59375
5
#Prompts user to enter distance in kilmoters and outputs it in miles #09/30/18 #CTI-110 P5T1_KilometerConverter #Leonardo Delgado # #Get the number to multiply by Conversion_Factor = 0.6214 #Start the main funtion def main(): #Get the distance in kilometers kilometers = float(input('Enter a distance in kilometers: ')) #Display the converted distance. show_miles(kilometers) #Start the callback conversion function def show_miles(km): #Formula for conversion miles = km * Conversion_Factor #Output converted miles print(km, 'kilometers equals', miles, 'miles.') #Calls back the main funtion main()
true
b97e8694dd80c4207d2aef3db11326bef494c1d5
aju22/Assignments-2021
/Week1/run.py
602
4.15625
4
## This is the most simplest assignment where in you are asked to solve ## the folowing problems, you may use the internet ''' Problem - 0 Print the odd values in the given array ''' arr = [5,99,36,54,88] ## Code Here print(list(i for i in arr if not i % 2 ==0)) ''' Problem - 1 Print all the prime numbers from 0-100 ''' ## Code Here for num in range(101): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num) ''' Problem - 2 Print the reverse of a string ''' string = 'Reverse Me!' ## Code Here print(string[::-1])
true
c487f10008953853ffce904974c01f60be0e9874
justus-migosi/desktop
/database/queries.py
1,179
4.40625
4
import sqlite3 from sqlite3 import Error # Create a connection def create_connection(file_path): """ Creates a database connection to the SQLite database specified by the 'path'. Parameters: - path - Provide path to a database file. A new database is created where non exists. Return: - Returns a Connection Object or None. """ try: connection = sqlite3.connect(r'file_path') except Error as e: connection = None print(f'Error! Occured while creating a connection! --> {e}') return connection # Read table from the database def read_table(connection, command): """ Queries all rows of the 'table' provided as a parameter. Parameters: - connection - Provide a connection object to the desired database. - table - Give the name of the table to query from the database. Return: - A list of rows related to the queried table. """ try: cur = connection.cursor() cur.execute(command) rows = cur.fetchball() except Error as e: rows = None print(f'This Error Occured while querying the {table} table! --> {e}') return rows
true
0acadc79127f5cc53cb616bac3e31c2ef120822f
shahzadhaider7/python-basics
/17 ranges.py
926
4.71875
5
# Ranges - range() range1 = range(10) # a range from 0 to 10, but not including 10 type(range1) # type = range range1 # this will only print starting and last element of range print(range1) # this will also print same, starting and last element list(range1) # this will list the whole range from start to the end list(range1[2:5]) # slicing the range datatype, using list to show all elements list(range1[3:9:2]) # slicing the range datatype with a step of 2 list(range1)[3:9:2] # another way to slice, this will return same as the last command list(range(20)) # we can still use range function without creating it first len(range1) # length is 10, 0 to 9 10 in range1 # False, because 10 is last element and is not included 7 not in range1 # False, because 7 is in range1 range1[3] # element at index 3 range1.index(5) # returns the index of 5
true
69f33f4919562b4dd54d868fbc63c81ecf4567ca
youssefibrahim/Programming-Questions
/Is Anagram.py
725
4.15625
4
#Write a method to decide if two strings are anagrams or not from collections import defaultdict def is_anagram(word_one, word_two): size_one = len(word_one) size_two = len(word_two) # First check if both strings hold same size if size_one != size_two: return False dict_chars = defaultdict(int) # Use dictionary to store both characters and how many # times they appear in one dictionary for chars in word_one: dict_chars[chars] += 1 for chars in word_two: dict_chars[chars] += 1 # Each character has to be divisible by two since # characters for both words are stored in the same # dictionary for key in dict_chars: if (dict_chars[key] % 2) != 0: return False return True
true
65778e41f5d2fae0c62993edd0c98ca8c603783d
EXCurryBar/108-2_Python-class
/GuessNumber.py
374
4.125
4
import random number = random.randint(0,100) print(number) print("Guess a magic number between 0 to 100") guess = -1 while guess != number : guess = eval(input("Enter your guess: ")) if guess == number : print("Yes, the number is ",number) elif guess > number : print("Your guess is too high") else : print("Your guess is too low")
true
112da84fe029bfec6674f8fdf8cea87da361a96f
tminhduc2811/DSnA
/DataStructures/doubly-linked-list.py
2,053
4.3125
4
""" * Singly linked list is more suitable when we have limited memory and searching for elements is not our priority * When the limitation of memory is not our issue, and insertion, deletion task doesn't happend frequently """ class Node(): def __init__(self, data): self.data = data self.next = None self.prev = None class LinkedList(): def __init__(self, data): a = Node(data) self.head = a def traversal(l): temp = l.head result = '' while temp != None: result += str(temp.data) + '\t' temp = temp.next return result def insert_at_beginning(l, n): n.next = l.head l.head.prev = n l.head = n def insert_at_last(l, n): temp = l.head while temp.next != None: temp = temp.next temp.next = n n.prev = temp def insert_node_after(n, a): n.next = a.next n.next.prev = n n.prev = a a.next = n def delete(l, n): if n.prev == None: # If n is head l.head = n.next else: # n is not head n.prev.next = n.next if n.next != None: n.next.prev = n.prev del n if __name__=='__main__': l = LinkedList(20) a = Node('node-a') b = Node('node-b') c = Node('node-c') # Connecting all nodes l.head.next = a a.next = b a.prev = l.head b.next = c b.prev = a c.prev = b print('Linked list: ', traversal(l)) # Insert a node at the beginning of the list d = Node('Inserted-node') insert_at_beginning(l, d) print('Linked list after inserting a node at the beginning: ', traversal(l)) # Insert a node after node b e = Node('Node-after-b') insert_node_after(e, b) print('Linked list after inserting a node after b: ', traversal(l)) # Insert a node at the end of the list f = Node('last-node') insert_at_last(l, f) print('Linked list after inserting a node at the end: ', traversal(l)) # Delete node b = 50 delete(l, b) print('Linked list after delete node b: ', traversal(l))
true
4e60800182b8bb8fccbb924b21ebc40cdfb497b5
jessiicacmoore/python-reinforcement-exercises
/python_fundamentals1/exercise5.py
319
4.125
4
distance_traveled = 0 while distance_traveled >= 0: print("Do you want to walk or run?") travel_mode = input() if travel_mode.lower() == "walk": distance_traveled += 1 elif travel_mode.lower() == "run": distance_traveled += 5 print("Distance from home is {}km.".format(distance_traveled))
true
bcc2045e953975bbdf2d78dc2888346072a0af24
chantigit/pythonbatch1_june2021data
/Python_9to10_June21Apps/project1/listapps/ex5.py
407
4.3125
4
#II.Reading list elements from console list1=list() size=int(input('Enter size of list:')) for i in range(size): list1.append(int(input('Enter an element:'))) print('List elements are:',list1) print('Iterating elements using for loop (index based accessing)') for i in range(size): print(list1[i]) print('Iterating elements using foreach loop(element based accessing)') for i in list1: print(i)
true
7ccc459d2ab9e420b47bfefd00e04dddff87fa8a
NSO2008/Python-Projects
/Printing to the terminal/HelloWorld.py
584
4.21875
4
#This is a comment, it will not print... #This says Hello World... print('Hello World') #This is another example... print("This uses double quotes") #Quotes are characters while quotation is the use quotes... print("""This uses triple quotation... it will be displayed however I type it""") #This is an exampe of the use of single quotes against double quotes... print('''I could do same with single quotes... See?''') #This is another way of printing a new line as against triple quotation... print("This uses a backslash then an n.... \nIt's used to signify a new line")
true
0b8f08d1f44d32eac328848be344c8d5e7cca3ad
cbolles/auto_typing
/auto_type/main.py
2,162
4.125
4
""" A tool that simulates keypresses based on a given input file. The program works by accepting a source file containing the text and an optional delimeter for how to split up the text. The program then creates an array of string based on the delimeter. Once the user presses the ESCAPE key, each value in the array will be typed out seperated by newlines. :author Collin Bolles: """ import keyboard import argparse from typing import List def get_segments(delimeter: str, source_location: str) -> List[str]: """ Takes in the location of the source file and returns a list of inputs that are split up based on the passed in delimeter :param delimeter: The delimeter to break up the input :param source_location: Path to file where source material exists """ segments = [] with open(source_location) as source_file: for line in source_file: for word in line.split(delimeter): segments.append(word.strip()) return segments def run_typing(segments: List[str]): """ Function that handles typing the segments out. :param segments: The segments to write out seperated by newlines """ for segment in segments: keyboard.write(segment) keyboard.press_and_release('enter') def main(): parser = argparse.ArgumentParser(description='''A tool to automatically type out a given piece of text''') parser.add_argument('source', action='store', help='''path to the source text that will be typed out by the program''') parser.add_argument('--delimeter', action='store', help='''delimeter that will be used to split up the text, by default will be split by newline''', default='\n') args = parser.parse_args() # Get the segments seperated based on the defined delimeter segments = get_segments(args.delimeter, args.source) # Setup listener to kick off running the typing function keyboard.add_hotkey('esc', lambda: run_typing(segments)) # Wait until the escape key is pressed again keyboard.wait('esc') if __name__ == '__main__': main()
true
3aa1d42dbbe55beadaeafe334950694fa9ece8f2
mickeyla/gwc
/Test A/test.py
596
4.125
4
#Comments are not for the code #Comments are for you #Or whoever answer1 = input ("What is your name?") print ("My name is", answer1) answer2 = input ("How old are you?") print ("I am", answer2, "years old!") answer3 = input ("Where are you from?") print ("I am from", answer3) answer4 = input ("Do you like coding?") if answer4 == ("Yes"): print ("Great! So do I!") else: print ("Oh, I'm sorry.") answer5 = input ("Do you think pineapple on pizza is okay?") if answer5 == ("Yes"): print ("No. Rethink your answer.") else: print ("Thank you! It's terrible!")
true
cc8bf4379d575d1d414c7fd61e236c3d4d904b12
hauqxngo/PythonSyntax
/words.py
1,385
4.75
5
# 1. For a list of words, print out each word on a separate line, but in all uppercase. How can you change a word to uppercase? Ask Python for help on what you can do with strings! # 2. Turn that into a function, print_upper_words. Test it out. (Don’t forget to add a docstring to your function!) def print_upper_words(words): """Print out each word on a separate line in all uppercase.""" for word in words: print(word.upper()) # 3. Change that function so that it only prints words that start with the letter ‘e’ (either upper or lowercase). def print_upper_words_e(words): """Print words that start with the letter ‘e’ (either upper or lowercase) on a separate line in all uppercase.""" for word in words: if word.startswith("E") or word.startswith("e"): print(word.upper()) # 4. Make your function more general: you should be able to pass in a set of letters, and it only prints words that start with one of those letters. def print_upper_words_x(words, must_start_with): """You should be able to pass in a set of letters, and it only prints words that start with one of those letters on a separate line in all uppercase.""" for word in words: for letter in must_start_with: if word.startswith(letter): print(word.upper()) break
true
1f52ebb74b762dcce6213360939086acb0b59f46
getconnected2010/testing123
/adventure story.py
1,194
4.1875
4
name = input('What is your name?:') print(f'Hello {name.capitalize()}, you are about to go on an adventure. You enter a room and see two doors. One is red and the other blue.') door_input = input('which door do you choose?: ') if door_input == 'red': print('Red door leads you to the future. You have to help a scientist to get back.') help = input('Do you help?: ') if help == 'yes': print('Awesome, the scentist will help you get back') elif help == 'no': print('what? now you are stuck in the future forever. Game over.') elif door_input == 'blue': print('Blue dooor leads to the past. You have to help a wizard, who will help you get back') wizard_help = input('will you help the wizard?: ') if wizard_help == 'yes': print('yaaay you get back') elif wizard_help == 'no': print ('omg. what were you thinking? now you have to steal his saber to escape.') steal = input('would you steal or leave?: ') if steal == 'steal': print('good choice. now run and use it to escape. good luck') elif steal == 'leave': print('woow you must know a way out. good luck.')
true
cd7793038854eab3c67e631d3c158f2f00e9ad70
gauravraul/Competitive-Coding
/lcm.py
485
4.15625
4
# Program to get the lcm of two numbers def lcm(x,y) : #take the greater number if x>y: greater = x else: greater = y #if greater is divisible by any of the inputs , greater is the lcm #else increment greater by one until it is divisible by both the inputs while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater +=1 return lcm print(lcm(10,45))
true
ecf0d4117ad8aab226e9808899b922d720cb0294
2018JTM2248/assignment-8
/ps2.py
1,919
4.65625
5
#!/usr/bin/python3 ###### this is the second .py file ########### ####### write your code here ########## #function definition to rotate a string d elemets to right def rotate_right(array,d): r1=array[0:len(array)-d] # taking first n-d letters r2=array[len(array)-d:] # last d letters rotate = r2+r1 # reversed the order return rotate #return ststement decrypted="" # decrypted string will be stored here #k1=int(input("Enter the amount by which key1 elemets to be rotated\n Decryption key1 = : ")) #k2=int(input("\nDecryption key2 = : ")) #k3=int(input("\nDecryption key3 = : ")) print("Enter Key") j1,j2,j3 =input().split(" ") k1=int(j1) k2=int(j2) k3=int(j3) quer_str = input("Enter Encrypted string\n") print(quer_str) alphabets="abcdefghijklmnopqrstuvwxyz_" alphabets1=alphabets[0:9] alphabets2=alphabets[9:18] alphabets3=alphabets[18:27] # Declaring Strings to store different key characters key1="" key2="" key3="" # Seperating keys for different range for i in quer_str : for j in alphabets1: if i==j : key1 = key1 + str(i) for k in alphabets2: if i==k : key2 = key2 + str(i) for l in alphabets3: if i==l: key3 = key3 + str(i) # keys sorted according to input numbers by which they are to be shifted new_k1=rotate_right(key1,k1) new_k2=rotate_right(key2,k2) new_k3=rotate_right(key3,k3) index1=0 index2=0 index3=0 # Decrypting a string and printing original decrypted string for i in quer_str: for j in new_k1 : if i==j: decrypted=decrypted+new_k1[index1] index1 = index1+1 for k in new_k2 : if i==k : decrypted=decrypted+new_k2[index2] index2=index2+1 for l in new_k3 : if i==l : decrypted=decrypted+new_k3[index3] index3=index3+1 print("Decrypted string is : ",decrypted)
true
b71a8ef228748fe80c9696c057b4f6c459c13f49
vikashvishnu1508/algo
/Revision/Sorting/ThreeNumSort.py
521
4.15625
4
def threeNumSort(array, order): first = 0 second = 0 third = len(array) - 1 while second <= third: if array[second] == order[0]: array[first], array[second] = array[second], array[first] first += 1 second += 1 elif array[second] == order[2]: array[second], array[third] = array[third], array[second] third -= 1 else: second += 1 return array print(threeNumSort([1, 0, 0, -1, -1, 0, 1, 1], [0, 1, -1]))
true
fff30ad774cb793bd20a0832cf45a1855e75a263
kacifer/leetcode-python
/problems/problem232.py
2,563
4.34375
4
# https://leetcode.com/problems/implement-queue-using-stacks/ # # Implement the following operations of a queue using stacks. # # push(x) -- Push element x to the back of queue. # pop() -- Removes the element from in front of queue. # peek() -- Get the front element. # empty() -- Return whether the queue is empty. # Example: # # MyQueue queue = new MyQueue(); # # queue.push(1); # queue.push(2); # queue.peek(); // returns 1 # queue.pop(); // returns 1 # queue.empty(); // returns false # Notes: # # You must use only standard operations of a stack -- which means only push # to top, peek/pop from top, size, and is empty operations are valid. # Depending on your language, stack may not be supported natively. You may # simulate a stack by using a list or deque (double-ended queue), as long as # you use only standard operations of a stack. # You may assume that all operations are valid (for example, no pop or peek # operations will be called on an empty queue). class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.inStack, self.outStack = [], [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.inStack.append(x) def transfer(self): for _ in range(len(self.inStack)): self.outStack.append(self.inStack.pop()) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if self.outStack: return self.outStack.pop() if self.inStack: self.transfer() return self.pop() raise ValueError("No more element") def peek(self) -> int: """ Get the front element. """ if self.outStack: return self.outStack[-1] if self.inStack: self.transfer() return self.peek() raise ValueError("No element") def empty(self) -> bool: """ Returns whether the queue is empty. """ return not self.inStack and not self.outStack # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty() def solve(): obj = MyQueue() assert obj.empty() obj.push(1) obj.push(2) assert not obj.empty() assert obj.peek() == 1 # not 2 assert not obj.empty() assert obj.pop() == 1 # not 2 assert obj.pop() == 2 assert obj.empty()
true
44bd4d30acfddb690556faaf26174f6a6faee6fe
Carvanlo/Python-Crash-Course
/Chapter 8/album.py
412
4.15625
4
def make_album(artist_name, album_title, track=''): """Return a dictionary of information of an album.""" album = {'artist': artist_name, 'title': album_title} if track: album['track'] = track return album album_1 = make_album('Adam Levine', 'Begin Again', 3) print(album_1) album_2 = make_album('Emma Stevens', 'Enchanted') print(album_2) album_3 = make_album('Blake Shelton', 'Based on a True Story') print(album_3)
true
94d9bca02dd044b5574522ef5f3185f8223a74e0
kumk/python_code
/donuts.py
593
4.15625
4
#Strings Exercise 1: Donuts # # Given an int count of a number of donuts, return a string of the form 'Number # #of donuts: <count>', where <count> is the number passed in. However, if the # #count is 10 or more, then use the word 'many' instead of the actual count. # So #donuts(5) returns 'Number of donuts: 5' and donuts(23) returns # 'Number of #donuts: many' import sys def numberofdonuts(count): if count < 10: print ("Number of donuts: ", count) else: print ("Number of #donuts: many") if __name__ == '__main__': numberofdonuts((int)(sys.argv[1]))
true
7b418a8b46b44fe6913f808024e6c2ba683885d2
loknath0502/python-programs
/28_local_global_variable.py
374
4.25
4
a=8 # global variable def n(): a=10 print("The local variable value is:",a) # local variable n() print("The global variable value is:",a) '''Note: The value of the global variable can be used by local function variable containing print . But the value of the local variable cannot be used by the global function variable containing print. '''
true
db8502678f3b850ad743cc8464436efcc6e01b20
ryanfirst/NextGen
/problem_types_set2.py
799
4.15625
4
# first_num = input('enter first number') # second_num = input('enter second number') # third_num = input('enter third number') # print(int(first_num) * int(second_num)) # print(int(first_num) * int(second_num) / int(third_num)) # num = input('pick a number') # print(int(num) % 2 == 0) # money = input('how much money will you be taking with you on vacation?') # print('you will have', end=' ') # print(int(money) * .86) # print(7 > 5 and 'b' > 'd') # print(7+5 and 'b' + 'd') # print(7 * 5 or 'b' * 'd') # name = input('what is your name?') # print(ord(name[0])) # word = input('pick any word') # print(word, 'is a great word') # ques = input('do you like that word') # # print('i agree') # # print(pow(4,2)) # # print(sum((3,5,2))) # a=8 # print(isinstance(a, int)) # print(vars()) # print(id(a))
true
09c8da67245a500ea982344061b5d25dbc1d0a58
olive/college-fund
/module-001/Ex1-automated.py
1,456
4.25
4
# 1*.1.1) Rewrite the following function so that instead of printing strings, # the strings are returned. Each print statement should correspond to # a newline character '\n' in the functiono's output. def bar_print(a, b, c): if a == b: print("1") elif b == c: print("2") if a == c: print("3") return else: print("4") print("5") def bar_string(a, b, c): return "" # Example rewrite: def foo_print(a, b): if a == b: print("1") return else: print("2") if a == 1: print("3") print("4") def foo_string(a, b): result = "" if a == b: result += "1\n" return result else: result += "2\n" if a == 1: result += "3\n" result += "4\n" return result def test_equals(s, answ): lines = s.split('\n')[:-1] if lines == answ: print("PASS") else: print("FAIL") def main(): test_equals(bar_string(1,1,2), ["1","4","5"]) test_equals(bar_string(2,1,1), ["2","4","5"]) test_equals(bar_string(1,2,1), ["3"]) # 1*.1.2) Write another call to test_equals that prints PASS using func. # 1*.1.3) The second argument to test_equals must be distinct from the # above three. # 1*.1.4) Write 3 distinct calls to test_equals that pass for foo_string # instead of bar_string if __name__ == '__main__': main()
true
e1146f7a613892b9d79b70a5fdf218eafd812681
AjayKumar2916/python-challenges
/047-task.py
280
4.15625
4
''' Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. ''' e = range(1, 21) a = filter(lambda x:x%2==0, e) print(list(a))
true
ed08b421996fab5b1db393c23496aff72939db24
svukosav/crm
/database.py
1,603
4.375
4
import sqlite3 db = sqlite3.connect("database") cursor = db.cursor() # cursor.execute("""DROP TABLE users""") if db: # Create a table cursor.execute("""CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT, phone TEXT, email TEXT unique, password TEXT)""") db.commit() name1 = 'Andres' phone1 = '3366858' email1 = 'user@example.com' password1 = '12345' name2 = 'John' phone2 = '5557241' email2 = 'johndoe@example.com' password2 = 'abcdef' # Inserting new entries cursor.execute("""INSERT INTO users(name, phone, email, password) VALUES (?,?,?,?)""", (name1, phone1, email1, password1)) id = cursor.lastrowid print("First user inserted") print("last row id: %d" % id) cursor.execute("""INSERT INTO users(name, phone, email, password) VALUES (?,?,?,?)""", (name2, phone2, email2, password2)) id = cursor.lastrowid print("Second user inserted") print("last row id: %d" % id) db.commit() # Reading entries cursor.execute("""SELECT name, email, phone FROM users""") # Get one user # user1 = cursor.fetchone() # print("Name: " + user1[0]) # Get all users for row in cursor: print('{0} : {1} , {2}'.format(row[0], row[1], row[2])) # Selecting one predefined user # user_id = 3 # cursor.execute("""SELECT name, email, phone FROM users WHERE id=?""", (user_id,)) # user = cursor.fetchone() # Updating users newphone = '3113093164' userid = 1 cursor.execute("""UPDATE users SET phone = ? WHERE id = ?""", (newphone, userid)) # Delete users userid = 2 cursor.execute(""" DELETE FROM users WHERE id = ?""", (userid,)) db.commit() # Drop a table cursor.execute("""DROP TABLE users""") db.commit() db.close()
true
4dd828096a5eb69c493930c8381a4b0bb6e7f9ca
si20094536/Pyton-scripting-course-L1
/q4.py
673
4.375
4
## 4. Given a list of non-empty tuples, return a list sorted in increasing order by the last element in each tuple. ##e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)] ## Hint: use a custom key= function to extract the last element form each tuple. ##i. [(1, 3), (3, 2), (2, 1)] ##ii. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] l1=[(1, 7), (1, 3), (3, 4, 5), (2, 2)] l2= [(1, 3), (3, 2), (2, 1)] l3= [(1, 7), (1, 3), (3, 4, 5), (2, 2)] def func(abc): print("The list before being sorted is : ",abc) abc.sort(key=lambda x: x[1]) print("The list are being sorted is : ",abc) func(l1) func(l2) func(l3)
true
9acba907b818c3e591571dbadaf3bdb751b91d99
kishan-pj/python_lab_exercise_1
/pythonproject_lab2/temperature.py
323
4.5
4
# if temperature is greater than 30, it's a hot day other wise if it's less than 10; # it's a cold day;otherwise,it's neither hot nor cold. temperature=int(input("enter the number: ")) if temperature>30: print("it's hot day") elif temperature<10: print("it's cold day") else: print("it's neither hot nor cold")
true