blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
e6a688b5a85a54fedd45925b8d263ed5f79a5b41
shardul1999/Competitive-Programming
/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.py
1,018
4.25
4
# implementing the function of Sieve of Eratosthenes def Sieve_of_Eratosthenes(n): # Creating a boolean array and # keeping all the entries as true. # entry will become false later on in case # the number turns out to be prime. prime_list = [True for i in range(n+1)] for number in range(2,n): # It is a prime if prime_list[number] doesn't change. if (prime_list[number] == True): # Updating the multiples of the "number" greater # than or equal to the square of this number. # all the numbers which are multiple of "number" and # are less than number2 have already been marked. for i in range(number * number, n+1, number): prime_list[i] = False # To print all the prime numbers for i in range(2, n+1): if prime_list[i]: print(i) # Driver Function if __name__=='__main__': n = 40 print("The prime numbers less than or equal to ",end="") print(n," are as follows: - ") Sieve_of_Eratosthenes(n)
true
94a4e95a13557630c6e6a551f297a934b01e72f1
gadamsetty-lohith-kumar/skillrack
/N Equal Strings 09-10-2018.py
836
4.15625
4
''' N Equal Strings The program must accept a string S and an integer N as the input. The program must print N equal parts of the string S if the string S can be divided into N equal parts. Else the program must print -1 as the output. Boundary Condition(s): 2 <= Length of S <= 1000 2 <= N <= Length of S Example Input/Output 1: Input: whiteblackgreen 3 Output: white black green Explanation: Divide the string whiteblackgreen into 3 equal parts as white black green Hence the output is white black green Example Input/Output 2: Input: pencilrubber 5 Output: -1 ''' #Your code below a=(input().split()) l=len(a[0]) k=int(a[1]) m=l/k if(l%k==0): for i in range (0,l): print(a[0][i],end="") if (i+1)%(m)==0: print(end=" ") else: print("-1")
true
cb332c445ab691639f8b6fb76e25bf95ba5f7af4
gadamsetty-lohith-kumar/skillrack
/Remove Alphabet 14-10-2018.py
930
4.28125
4
''' Remove Alphabet The program must accept two alphabets CH1 and CH2 as the input. The program must print the output based on the following conditions. - If CH1 is either 'U' or 'u' then print all the uppercase alphabets except CH2. - If CH1 is either 'L' or 'l' then print all the lowercase alphabets except CH2. - For any other values of CH1 then print INVALID. Example Input/Output 1: Input: U v Output: A B C D E F G H I J K L M N O P Q R S T U W X Y Z Example Input/Output 2: Input: L C Output: a b d e f g h i j k l m n o p q r s t u v w x y z ''' #Your code below l=input().split() if l[0] in ('UuLl'): if l[0]=='U' or l[0]=='u': s='A' l[1]=l[1].upper() elif l[0]=='L' or l[0]=='l': s='a' l[1]=l[1].lower() for i in range (0,26): if s!=l[1]: print(s,end=" ") s=chr(ord(s)+1) else: print("INVALID")
true
51edd7c35ccfe2b7d07bcbfe97395f0c88c251fa
TAMU-BMEN207/Apple_stock_analysis
/OHLC_plots_using_matplotlib.py
2,535
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 13 21:20:18 2021 @author: annicenajafi Description: In this example we take a look at Apple's stock prices and write a program to plot an OHLC chart. To learn more about OHLC plots visit https://www.investopedia.com/terms/o/ohlcchart.asp #Dataset Source: downloaded from Kaggle ==> https://www.kaggle.com/meetnagadia/apple-stock-price-from-19802021?select=AAPL.csv #Make sure you have studied: Numpy, Matplotlib, Pandas """ #import necessary modules import matplotlib.pyplot as plt import pandas as pd import numpy as np #Read csv file using pandas df = pd.read_csv("/Users/annicenajafi/Downloads/AAPL.csv") #let's take a look at our data df.head() ''' Let's only look at recent data more specifically from 2020 to the most recent data But first we have to convert our date column to datetime type so we would be able to treat it as date ''' df['Date'] = pd.to_datetime(df['Date']) df = df[df['Date'].dt.year > 2020] #Hold on let's look at the dataframe again df.head() #Hmmm... Do you see that the index starts at 10100? #Question: what problems may it cause if we don't reset the index?! #Let's fix it so it starts from 0 like the original df df.reset_index(inplace=True) df.head() #Let's define the x axis x_vals = np.arange(0,len(df['Date'])) fig, ax = plt.subplots(1, figsize=(50,10)) ''' Let's iterate through the rows and plot a candle stick for every date What we do is we plot a vertical line that starts from the low point and ends at the high point for every date ''' for idx, val in df.iterrows(): #Change the color to red if opening price is more than closing price #Otherwise change it to green if val['Open'] > val['Close']: col = 'red' else: col ='green' plt.plot([x_vals[idx], x_vals[idx]], [val['Low'], val['High']], color=col) #add a horizontal line to the left to show the openning price plt.plot([x_vals[idx], x_vals[idx]-0.05], [val['Open'], val['Open']], color=col) #add a horizontal line to the right to show the closing price plt.plot([x_vals[idx], x_vals[idx]+0.05], [val['Close'], val['Close']], color=col) #Change the x axis tick marks plt.xticks(x_vals[::50], df.Date.dt.date[::50]) #change the y label plt.ylabel('USD') #Change the title of the plot plt.title('Apple Stock Price', loc='left', fontsize=20) #let's show the plot plt.show() ''' Texas A&M University BMEN 207 Fall 2021 '''
true
68bb040d0e9828fc34660de7b3d0d4ffa6e36d2d
s-nilesh/Leetcode-May2020-Challenge
/14-ImplementTrie(PrefixTree).py
1,854
4.40625
4
#PROBLEM # Implement a trie with insert, search, and startsWith methods. # Example: # Trie trie = new Trie(); # trie.insert("apple"); # trie.search("apple"); // returns true # trie.search("app"); // returns false # trie.startsWith("app"); // returns true # trie.insert("app"); # trie.search("app"); // returns true # Note: # You may assume that all inputs are consist of lowercase letters a-z. # All inputs are guaranteed to be non-empty strings. #SOLUTION class Trie: def __init__(self): """ Initialize your data structure here. """ self.children = {} self.marker = '$' def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ cur = self.children for c in word: if c not in cur: cur[c] = {} cur = cur[c] cur[self.marker] = True def __search__(self, word): cur = self.children for c in word: if c not in cur: return False cur = cur[c] return cur def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ found = self.__search__(word) return found and len(found) > 0 and self.marker in found def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ if len(prefix) == 0: return True found = self.__search__(prefix) return found and len(found) > 0 # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
e8b6ef6df71a327b6575593166873c6576f78f7b
SirazSium84/100-days-of-code
/Day1-100/Day1-10/Bill Calculator.py
911
4.1875
4
print("Welcome to the tip calculator") total_bill = float(input("What was the total bill? \n$")) percentage = int(input( "What percentage tip would you like to give ? 10, 12 or 15?\n")) people = int(input("How many people to split the bill? \n")) bill_per_person = (total_bill + total_bill * (percentage)/100)/(people) print("Each person should pay : ${:.2f}".format(bill_per_person)) # # print(123_567_789) # # 🚨 Don't change the code below 👇 # age = input("What is your current age?") # # 🚨 Don't change the code above 👆 # # Write your code below this line 👇 # def time_left(age): # years_left = 90 - int(age) # months_left = years_left * 12 # weeks_left = years_left * 52 # days_left = years_left * 365 # return days_left, weeks_left, months_left # days, weeks, months = time_left(age) # print(f"You have {days} days, {weeks} weeks, and {months} months left")
true
24a69e38cdc2156452898144165634fd6579ef6c
keyurgolani/exercism
/python/isogram/isogram.py
564
4.375
4
def is_isogram(string): """ A function that, given a string, returns if the string is an isogram or not Isogram is a string that has all characters only once except hyphans and spaces can appear multiple times. """ lookup = [0] * 26 # Assuming that the string is case insensitive string = string.lower() for char in string: if 'a' <= char <= 'z': index = ord(char) - ord('a') if lookup[index] == 0: lookup[index] = 1 else: return False return True
true
8af76392fb8ade32aa16f998867a9312303cd2fa
porigonop/code_v2
/linear_solving/Complex.py
2,070
4.375
4
#!/usr/bin/env python3 class Complex: """ this class represent the complex number """ def __init__(self, Re, Im): """the numer is initiate with a string as "3+5i" """ try: self.Re = float(Re) self.Im = float(Im) except: raise TypeError("please enter a correct number") def __str__(self): """ allow the user to print the complex number """ if self.Im < 0: return str(self.Re) + str(self.Im) + "i" return str(self.Re) + "+" + str(self.Im) + "i" def __repr__(self): """ allow the user to print the complex number """ if self.Im < 0: return str(self.Re) + str(self.Im) + "i" return str(self.Re) + "+" + str(self.Im) + "i" def multiplicate_by(self, number): """allow the multiplication """ answerRE = 0 answerIm = 0 if type(number) is Complex: Re = self.Re answerRe = Re * number.Re -\ self.Im * number.Im answerIm = Re * number.Im +\ self.Im * number.Re else: try: number = float(number) except: raise TypeError("please enter a valid number") answerRe = self.Re * number answerIm = self.Im * number return Complex(answerRe, answerIm) def divide_by(self, number): """allow the division """ answerRE = 0 answerIm = 0 if type(number) is Complex: numerator = self.multiplicate_by(Complex(number.Re, - number.Im)) answerRe = numerator.divide_by(number.Re **2 + number.Im **2).Re answerIm = numerator.divide_by(number.Re **2 + number.Im **2).Im else: try: number = float(number) except: raise TypeError("please enter a valid number") answerRe = self.Re / number answerIm = self.Im / number return Complex(answerRe, answerIm) def sum_by(self, number): """allow addition and subtraction """ answerRe = 0 answerIm = 0 if type(number) is Complex: answerRe = self.Re + number.Re answerIm = self.Im + number.Im else: try: number = float(number) except: raise TypeError("please enter a valid number") answerRe = self.Re + number answerIm = self.Im return Complex(answerRe, answerIm)
true
af2c02c975c53c1bd12955b8bbe72bac35ab54fd
BryanBain/Statistics
/Python_Code/ExperimProbLawOfLargeNums.py
550
4.1875
4
""" Purpose: Illustrate how several experiments leads the experimental probability of an event to approach the theoretical probability. Author: Bryan Bain Date: June 5, 2020 File: ExperimProbLawOfLargeNums.py """ import random as rd possibilities = ['H', 'T'] num_tails = 0 num_flips = 1_000_000 # change this value to adjust the number of coin flips. for _ in range(num_flips): result = rd.choice(possibilities) # flip the coin if result == 'T': num_tails += 1 print(f'The probability of flipping tails is {num_tails/num_flips}')
true
d2e63bfba6fdfa348260d81a84628cacc6243a18
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
/Level 1/Task 7/investment_calculator.py
986
4.125
4
"""A program on an Investment Calculator""" import math # user inputs # the amount they are depositing P = int(input("How much are you depositing? : ")) # the interest rate i = int(input("What is the interest rate? : ")) # the number of years of the investment t = int(input("Enter the number of years of the investment: ")) # simple or compound interest interest = input("Enter either 'Simple' or 'Compound' interest: ").lower() # the 'r' variable is the interest divided by 100 r = i / 100 # check if the user entered either Simple or Compound and perform the relevant calculations # Simple Interest Formula : A = P*(1+r*t) N.B. A is the total received or accumulated amount if interest == 'simple': A = P * (1 + r*t) elif interest == 'compound': # Compound Interest Formula : A = P* math.pow((1+r),t) A = P * math.pow((1 + r), t) # t is the power # print out the Accrued amount ie. the received or accumulated amount print(f"The Accrued amount is : {round(A, 2)}")
true
720fefd121f1bc900454dcbfd668b12f0ad9f551
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
/Level 1/Task 2/conversion.py
445
4.25
4
"""Declaring and printing out variables of different data types""" # declare variables num1 = 99.23 num2 = 23 num3 = 150 string1 = "100" # convert the variables num1 = int(num1) # convert into an integer num2 = float(num2) # convert into a float num3 = str(num3) # convert into a string string1 = int(string1) # convert string to an integer # print out the variables with new data types print(num1) print(num2) print(num3) print(string1)
true
1143957f959a603f694c7ed6012acf2f7d465a4c
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
/Level 1/Task 7/control.py
258
4.125
4
"""Program that evaluates a person's age""" # take in user's age age = int(input("Please enter in your age: ")) # evaluate the input if age >= 18: print("You are old enough!") elif age >= 16: print("Almost there") else: print("You're just too young!")
true
aa41b93ab44deded12fa4705ea497d2c6bbc74e8
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
/Level 1/Task 10/logic.py
648
4.1875
4
"""A program about fast food service""" menu_items = ['Fries', 'Beef Burger', 'Chicken Burger', 'Nachos', 'Tortilla', 'Milkshake'] print("***MENU***") print("Pick an item") print("1.Fries\n2.Beef Burger\n3.Chicken Burger\n4.Nachos\n5.Tortilla\n6.Milkshake") choice = int(input("\nType in number: ")) for i in menu_items: if choice == i: print(f"You have chosen {choice}") # Nothing gets printed out """The reason why it doesn't print out is because when we are looping through the list it is printing out the strings, not the positions. So, if we are going to compare a string and an integer then it wont reach the print statement"""
true
7eafe6d1231ff66b56fdeab6c409922e82ec5691
purvajakumar/python_prog
/pos.py
268
4.125
4
#check whether the nmuber is postive or not n=int(input("Enter the value of n")) if(n<0): print("negative number") elif(n>0): print("positive number") else: print("The number is zero") #output """Enter the value of n 6 positive number"""
true
0fc620866a5180d3a6d0d51547d74896a6d3c193
ky822/assignment7
/yl3068/questions/question3.py
734
4.3125
4
import numpy as np def result(): print '\nQuestion Three:\n' #Generate 10*3 array of random numbers in the range [0,1]. initial = np.random.rand(10,3) print 'The initial random array is:\n{}\n'.format(initial) #Question a: pick the number closest to 0.5 for each row initial_a = abs(initial-0.5).min(axis=1) #Question b: find the column for each of the numbers closest to 0.5 colunm_ix = (abs(initial-0.5).argsort())[:,0] #Question c: a new array containing numbers closest to o.5 in each row row_ix = np.arange(len(initial)) result = initial[row_ix, colunm_ix] print 'The result array containing numbers closest to 0.5 in each row of initial array is:\n{}\n'.format(result)
true
39e36aeb85538a4be57dd457d005fd12bc642e25
ky822/assignment7
/ql516/question3.py
1,927
4.1875
4
# -*- coding: utf-8 -*- import numpy as np def array_generate(): """ generate a 10x3 array of random numbers in range[0,1] """ array = np.random.rand(10,3) return array def GetClosestNumber(array): """ for each row, pick the number closest to .5 """ min_index = np.argmin(np.abs(array-0.5),1) closest_array = array[np.arange(10),min_index] return closest_array def GetClosestNumberBySort(array): """ Generte an array contain the numbers closest to 0.5 in each rows Argument ======== array: numpy array Return ====== an array contain the closest numbers Example ======= >>>array1 = array_generate() >>>array1 array([[ 0.63665097, 0.50696162, 0.76121097], [ 0.68714886, 0.20228392, 0.52424866], [ 0.3275332 , 0.76667842, 0.41314787], [ 0.05645787, 0.6146244 , 0.69211519], [ 0.13655137, 0.84564668, 0.57381465], [ 0.65070546, 0.7825995 , 0.67390848], [ 0.23796975, 0.97312122, 0.87593416], [ 0.39804522, 0.30356075, 0.79707104], [ 0.45504483, 0.28996881, 0.71733035], [ 0.94605093, 0.65489037, 0.54693193]]) >>>print GetClosestNumberBySort(array1) array[ 0.50696162 0.52424866 0.41314787 0.6146244 0.57381465 0.65070546 0.23796975 0.39804522 0.45504483 0.54693193] """ row_number = 10 array_abs = np.abs(array-0.5) array_sorted_index = np.argsort(array_abs) sorted_array = array[np.arange(row_number).reshape((row_number,1)),array_sorted_index] closest_array = sorted_array[:,0] return closest_array def main(): array = array_generate() print array #print "get closest number: \n",GetClosestNumber(array) print "get closest number for each row: \n", GetClosestNumberBySort(array) if __name__ == "__main__": main()
true
7d82924a9a4123d5a340cbbd352ddea2bd4b3e18
ky822/assignment7
/wl1207/question1.py
694
4.125
4
import numpy as np def function(): print "This is the answer to question1 is:\n" array = np.array(range(1,16)).reshape(3,5).transpose() print "The 2-D array is:\n",array,"\n" array_a = array[[1,3]] print "The new array contains the 2nd column and 4th rows is:\n", array_a, "\n" array_b = array[:, 1] print "The new array contains the 2nd column is:\n",array_b, "\n" array_c = array[1:4, :] print "The new array contains all the elements in the rectangular section is:\n", array_c, "\n" array_d = array[np.logical_and(array>=3, array<=11)] print "The new array contains all the elements between 3 and 11 is:\n", array_d, "\n" if __name__ =='__main__': function()
true
ae63f36897ced379ec1f7b20bc399182c36682c5
Kamilet/learning-coding
/python/ds_str_methods.py
305
4.1875
4
#这是一个字符串对象 name = 'Kamilet' if name.startswith('Kam'): print('Yes, the string starts with "Kam"') if 'a' in name: print('Yes, contains "a"') if name.find('mil') != -1: print('Yes, contains "mil"') delimiter='_*_' mylist = ['aaa', 'bbb', 'ccc', 'ddd'] print(delimiter.join(mylist))
true
5b01a489805c58909979dae65c04763df722bfaa
Sauvikk/practice_questions
/Level6/Trees/Balanced Binary Tree.py
1,233
4.34375
4
# Given a binary tree, determine if it is height-balanced. # # Height-balanced binary tree : is defined as a binary tree in which # the depth of the two subtrees of every node never differ by more than 1. # Return 0 / 1 ( 0 for false, 1 for true ) for this problem # # Example : # # Input : # 1 # / \ # 2 3 # # Return : True or 1 # # Input 2 : # 3 # / # 2 # / # 1 # # Return : False or 0 # Because for the root node, left subtree has depth 2 and right subtree has depth 0. # Difference = 2 > 1. from Level6.Trees.BinaryTree import BinaryTree class Solution: def is_balanced(self, root): if root is None: return True if self.get_depth(root) == -1: return False return True def get_depth(self, root): if root is None: return 0 left = self.get_depth(root.left) right = self.get_depth(root.right) if left == -1 or right == -1: return -1 if abs(left - right) > 1: return -1 return max(left, right) + 1 A = BinaryTree() A.insert(100) A.insert(102) A.insert(96) res = Solution().is_balanced(A.root) print(res)
true
9cea8f90b8556dcacec43dd9ae4a7b4500db2114
Sauvikk/practice_questions
/Level6/Trees/Sorted Array To Balanced BST.py
951
4.125
4
# Given an array where elements are sorted in ascending order, convert it to a height balanced BST. # # Balanced tree : a height-balanced binary tree is defined as a # binary tree in which the depth of the two subtrees of every node never differ by more than 1. # Example : # # # Given A : [1, 2, 3] # A height balanced BST : # # 2 # / \ # 1 3 from Level6.Trees.BinaryTree import BinaryTree, Node class Solution: def generate_bt(self, num, start, end): if start > end: return None mid = int((start+end)/2) node = Node(num[mid]) node.left = self.generate_bt(num, start, mid-1) node.right = self.generate_bt(num, mid+1, end) return node def solution(self, num): if num is None or len(num) == 0: return num return self.generate_bt(num, 0, len(num)-1) res = Solution().solution([1, 2, 3, 4, 5, 6, 7]) BinaryTree().pre_order(res)
true
7708927408c989e6d7d6a297eb62d27ca489ee49
Sauvikk/practice_questions
/Level6/Trees/BinaryTree.py
2,379
4.15625
4
# Implementation of BST class Node: def __init__(self, val): # constructor of class self.val = val # information for node self.left = None # left leef self.right = None # right leef self.level = None # level none defined self.next = None # def __str__(self): # return str(self.val) # return as string class BinaryTree: def __init__(self): # constructor of class self.root = None def insert(self, val): # create binary search tree nodes if self.root is None: self.root = Node(val) else: current = self.root while 1: if val < current.val: if current.left: current = current.left else: current.left = Node(val) break elif val > current.val: if current.right: current = current.right else: current.right = Node(val) break else: break def bft(self): # Breadth-First Traversal self.root.level = 0 queue = [self.root] out = [] current_level = self.root.level while len(queue) > 0: current_node = queue.pop(0) if current_node.level > current_level: current_level += 1 out.append("\n") out.append(str(current_node.val) + " ") if current_node.left: current_node.left.level = current_level + 1 queue.append(current_node.left) if current_node.right: current_node.right.level = current_level + 1 queue.append(current_node.right) print(''.join(out)) def in_order(self, node): if node is not None: self.in_order(node.left) print(node.val) self.in_order(node.right) def pre_order(self, node): if node is not None: print(node.val) self.pre_order(node.left) self.pre_order(node.right) def post_order(self, node): if node is not None: self.post_order(node.left) self.post_order(node.right) print(node.val)
true
4a0eca90de3ce7fb0ab6decb0ec6aadb32c1a9fa
Sauvikk/practice_questions
/Level6/Trees/Identical Binary Trees.py
998
4.15625
4
# Given two binary trees, write a function to check if they are equal or not. # # Two binary trees are considered equal if they are structurally identical and the nodes have the same value. # # Return 0 / 1 ( 0 for false, 1 for true ) for this problem # # Example : # # Input : # # 1 1 # / \ / \ # 2 3 2 3 # # Output : # 1 or True from Level6.Trees.BinaryTree import BinaryTree class Solution: def solution(self, rootA, rootB): if rootA == rootB: print('h') return True if rootA is None or rootB is None: return False # if rootA is None and rootB is None: # return True return ((rootA.val == rootB.val) and self.solution(rootA.left, rootB.left) and self.solution(rootA.right, rootB.right)) A = BinaryTree() A.insert(100) A.insert(102) A.insert(96) B = BinaryTree() B.insert(100) B.insert(102) B.insert(96) res = Solution().solution(A.root, B.root) print(res)
true
8bf85ec04b5f5619a235f1506b7226597a75bef0
Kaushikdhar007/pythontutorials
/kaushiklaptop/NUMBER GUESS.py
766
4.15625
4
n=18 print("You have only 5 guesses!! So please be aware to do the operation\n") time_of_guessing=1 while(time_of_guessing<=5): no_to_guess = int(input("ENTER your number\n")) if no_to_guess>n: print("You guessed the number above the actual one\n") print("You have only", 5 - time_of_guessing, "more guesses") time_of_guessing = time_of_guessing + 1 elif no_to_guess<n: print("You guessed the number below the actual one\n") print("You have only",5-time_of_guessing,"more guesses") time_of_guessing=time_of_guessing+1 continue elif no_to_guess==n: print("You have printed the actual number by guessing successfully at guess no.",time_of_guessing) break
true
be99bff4b371868985a64a79a23e34be58a0831f
KrishnaPatel1/python-workshop
/theory/methods.py
1,722
4.28125
4
def say_hello(): print("Hello") print() say_hello() # Here is a method that calculates the double of a number def double(number): result = number * 2 return result result = double(2) print(result) print() # Here is a method that calculates the average of a list of numbers def average(list_of_numbers): total = 0 number_of_items_in_list = 0 average = 0 for number in list_of_numbers: number_of_items_in_list = number_of_items_in_list + 1 total = total + number average = total/number_of_items_in_list return average a_bunch_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = average(a_bunch_of_numbers) print(result) print() # Challenge 1 # Create a function that takes a number # it returns the negative of the number # Note, use print(method) to print out the value print("Challenge 1:") # Challenge 2 # Imagine you are given some product that has some cost to it (e.g. $14.99) # calculate the tax of the product and and it to the cost of the product # return the total cost of the product # assume the tax is 15% # Note, use print() to print out the result of the method print() print("Challenge 2:") # Challenge 3 # Create a method that # takes in a student's test score and the total amount of points in the test # returns the result of the student in percentage print() print("Challenge 3:") # Challenge 4 # Create a method that: # takes in one number # if even, print the number and state that it is even # if odd, print the number and state that it is odd # if less than zero, print the number and state that it is negative # if the number is a combination of the above conditions, then print both conditions (e.g. -2 is even and negative) print() print("Challenge 4:")
true
06bea009748a261e7d0c893a18d60e4b625d6243
hoanghuyen98/fundamental-c4e19
/Session05/homeword/Ex_1.py
1,302
4.25
4
inventory = { 'gold' : 500, 'pouch': ['flint', 'twine', 'gemstone'], 'backpack' : ['xylophone', 'dagger', 'bedroll', 'bread loaf'] } # Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list print("1: Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list ") print() print(" =====>> List ban đầu : ") print(inventory) inventory['pocket'] = ['seashell', 'strange', 'berry', 'lint'] print(" =====>> List sau khi thêm : ") print(inventory) print() print("* "*20) # Then remove('dagger') from the list of items stored under the 'backpack' key print("2: Then remove('dagger') from the list of items stored under the 'backpack' key") print() key = "backpack" if key in inventory: value = inventory[key] value.pop(1) print(" =====>> List sau khi xóa value dagger của key 'backpack ") print() print(inventory) else: print(" not found ") print() print("* "*20) # Add 50 to the number stored under the 'gold' key. print("3: Add 50 to the number stored under the 'gold' key.") print() key_1 = 'gold' if key_1 in inventory: inventory[key_1] += 50 print(" =====>> List sau khi thêm 50 vào 500 ") print() print(inventory) print() else: inventory[key_1] = 50 print(inventory)
true
e1139905c3f17bd9e16a51a69853a0923160c84f
bbaja42/projectEuler
/src/problem14.py
1,496
4.15625
4
''' The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. ''' #Contains maximum chain length for each found origin number cache_numbers = {} def find_start_number(): ''' Find start number with largest chain Uses cache for found numbers as an optimization ''' max_value = 1 index = 0 for i in range(2, 1000000): cache_numbers[i] = calc_chain(i) if cache_numbers[i] > max_value: max_value = cache_numbers[i] index = i return index def calc_chain(n): if n in cache_numbers: return cache_numbers[n] if n == 1: return 1 result = 1 if (n % 2 == 0): result += calc_chain(n // 2) else: result += calc_chain(3 * n + 1) return result print ("Chain is {}".format(find_start_number())) import timeit t = timeit.Timer("find_start_number", "from __main__ import find_start_number") print ("Average running time: {} seconds".format(t.timeit(1000)))
true
fc846895589cb0b3d0227622ca53c4c6a62b61bc
Mahedi522/Python_basic
/strip_function.py
384
4.34375
4
# Python3 program to demonstrate the use of # strip() method string = """ geeks for geeks """ # prints the string without stripping print(string) # prints the string by removing leading and trailing whitespaces print(string.strip()) # prints the string by removing geeks print(string.strip(' geeks')) a = list(map(int, input().rstrip().split())) print(a) print(type(a[1]))
true
0b9e842cbeb52e819ecc2a10e135008f4380f8ed
monadplus/python-tutorial
/07-input-output.py
1,748
4.34375
4
#!/user/bin/env python3.7 # -*- coding: utf8 -*- ##### Fancier Output Formatting #### year = 2016 f'The current year is {year}' yes_votes = 1/3 'Percentage of votes: {:2.2%}'.format(yes_votes) # You can convert any variable to string using: # * repr(): read by the interpreter # * str(): human-readable s = "Hello, world." str(s) repr(s) #### Formatted String Literals #### name = 'arnau' f'At least 10 chars: {name:10}' # adds whitespaces # * !a ascii() # * !s str() # * !r repr() f'My name is {name!r}' #### The String format() Method #### '{1} and {0}'.format('spam', 'eggs') 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible') # :d for decimal format table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table)) print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) #### Reading and Writing Files ##### # By default is opened for text mode #f = open('foo', 'x') # 'a' to append instead of erasing # 'r+' reading/writing # 'b' for binary mode # 'x' new file and write #f.write("Should not work") #f.close() with open('lore.txt', 'r') as f: # print(f.readline()) # print(f.read(100)) # print(f.read()) for line in f: print(line, end='') f = open('lore.txt', 'rb+') f.write(b'0123456789abcdef') f.seek(5) # Go to the 6th byte in the file f.read(1) f.seek(-3, 2) # Go to the 3rd byte before the end f.read(1) #### JSON #### import json json.dumps([1, 'simple', 'list']) f = open('foo.json', 'r+') json.dump(['i', 'simple', 'list'], f) f.seek(0) # rewind x = json.load(f) print(x) f.close()
true
c6145249ef56fe9890f142f597766fdb55200466
Ahmad-Saadeh/calculator
/calculator.py
810
4.125
4
def main(): firstNumber = input("Enter the first number: ") secondNumber = input("Enter the second number: ") operation = input("Choose one of the operations (*, /, +, -) ") if firstNumber.isdigit() and secondNumber.isdigit(): firstNumber = int(firstNumber) secondNumber = int(secondNumber) if operation == "*": print("The answer is {}".format(firstNumber * secondNumber)) elif operation == "/": print("The answer is {}".format(firstNumber / secondNumber)) elif operation == "+": print("The answer is {}".format(firstNumber + secondNumber)) elif operation == "-": print("The answer is {}".format(firstNumber - secondNumber)) else: print("Invalid Operation!") else: print("Invalid Numbers!") if __name__ == '__main__': main()
true
4f603beccd737bea2d9ebd9d92bf3013dc91b9d1
surajkumar0232/recursion
/binary.py
233
4.125
4
def binary(number): if number==0: return 0 else: return number%2+10 * binary(number//2) if __name__=="__main__": number=int(input("Enter the numner which binary you want: ")) print(binary(number))
true
4647a038acd767895c4fd6cdbfcc130ef60a87ce
shreeyash-hello/Python-codes
/leap year.py
396
4.1875
4
while True : year = int(input("Enter year to be checked:")) string = str(year) length = len(string) if length == 4: if(year%4==0 and year%100!=0 or year%400==0): print("The year is a leap year!") break else: print("The year isn't a leap year!") break else: print('enter appropriate year')
true
b74ba7ee11dafa4f0482c903eeee240142181873
bengovernali/python_exercises
/tip_calculator_2.py
870
4.1875
4
bill = float(input("Total bill amount? ")) people = int(input("Split how many ways? ")) service_status = False while service_status == False: service = input("Level of service? ") if service == "good": service_status = True elif service == "fair": service_status = True elif service_status == "bad": service_status = True def calculate_tip(bill, service): if service == "good": tip_percent = 0.20 elif service == "fair": tip_percent = 0.15 elif service == "bad": tip_percent = 0.10 tip_amount = bill * tip_percent print("Tip amount: $%.2f" % tip_amount) total_amount = bill + tip_amount print("Total amount: $%.2f" % total_amount) amount_per_person = total_amount / people print("Amount per person: $%.2f" % amount_per_person) calculate_tip(bill, service)
true
e54410cf9db5300e6ef5c84fd3432b1723c017c6
MeganTj/CS1-Python
/lab5/lab5_c_2.py
2,836
4.3125
4
from tkinter import * import random import math # Graphics commands. def draw_line(canvas, start, end, color): '''Takes in four arguments: the canvas to draw the line on, the starting location, the ending location, and the color of the line. Draws a line given these parameters. Returns the handle of the line that was drawn on the canvas.''' start_x, start_y = start end_x, end_y = end return canvas.create_line(start_x, start_y, end_x, end_y, fill = color, width = 3) def draw_star(canvas, n, center, color): '''Takes in four arguments: the canvas to draw the line on, the number of points that the star has (a positive odd integer no smaller than 5), the center of the star, and the color of the star. Draws a star pointed vertically upwards given these parameters and with a randomly chosen radius between 50 to 100 pixels. Returns a list of the handles of all the lines drawn.''' points = [] lines = [] r = random.randint(50, 100) center_x, center_y = center theta = (2 * math.pi) / n for p in range(n): x = r * math.cos(theta * p) y = r * math.sin(theta * p) points.append((y + center_x, -x + center_y)) increment = int((n - 1) / 2) for l in range(n): end_index = (l + increment) % n lines.append(draw_line(canvas, points[l], points[end_index], color)) return lines def random_color(): '''Generates random color values in the format recognized by the tkinter graphics package, of the form #RRGGBB''' seq = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] rand = '#' for i in range(6): rand += random.choice(seq) return rand # Event handlers. def key_handler(event): '''Handle key presses.''' global stars global color global n key = event.keysym if key == 'q': exit_python(event) if key == 'c': color = random_color() if key == 'plus': n += 2 if key == 'minus': if n >= 7: n -= 2 if key == 'x': for lines in stars: for line in lines: canvas.delete(line) stars = [] def button_handler(event): '''Handle left mouse button click events.''' global stars lines = draw_star(canvas, n, (event.x, event.y), color) stars.append(lines) def exit_python(event): '''Exit Python.''' quit() if __name__ == '__main__': root = Tk() root.geometry('800x800') canvas = Canvas(root, width=800, height=800) canvas.pack() stars = [] color = random_color() n = 5 # Bind events to handlers. root.bind('<Key>', key_handler) canvas.bind('<Button-1>', button_handler) # Start it up. root.mainloop()
true
f84fdef224b8a97d88809dcf45fb0f574dc61ed4
SnarkyLemon/VSA-Projects
/proj06/proj06.py
2,181
4.15625
4
# Name: # Date: # proj06: Hangman # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ # print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) # print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere def hangman(): wordlist = load_words() word = choose_word(wordlist) l = len(word) # print l ans_list = ["_"]*l print ans_list numguess = 6 print l, "letters long." print word while numguess > 0: guess = raw_input("Guess a letter or word ") for letter in guess: if letter in word: for num in range(len(word)): if guess == word[num]: ans_list[num] = guess print "You've guessed correctly." print ans_list print str(ans_list) if guess == word: print("Wow I'm impressed") if str(ans_list) == word: print "You've correctly guessed the word. Also, this took like 6 hours to make, so no big deal." elif guess not in word: numguess -= 1 print ("Sorry, that's incorrect") if numguess == 0: print "sorry, out of tries" if ans_list == word: print "You win" print ans_list print str(ans_list), "is the string answer list" hangman()
true
d7736ee0897218affa62d98dbb4117ff96d59818
djmgit/Algorithms-5th-Semester
/FastPower.py
389
4.28125
4
# function for fast power calculation def fastPower(base, power): # base case if power==0: return 1 # checking if power is even if power&1==0: return fastPower(base*base,power/2) # if power is odd else: return base*fastPower(base*base,(power-1)/2) base=int(raw_input("Enter base : ")) power=int(raw_input("Enter power : ")) result=fastPower(base,power) print result
true
c1b83c2ac9d096558fa7188d269cc55f2a25ecf1
tolu1111/Python-Challenge
/PyBank.py
2,088
4.1875
4
#Import Dependencies perform certain functions in python import os import csv # define where the data is located bankcsv = os.path.join("Resources", "budget_data.csv") # define empty lists for Date, profit/loss and profit and loss changes Profit_loss = [] Date = [] PL_Change = [] # Read csv file with open(bankcsv, newline= '') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csvheader = next(csvreader) # calculate the values for the profit/loss and the dates # store respective values in appropraite lists created earlier for row in csvreader: Profit_loss.append(float(row[1])) Date.append(row[0]) #Print the calculated values print("Financial Analysis") print("-----------------------------------") print(f"Total Months: {len(Date)}") print(f"Total Revenue: {sum(Profit_loss)}") #Calculate the average revenue change, the greatest revenue increase and the greatest revenue decrease for i in range(1,len(Profit_loss)): PL_Change.append(Profit_loss[i] - Profit_loss[i-1]) avg_PL_Change = (sum(PL_Change)/len(PL_Change)) max_PL_Change = max(PL_Change) min_PL_Change = min(PL_Change) max_PL_Change_date = str(Date[PL_Change.index(max(PL_Change)) + 1]) min_PL_Change_date = str(Date[PL_Change.index(min(PL_Change)) + 1]) # print the calculated values print(f"Avereage Revenue Change: {round(avg_PL_Change,2)}") print(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}") print(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}") #export text file p = open("PyBank.txt","w+") p.write("Financial Analysis\n") p.write("-----------------------------------\n") p.write(f"Total Months: {len(Date)}\n") p.write(f"Total Revenue: {sum(Profit_loss)}\n") p.write(f"Avereage Revenue Change: {round(avg_PL_Change,2)}\n") p.write(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}\n") p.write(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}\n") p.close()
true
317e92540d3a6e00bec3dcddb29669fe4806c7fa
Frank1963-mpoyi/REAL-PYTHON
/FOR LOOP/range_function.py
2,163
4.8125
5
#The range() Function ''' a numeric range loop, in which starting and ending numeric values are specified. Although this form of for loop isn’t directly built into Python, it is easily arrived at. For example, if you wanted to iterate through the values from 0 to 4, you could simply do this: ''' for n in (0, 1, 2, 3, 4): print(n) # This solution isn’t too bad when there are just a few numbers. # But if the number range were much larger, it would become tedious # pretty quickly. ''' Happily, Python provides a better option—the built-in range() function, which returns an iterable that yields a sequence of integers. range(<end>) returns an iterable that yields integers starting with 0, up to but not including <end>: ''' print() x = range(5) print(x) print(type(x)) print(range(0, 15)) # Note that range() returns an object of class range, not a list or tuple of the values. Because a range object is an iterable, you can obtain the values by iterating over them with a for loop: x = range(5) list(x) tuple(x) print(list(x)) print(tuple(x)) for n in x: print(n) # However, when range() is used in code that is part of a larger application, # it is typically considered poor practice to use list() or tuple() in this way. # Like iterators, range objects are lazy—the values in the specified range are not # generated until they are requested. Using list() or tuple() on a range object forces # all the values to be returned at once. This is rarely necessary, and if the list is long, # it can waste time and memory. print(list(range(5, 20, 3))) #range(<begin>, <end>, <stride>) returns an iterable that yields integers starting with # <begin>, up to but not including <end>. If specified, <stride> indicates an amount to skip # between values (analogous to the stride value used for string and list slicing): #If <stride> is omitted, it defaults to 1: print( list(range(5, 10, 1))) print( list(range(5, 10)))# if stride is omiited the default is one print(list(range(-5, 5))) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] print(list(range(5, -5)))#[] print(list(range(5, -5, -1)))# [5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
true
1eec2e1904286641b7140f572c19f7b860c3427e
Frank1963-mpoyi/REAL-PYTHON
/WHILE LOOP/whileloop_course.py
2,036
4.25
4
''' Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop''' ''' In programming, there are two types of iteration, indefinite and definite: With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in advance. Rather, the designated block is executed repeatedly as long as some condition is met. With definite iteration, the number of times the designated block will be executed is specified explicitly at the time the loop starts. while <expr>: <statement(s)> <statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an if statement. ''' a = 0# initialise while a <= 5: # to check Boolean condition if its True it will execute the body # then when a variale will do addition it will be 0+1=1 go again to check the condition like new value # of a = 1 and 1<=5 True it print and add again 1+1=2 2<=5, 2+1= 3 , 3<=5, until 6<=5 no the condition become false # and the loop terminate print(a)# you can print the a value for each iteration # print("Frank") or you can print Frank the number of the iterations a = a + 1# increment to make the initialize condition become false in order to get out of the loop #Note : Note that the controlling expression of the while loop is tested first, # before anything else happens. If it’s false to start with, the loop body will never # be executed at all: family = ['mpoyi', 'mitongu', 'kamuanya', 'sharon', 'ndaya', 'mbuyi', 'tshibuyi'] while family:#When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty print(family.pop(-1)) # for every iteration it will remove the last element in the list until the list is finish #Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.
true
cf38d3bf5f83a42c436e46a934f2557763ab0ff4
utkarsht724/Pythonprograms
/Replacestring.py
387
4.65625
5
#program to replace USERNAME with any name in a string import re str= print("Hello USERNAME How are you?") name=input("Enter the name you want to replace with USERNAME :") #taking input name from the user str ="Hello USERNAME How are you?" regex =re.compile("USERNAME") str = regex.sub(name,str) #replace Username with input name by using regular expression print(str)
true
f81f22047a6538e19c1ef847ef365609646ed2df
utkarsht724/Pythonprograms
/Harmonicno.py
296
4.46875
4
#program to display nth harmonic value def Harmonic(Nth): harmonic_no=1.00 for number in range (2,Nth+1): #iterate Nth+1 times from 2 harmonic_no += 1/number print(harmonic_no) #driver_code Nth=int(input("enter the Nth term")) #to take Nth term from the user print(Harmonic(Nth))
true
5b74b55cbc8f0145d125993fc7ac34702d8954f7
rawatrs/rawatrs.github.io
/python/prob1.py
819
4.15625
4
sum = 0 for i in range(1,1000): if (i % 15 == 0): sum += i elif (i % 3 == 0): sum += i elif (i % 5 == 0): sum += i print "Sum of all multiples of 3 or 5 below 1000 = {0}".format(sum) ''' **** Consider using xrange rather than range: range vs xrange The range function creates a list containing numbers defined by the input. The xrange function creates a number generator. You will often see that xrange is used much more frequently than range. This is for one reason only - resource usage. The range function generates a list of numbers all at once, where as xrange generates them as needed. This means that less memory is used, and should the for loop exit early, there's no need to waste time creating the unused numbers. This effect is tiny in smaller lists, but increases rapidly in larger lists. '''
true
6936a4fbce24ffa6be02883497224eb0fc6ad7e5
nirmalshajup/Star
/Star.py
518
4.5625
5
# draw color filled star in turtle import turtle # creating turtle pen t = turtle.Turtle() # taking input for the side of the star s = int(input("Enter the length of the side of the star: ")) # taking the input for the color col = input("Enter the color name or hex value of color(# RRGGBB): ") # set the fillcolor t.fillcolor(col) # start the filling color t.begin_fill() # drawing the star of side s for _ in range(5): t.forward(s) t.right(144) # ending the filling of color t.end_fill()
true
cd03b7b76bfb8c217c0a82b3d48321f8326cc017
jnassula/calculator
/calculator.py
1,555
4.3125
4
def welcome(): print('Welcome to Python Calculator') def calculate(): operation = input(''' Please type in the math operation you would like to complete: + for addition - for substraction * for multiplication / for division ** for power % for modulo ''') number_1 = int(input("Enter your first number: ")) number_2 = int(input("Enter your second number: ")) #Addition if operation == '+': print(f'{number_1} + {number_2} = ') print(number_1 + number_2) #Subtraction elif operation == '-': print(f'{number_1} - {number_2} = ') print(number_1 - number_2) #Multiplication elif operation == '*': print(f'{number_1} * {number_2} = ') print(number_1 * number_2) #Division elif operation == '/': print(f'{number_1} / {number_2} = ') print(number_1 / number_2) #Power elif operation == '**': print(f'{number_1} ** {number_2} = ') print(number_1 ** number_2) #Modulo elif operation == '%': print(f'{number_1 % number_2} = ') print(number_1 % number_2) else: print('You have not typed a valid operator, please run the program again.') again() def again(): calc_again = input(''' Do you want to calculate again? Please type Y for YES or N for NO.''') if calc_again.upper() == 'Y': calculate() elif calc_again.upper() == 'N': print('See you later.') else: again() welcome() calculate()
true
6741dfd84673f751765d5b93a377a462b82da315
BatuhanAktan/SchoolWork
/CS121/Assignment 4/sort_sim.py
2,852
4.21875
4
''' Demonstration of time complexities using sorting algorithms. Author: Dr. Burton Ma Edited by: Batuhan Aktan Student Number: 20229360 Date: April 2021 ''' import random import time import a4 def time_to_sort(sorter, t): ''' Returns the times needed to sort lists of sizes sz = [1024, 2048, 4096, 8192] The function sorts the slice t[0:sz] using the sorting function specified by the caller and records the time required in seconds. Because a slice is sorted instead of the list t, the list t is not modified by this function. The list t should have at least 8192 elements. The times are returned in a list of length 4 where the times in seconds are formatted strings having 4 digits after the decimal point making it easier to print the returned lists. Parameters ---------- sorter : function A sorting function from the module a4. t : list of comparable type A list of elements to slice and sort. Returns ------- list of str The times to sort lists of lengths 1024, 2048, 4096, and 8192. Raises ------ ValueError If len(t) is less than 8192. ''' if len(t) < 8192: raise ValueError('not enough elements in t') times = [] for sz in [1024, 2048, 4096, 8192]: # slice t u = t[0:sz] # record the time needed to sort tic = time.perf_counter() sorter(u) toc = time.perf_counter() times.append(f'{toc - tic:0.4f}') return times list8192 = list(range(8192)) def sim_sorted(): print(time_to_sort(a4.selection_sort, list8192), "Selection Sort") print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1") print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2") print(time_to_sort(a4.merge_sort, list8192), "Merge Sort") def sim_partial(): a4.partial_shuffle(list8192) print(time_to_sort(a4.selection_sort, list8192), "Selection Sort") print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1") print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2") print(time_to_sort(a4.merge_sort, list8192), "Merge Sort") def sim_reverse(): list8192.reverse() print(time_to_sort(a4.selection_sort, list8192), "Selection Sort") print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1") print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2") print(time_to_sort(a4.merge_sort, list8192), "Merge Sort") def sim_shuffled(): random.shuffle(list8192) print(time_to_sort(a4.selection_sort, list8192), "Selection Sort") print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1") print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2") print(time_to_sort(a4.merge_sort, list8192), "Merge Sort") sim_shuffled() sim_reverse() sim_partial() sim_sorted()
true
a38ccc08bc8734389f11b1a6a9ac15eca5b7d53a
sammhit/Learning-Coding
/HackerRankSolutions/quickSortPartion.py
521
4.1875
4
#!/bin/python3 import sys #https://www.hackerrank.com/challenges/quicksort1/problem def quickSort(arr): pivot = arr[0] left = [] right = [] for i in arr: if i>pivot: right.append(i) if i<pivot: left.append(i) left.append(pivot) return left+right # Complete this function if __name__ == "__main__": n = int(input().strip()) arr = list(map(int, input().strip().split(' '))) result = quickSort(arr) print (" ".join(map(str, result)))
true
78a204b4a7ddcc8d39cab0d2c92430d292ad204a
bswood9321/PHYS-3210
/Week 03/Exercise_06_Q4_BSW.py
1,653
4.34375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 7 19:50:39 2019 @author: Brandon """ import numpy as np import numpy.random as rand import matplotlib.pyplot as plt def walk(N): rand.seed() x = [0.0] y = [0.0] for n in range(N): x.append(x[-1] + (rand.random() - 0.5)*2.0) y.append(y[-1] + (rand.random() - 0.5)*2.0) return np.array(x), np.array(y) M, N = 0, 1000 #Setting variables for later Distance = list() #Creating an empty list to hold the distances we will record Walker = list() #Creating an empty list of the number of steps each walker takes while(M<=99): walker1=walk(N) #Our walkers Distance.append(np.sqrt((walker1[0][-1]**2)+(walker1[1][-1]**2))) #Appending the Distance list with the distances of each walker Walker.append(N) # Appending the Walker list with the number of steps the walker has taken M = M+1 #Increasing our M value to progress the while loop N = N+45 #Increasing our N value to change our walker's number of steps plt.plot(Walker, Distance, 'r+') plt.xlabel("Number of steps") plt.ylabel("Distance from the origin") plt.show() # By looking at the plot we receive, we can fairly well determine that the distance # from the origin is fairly random, and does not necessarily increase, decrease, or # stagnate as the N value of the walker changes.This is exactly as I imagined would happen. # there is no reason why the distance should stay around any particular number. In fact, # I believe if we plotted the average dsitance for several iterations of this code, we would find # a similar plot of seemingly random values.
true
70fe8fdf2f0d12b61f21f5d9bd825d2f0a0ec93f
LiuJLin/learn_python_basic
/ex32.py
639
4.53125
5
the_count = [1, 2, 3, 4, 5] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #this first kind of for-loop goes through a list for number in the_count: print("This is count %d"% number) #also we can go through mixed lists too #notice we have use %r since we don't know what's in it for i in change: print("I got %r"% i) #we can also build lists, first start with an empty one elements = [] #the use the range function to do 0 to 5 counts for i in range(0, 6): print("Adding %d to the list."% i) #append is a function that lists Understanding elements.append(i) for i in elements: print("Elements was: %d"% i)
true
8b8945a9936304593b65b5648bcb882365ba5ad3
Phongkaka/python
/TrinhTienPhong_92580_CH05/Exercise/page_145_exercise_06.py
469
4.1875
4
""" Author: Trịnh Tiến Phong Date: 31/10/2021 Program: page_145_exercise_06.py Problem: 6. Write a loop that replaces each number in a list named data with its absolute value * * * * * ============================================================================================= * * * * * Solution: Display result: [21, 12, 20, 5, 26, 11] """ data = [21, -12, 20, 0, -5, 26, -11] for item in range(0, len(data)): data[item] = abs(data[item]) print(data)
true
fc399182e128c75611add67a65ddfe18d180dc55
gamershen/everything
/hangman.py
1,151
4.25
4
import random with open(r'C:\Users\User\Desktop\תכנות\python\wordlist.txt', 'r') as wordfile: wordlist = [line[:-1] for line in wordfile] # creates a list of all the words in the file word = random.choice(wordlist) # choose random word from the list letterlist = [letter for letter in word] # the word converted into a list of letters secretlist = ['_' for letter in word] # the secret word as ( _ _ _ ) print('start playing\n') print(' '.join(secretlist) + '\n') def start_playing(): guess = input('guess a letter: ') while len(guess) > 1 or (not (guess >= 'a' and guess <= 'z')) and (not (guess >= 'A' and guess <= 'Z')): guess = input('that aint a letter,guess a letter: ') # char validation [secretlist.pop(i) and secretlist.insert(i, char) for i, char in enumerate(word) if guess == char] # if guess is correct show the letter print('\n' + ' '.join(secretlist)) for i in range(15): start_playing() print('tries left: ' + str(14 - i)) if letterlist == secretlist: print('you won!') break if not letterlist == secretlist: print(f'you lost! the word was: {word}')
true
e0d6812a81d0a65fb8998b63ac1af09247fc803e
Nihilnia/June1-June9
/thirdHour.py
1,283
4.21875
4
""" 7- Functions """ def sayHello(): print("Hello") def sayHi(name = "Nihil"): print("Hi", name) sayHello() sayHi() def primeQ(number): if number == 0 or number == 1: print(number, "is not a Primer number.") else: divs = 0 for f in range(2, number): if number % f == 0: divs += 1 if divs == 0: print(number, "is a Primer number.") else: print(number, "is not a Primer number.") primeQ(13) # return() Expression def hitMe(): firstNumber = int(input("Give me a number: ")) secondNumber = int(input("Give me the second number: ")) return firstNumber + secondNumber print("Result:", hitMe()) # Flexible parameters - we know it. """ 8- Lambda Expressions """ #Short way to create a function def Nihil1(): print("Gimme tha Power") Nihil2 = lambda: print("Gimme tha Power x2") Nihil1() Nihil2() #Another Example divideNumbers = lambda a, b: float(a/b) #If we won't write anything, it means return print(divideNumbers(12, 2)) #Last Example """ Finding are of circle (A = pi * r**2) """ findCircle = lambda r: 3.14 * (r ** 2) print(findCircle(r = 2.5))
true
af4c141fc364f89f4d1ad14541b368c164f40b81
stephenfreund/PLDI-2021-Mini-Conf
/scripts/json_to_csv.py
1,116
4.15625
4
# Python program to convert # JSON file to CSV import argparse import csv import json def parse_arguments(): parser = argparse.ArgumentParser(description="MiniConf Portal Command Line") parser.add_argument("input", default="data.json", help="paper file") parser.add_argument("out", default="data.csv", help="embeddings file to shrink") return parser.parse_args() if __name__ == "__main__": args = parse_arguments() # Opening JSON file and loading the data # into the variable data with open(args.input) as json_file: data = json.load(json_file) # now we will open a file for writing data_file = open(args.out, "w") # create the csv writer object csv_writer = csv.writer(data_file) # Counter variable used for writing # headers to the CSV file count = 0 for emp in data: if count == 0: # Writing headers of CSV file header = emp.keys() csv_writer.writerow(header) count += 1 # Writing data of CSV file csv_writer.writerow(emp.values()) data_file.close()
true
c64c542b57107c06de2ce0751075a81fcb195b61
DmitriiIlin/Merge_Sort
/Merge_Sort.py
1,028
4.25
4
def Merge (left,right,merged): #Ф-ция объединения и сравнения элементов массивов left_cursor,right_cursor=0,0 while left_cursor<len(left) and right_cursor<len(right): if left[left_cursor]<=right[right_cursor]: merged[left_cursor+right_cursor]=left[left_cursor] left_cursor+=1 else: merged[left_cursor+right_cursor]=right[right_cursor] right_cursor+=1 for left_cursor in range(left_cursor,len(left)): merged[left_cursor+right_cursor]=left[left_cursor] for right_cursor in range(right_cursor,len(right)): merged[left_cursor+right_cursor]=right[right_cursor] return merged def MergeSort(array): #Основная рекурсивная функция if len(array)<=1: return array mid=len(array)//2 left,right=MergeSort(array[:mid]),MergeSort(array[mid:]) return Merge(left,right,array.copy()) """ a=[2,45,1,4,66,34] print(MergeSort(a)) print(a) """
true
1605bc14384fc7d8f74a0af5f3eb1b03f23b1cd5
Oussema3/Python-Programming
/encryp1.py
343
4.28125
4
line=input("enter the string to be encrypted : ") num=int(input("how many letters you want to shift : ")) while num > 26: num = num -26 empty="" for char in line: if char.isalpha() is True: empty=chr(ord(char)+num) print(empty, end = "") else: empty=char print(empty,end="")
true
162acf35104d849e124d88a07e13fbdbc58e261b
stevewyl/chunk_segmentor
/chunk_segmentor/trie.py
2,508
4.15625
4
"""Trie树结构""" class TrieNode(object): def __init__(self): """ Initialize your data structure here. """ self.data = {} self.is_word = False class Trie(object): def __init__(self): self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for letter in word: child = node.data.get(letter) if not child: node.data[letter] = TrieNode() node = node.data[letter] node.is_word = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for letter in word: node = node.data.get(letter) if not node: return False return node.is_word # 判断单词是否是完整的存在在trie树中 def starts_with(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.root for letter in prefix: node = node.data.get(letter) if not node: return False return True def get_start(self, prefix): """ Returns words started with prefix :param prefix: :return: words (list) """ def _get_key(pre, pre_node): words_list = [] if pre_node.is_word: words_list.append(pre) for x in pre_node.data.keys(): words_list.extend(_get_key(pre + str(x), pre_node.data.get(x))) return words_list words = [] if not self.starts_with(prefix): return words if self.search(prefix): words.append(prefix) return words node = self.root for letter in prefix: node = node.data.get(letter) return _get_key(prefix, node) if __name__ == '__main__': tree = Trie() tree.insert('深度学习') tree.insert('深度神经网络') tree.insert('深度网络') tree.insert('机器学习') tree.insert('机器学习模型') print(tree.search('深度学习')) print(tree.search('机器学习模型')) print(tree.get_start('深度')) print(tree.get_start('深度网'))
true
eb1ba8ee65ab19dad296f9793e0a0f6ba6230100
LeilaBagaco/DataCamp_Courses
/Supervised Machine Learning with scikit-learn/Chapter_1/1-k-nearest-neighbors-fit.py
2,163
4.28125
4
# ********** k-Nearest Neighbors: Fit ********** # Having explored the Congressional voting records dataset, it is time now to build your first classifier. # In this exercise, you will fit a k-Nearest Neighbors classifier to the voting dataset, which has once again been pre-loaded for you into a DataFrame df. # In the video, Hugo discussed the importance of ensuring your data adheres to the format required by the scikit-learn API. # The features need to be in an array where each column is a feature and each row a different observation or data point - in this case, a Congressman's voting record. # The target needs to be a single column with the same number of observations as the feature data. We have done this for you in this exercise. # Notice we named the feature array X and response variable y: This is in accordance with the common scikit-learn practice. # Your job is to create an instance of a k-NN classifier with 6 neighbors (by specifying the n_neighbors parameter) and then fit it to the data. # The data has been pre-loaded into a DataFrame called df. # ********** Exercise Instructions ********** # 1 - Import KNeighborsClassifier from sklearn.neighbors. # 2 - Create arrays X and y for the features and the target variable. Here this has been done for you. # Note the use of .drop() to drop the target variable 'party' from the feature array X as well as the use of the .values attribute to ensure X and y are NumPy arrays. # Without using .values, X and y are a DataFrame and Series respectively; the scikit-learn API will accept them in this form also as long as they are of the right shape. # 3 - Instantiate a KNeighborsClassifier called knn with 6 neighbors by specifying the n_neighbors parameter. # ********** Script ********** # Import KNeighborsClassifier from sklearn.neighbors from sklearn.neighbors import KNeighborsClassifier # Create arrays for the features and the response variable y = df['party'].values X = df.drop('party', axis=1).values # Create a k-NN classifier with 6 neighbors knn = KNeighborsClassifier(n_neighbors=6) # Fit the classifier to the data knn.fit(X, y)
true
39d5510129b23fc19a86740a018f61f19638570c
duchamvi/lfsrPredictor
/utils.py
599
4.28125
4
def bitToInt(bits): """Converts a list of bits into an integer""" n = 0 for i in range (len(bits)): n+= bits[i]*(2**i) return n def intToBits(n, length): """Converts an integer into a list of bits""" bits = [] for i in range(length): bits.append(n%2) n = n//2 return bits def stringToInt(str_input): """Checks that the input string is an integer then converts it""" try: int_input = int(str_input) except: print("That's not a valid input, please enter an integer next time") exit(0) return int_input
true
8e0148c31c798685c627b54d2d3fe90df4553443
Lukasz-MI/Knowledge
/Basics/01 Data types/06 type - tuple.py
907
4.28125
4
data = tuple(("engine", "breaks", "clutch", "radiator" )) print (data) # data [1] = "steering wheel" # cannot be executed as tuple does not support item assignment story = ("a man in love", "truth revealed", "choice") scene = ("new apartment", "medium-sized city", "autumn") book = story + scene + ("length",) # Tuple combined print (book) print(len(book)) print(type(book)) # <class 'tuple'> emptyTuple = () print(emptyTuple) print(type(emptyTuple)) # <class 'tuple'> print (book [-1]) print (book [len(book) -1]) print (book [3:]) print(book[::2]) cars = (("KIA", "Hyundai", "Mazda") , ("bmw", "mercedes", "Audi")) print(cars) print(cars[0][0]) # first tuple, first value - KIA if "Mazda" in cars[0]: print ("Yupi!") # del cars [0] - single element deletion not allowed del cars # print(cars) - whole tuple deleted - NameError: name 'cars' is not defined tuplex3 = book * 3 print(tuplex3)
true
164fcb27549ae14c058c7eaf3b6c47b58d198e6d
Dan-krm/interesting-problems
/gamblersRuin.py
2,478
4.34375
4
# The Gambler's Ruin # A gambler, starting with a given stake (some amount of money), and a goal # (a greater amount of money), repeatedly bets on a game that has a win probability # The game pays 1 unit for a win, and costs 1 unit for a loss. # The gambler will either reach the goal, or run out of money. # What is the probability that the gambler will reach the goal? # How many bets does it take, on average, to reach the goal or fall to ruin? import random as random import time as time stake = 10 # Starting quantity of currency units goal = 100 # Goal to reach in currency units n_trials = 10000 # Number of trials to run win_prob = 0.5 # Probability of winning an individual game def gamble(cash, target_goal, win_probability): """ A single trial of a gambler playing games until they reach their goal or run out of money. cash: the gambler's initial amount of currency units goal: the number of currency units to reach to be considered a win win_prob: the likelihood of winning a single game return: a tuple (outcome, bets): - outcome: the outcome of the trial (1 for success, 0 for failure) - bets: number of bets placed """ # play games until the goal is reached or no more currency units remain bets = 0 # number of bets placed while 0 < cash < target_goal: bets += 1 if random.random() < win_probability: cash += 1 else: cash -= 1 # return tuple of trial outcome, number of bets placed if cash == target_goal: return 1, bets else: return 0, bets def display_gamble(): print("\nQuestion 2: Gamblers Ruin\n") # run a number of trials while tracking trial wins & bet counts bets = 0 # total bets made across all games from all trials wins = 0 # total trials won start = time.time() # time when we started the simulation for t in range(n_trials): w, b = gamble(stake, goal, win_prob) wins += w bets += b end = time.time() # time when we stopped the simulation duration = end - start # display statistics of the trials print('Stake:', stake) print('Goal:', goal) print(str(100 * wins / n_trials) + '% were wins') print('Average number of bets made:', str(bets / n_trials)) print('Number of trials:', n_trials) print('The simulation took:', duration, 'seconds (about', n_trials/duration, 'trials per second)')
true
2e2821bc842d2b6c16a6e9a5f5252b64c4f2d097
ngenter/lnorth
/guessreverse.py
631
4.125
4
# Nate Genter # 1-9-16 # Guess my number reversed # In this program the computer will try and guess your number import random print("\nWelcome to Liberty North.") print("Lets play a game.") print("\nPlease select a number, from 1-100 and I will guess it.") number = int(input("Please enter your number: ")) if number <= 0 or number >= 101: print("That is not a valid number.") tries = 1 guess = () while number != guess: tries == 1 guess = random.randint(1,100) print(guess) if guess != number: tries += 1 print("\nIt took me", tries, "tries.") input("\nPress the enter key to exit.")
true
fe297a22342a92f9b3617b827367e60cb7b68f20
jpallavi23/Smart-Interviews
/03_Code_Forces/08_cAPS lOCK.py
1,119
4.125
4
''' wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: either it only contains uppercase letters; or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged. Input The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive. Output Print the result of the given word's processing. Examples Input cAPS Output Caps Input Lock Output Lock ''' word = input() if word[1:].upper() == word[1:]: word = word.swapcase() print(word)
true
4344f818cad8fd3759bab9e914dafb31171782f8
jpallavi23/Smart-Interviews
/06_SI_Basic-Hackerrank/40_Hollow rectangle pattern.py
628
4.21875
4
''' Print hollow rectangle pattern using '*'. See example for more details. Input Format Input contains two integers W and L. W - width of the rectangle, L - length of the rectangle. Constraints 2 <= W <= 50 2 <= L <= 50 Output Format For the given integers W and L, print the hollow rectangle pattern. Sample Input 0 5 4 Sample Output 0 ***** * * * * ***** ''' cols, rows = map(int, input().split()) for itr in range(1, rows+1): for ctr in range(1, cols+1): if itr == 1 or itr == rows or ctr == 1 or ctr == cols: print("*", end="") else: print(" ", end="") print("\r")
true
5510d31f40b640c9a702d7580d1d434715469ba9
smzapp/pyexers
/01-hello.py
882
4.46875
4
one = 1 two = 2 three = one + two # print(three) # print(type(three)) # comp = 3.43j # print(type(comp)) #Complex mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo'] B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3. print(mylist[1]) # This will return the value at index 1, which is 'Grasshopper' print(mylist[0:1]) # This will return the first 3 elements in the list. print(mylist[1:]) # is equivalent to "1 to end" print(len(mylist)) # Example: # [1:5] is equivalent to "from 1 to 5" (5 not included) # [1:] is equivalent to "1 to end" # [len(a):] is equivalent to "from length of a to end" #--------- tups = ('TupName', 'TupsAddress', 'TupsContact') #@TUPLE listo = ['ListName', 'Address', 'Contact'] print(type(tups)) print(type(listo)) print(tups[0], tups[2] ) #tups[3] is out of range print(listo[0]) #---------
true
5da5f3b2063362046288b6370ff541a13552f9c8
adamyajain/PRO-C97
/countingWords.py
279
4.28125
4
introString = input("Enter String") charCount = 0 wordCount = 1 for i in introString: charCount = charCount+1 if(i==' '): wordCount = wordCount+1 print("Number Of Words in a String: ") print(wordCount) print("Number Of Characters in a String: ") print(charCount)
true
80240cb2d0d6c060e516fd44946fd7c57f1a3b06
hungnv132/algorithm
/recursion/draw_english_ruler.py
1,689
4.5
4
""" + Describe: - Place a tick with a numeric label - The length of the tick designating a whole inch as th 'major tick length' - Between the marks of whole inches, the ruler contains a series of 'minor sticks', placed at intervals of 1/2 inch, 1/4 inch, and so on - As the size of the interval decrease by half, the tick length decreases by one + Base cases(recursion): tick_length = 0 + Input: inch, major tick length + Output: --- 0 - -- - --- 1 - -- - --- 2 + Ideas: - method draw_tick(...) is only responsible for printing the line of ticks (eg: ---, -, ---, --) - method interver_v (...) : recursion of draw_tick(...) mehtod until tick_length = 0 - draw_english_ruler(...) is main method - for loop: for displaying 'inch' + References: Data structures and Algorithms in Python by Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael """ def draw_tick(length , tick_label=''): line = '-'*int(length) if tick_label: line += ' ' + tick_label print(line) # interval_version 1 def interval_v1(tick_length): if tick_length > 1: interval_v1(tick_length - 1) draw_tick(tick_length) if tick_length > 1: interval_v1(tick_length - 1) # interval_version 2 def interval_v2(tick_length): if tick_length > 0: interval_v2(tick_length - 1) draw_tick(tick_length) interval_v2(tick_length - 1) def draw_english_ruler(inch, major_tick_length): draw_tick(major_tick_length, '0') for i in range(1,inch): interval_v2(major_tick_length - 1) draw_tick(major_tick_length, str(i)) if __name__ == '__main__': draw_english_ruler(4, 5)
true
7240fb816fb1beba9bf76eaf89579a7d87d46d67
hungnv132/algorithm
/books/python_cookbook_3rd/ch01_data_structures_and_algorithms/07_most_frequently_occurring_items.py
1,516
4.28125
4
from collections import Counter def most_frequently_occurring_items(): """ - Problem: You have a sequence of items and you'd like determine the most frequently occurring items in the sequence. - Solution: Use the collections.Counter """ words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] word_counts = Counter(words) print(word_counts) # Counter({'eyes': 8, 'the': 5, 'look': 4, 'my': 3, 'into': 3, 'around': 2, # "don't": 1, 'not': 1, "you're": 1, 'under': 1}) top_three = word_counts.most_common(3) print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)] print(word_counts['look']) # 4 print(word_counts['the']) # 5 print(word_counts['into']) # 3 print(word_counts['eyes']) # 8 # if you want to increment the count manually, simply use addition morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes'] for word in morewords: word_counts[word] += 1 print(word_counts['eyes']) # 9 # or use update() method word_counts.update(morewords) print(word_counts['eyes']) # 10 a = Counter(words) b = Counter(morewords) # Combine counts c = a + b # Subtract counts d = a - b if __name__ == '__main__': most_frequently_occurring_items()
true
d5004f19368c1db3f570771b70d9bd82f94f1a3b
hungnv132/algorithm
/design_patterns/decorator.py
1,029
4.3125
4
def decorator(func): def inner(n): return func(n) + 1 return inner def first(n): return n + 1 first = decorator(first) @decorator def second(n): return n + 1 print(first(1)) # print 3 print(second(1)) # print 3 # =============================================== def wrap_with_prints(func): # This will only happen when a function decorated # with @wrap_with_prints is defined print('wrap_with_prints runs only once') def wrapped(): # This will happen each time just before # the decorated function is called print('About to run: %s' % func.__name__) # Here is where the wrapper calls the decorated function func() # This will happen each time just after # the decorated function is called print('Done running: %s' % func.__name__) return wrapped @wrap_with_prints def func_to_decorate(): print('Running the function that was decorated.') func_to_decorate() print("================") func_to_decorate()
true
10bdaba3ac48babdc769cb838e1f7f4cdef66ae9
nikitaagarwala16/-100DaysofCodingInPython
/MonotonicArray.py
705
4.34375
4
''' Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic. An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non -decreasing. ''' def monoArray(array): arraylen=len(array) increasing=True decreasing=True for i in range(arraylen-1): if(array[i+1]>array[i]): decreasing=False if(array[i+1]<array[i]): increasing=False if not increasing and not decreasing: return False return increasing or decreasing if __name__ == "__main__": array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001] print(monoArray(array))
true
433ad06ffcf65021a07f380078ddf7be5a14bc0d
senorpatricio/python-exercizes
/warmup4-15.py
1,020
4.46875
4
""" Creating two classes, an employee and a job, where the employee class has-a job class. When printing an instance of the employee object the output should look something like this: My name is Morgan Williams, I am 24 years old and I am a Software Developer. """ class Job(object): def __init__(self, title, salary): self.title = title self.salary = salary class Employee(object): def __init__(self, name, age, job_title, job_salary): self.name = name self.age = age self.job = Job(job_title, job_salary) def __str__(self): return "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \ % (self.name, self.age, self.job.title, self.job.salary) # def speak(self): # print "Hi my name is %s, I am %s Years old and I am a %s, making $%i per year." \ # % (self.name, self.age, self.job.title, self.job.salary) morgan = Employee("Morgan Williams", 24, "Software Developer", 60000) print morgan # morgan.speak()
true
41fdc8a89fb3e7ecdcfaec78e5c668fc0e6e4e80
JoshuaShin/A01056181_1510_assignments
/A1/random_game.py
2,173
4.28125
4
""" random_game.py. Play a game of rock paper scissors with the computer. """ # Joshua Shin # A01056181 # Jan 25 2019 import doctest import random def computer_choice_translator(choice_computer): """ Translate computer choice (int between 0 - 2 inclusive) to "rock", "paper", or "scissors". PARAM choice_computer int between 0 - 2 PRE-CONDITION choice_computer must be int between 0 - 2 POST-CONDITION translate computer choice to "rock", "paper", or "scissors" RETURN return computer choice in "rock", "paper", or "scissors" >>> computer_choice_translator(0) 'rock' >>> computer_choice_translator(1) 'paper' >>> computer_choice_translator(2) 'scissors' """ if choice_computer == 0: return "rock" elif choice_computer == 1: return "paper" else: # choice_computer == 2 return "scissors" def rock_paper_scissors(): """ Play a game of rock paper scissors with the computer. """ choice_computer = computer_choice_translator(random.randint(0, 2)) choice_player = input("Ready? Rock, paper, scissors!: ").strip().lower() if not(choice_player == "rock" or choice_player == "paper" or choice_player == "scissors"): print("Dont you know how to play rock paper scissors, ya loser!") rock_paper_scissors() return print("Computer played:", choice_computer) print("You played:", choice_player) if choice_player == choice_computer: print("TIED") elif choice_player == "rock": if choice_computer == "paper": print("YOU LOSE") elif choice_computer == "scissors": print("YOU WIN") elif choice_player == "paper": if choice_computer == "scissors": print("YOU LOSE") elif choice_computer == "rock": print("YOU WIN") elif choice_player == "scissors": if choice_computer == "rock": print("YOU LOSE") elif choice_computer == "paper": print("YOU WIN") def main(): """ Drive the program. """ doctest.testmod() rock_paper_scissors() if __name__ == "__main__": main()
true
0ca8c1dc04f5e98a3d08b588e2a4c5903e7f61da
amit-kr-debug/CP
/Geeks for geeks/Heap/Sorting Elements of an Array by Frequency.py
2,697
4.125
4
""" Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. Output: For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be seperated by space. Constraints: 1 ≤ T ≤ 70 30 ≤ N ≤ 130 1 ≤ Ai ≤ 60 Example: Input: 2 5 5 5 4 6 4 5 9 9 9 2 5 Output: 4 4 5 5 6 9 9 9 2 5 Explanation: Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6. The output is 4 4 5 5 6. Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 9 9 9 comes first. Now both 2 and 5 have same frequency. So we print smaller element first. The output is 9 9 9 2 5 """ """ tCases = int(input()) for _ in range(tCases): n = int(input()) arr = list(map(int, input().split())) freq = {} for i in arr: if i in freq: freq[i] += 1 else: freq[i] = 1 nDict = {} for key, val in sorted(freq.items(), key = lambda kv:(kv[1], kv[0]), reverse=True): # print(key, val) if val not in nDict: nDict.update({val: [key]}) else: nDict[val].append(key) for key, val in nDict.items(): val.sort() for i in val: for j in range(key): print(i, end=" ") print() """ # solution without heap in O(n*logn), first find freq of each element and make a new dict with value as key # and values of that dict will be arr with that freq then sort each value and print it. tCases = int(input()) for _ in range(tCases): n = int(input()) arr = list(map(int, input().split())) freq = {} for i in arr: if i in freq: freq[i] += 1 else: freq[i] = 1 nDict = {} for key, val in freq.items(): if val not in nDict: nDict.update({val: [key]}) else: nDict[val].append(key) for key, val in sorted(nDict.items(), key=lambda kv: (kv[0], kv[1]), reverse=True): val.sort() for i in val: for j in range(key): print(i, end=" ") print()
true
e2fb43f0392cd69430a3604c6ddcf3b06425b671
amit-kr-debug/CP
/Geeks for geeks/array/sorting 0 1 2.py
1,329
4.1875
4
""" Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. Example 1: Input: N = 5 arr[]= {0 2 1 2 0} Output: 0 0 1 2 2 Explanation: 0s 1s and 2s are segregated into ascending order. Example 2: Input: N = 3 arr[] = {0 1 0} Output: 0 0 1 Explanation: 0s 1s and 2s are segregated into ascending order. Your Task: You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 10^6 0 <= A[i] <= 2 """ # User function Template for python3 class Solution: def sort012(self,arr,n): # code here d = {0: 0,1: 0,2: 0} index = 0 for i in range(n): d[arr[i]] += 1 for key,val in d.items(): for i in range(val): arr[index] = key index += 1 # { # Driver Code Starts # Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) arr = [int(x) for x in input().strip().split()] ob = Solution() ob.sort012(arr,n) for i in arr: print(i,end = ' ') print() # } Driver Code Ends
true
6069283e9388e6d1704f649d14b84e4a288f8d86
amit-kr-debug/CP
/Cryptography and network security/lab - 2/Vigenere Cipher encrypt.py
669
4.21875
4
def encrypt(plain_text, key): cipher_text = "" # Encrypting plain text for i in range(len(plain_text)): cipher_text += chr(((ord(plain_text[i]) + ord(key[i]) - 130) % 26) + 65) return cipher_text if __name__ == "__main__": # Taking key as input key = input("Enter the key:") # Taking plain text as input plain_text = input("Enter the plain text:") count = 0 key_updated = "" # Updating Key for _ in plain_text: if count == len(key): count = 0 key_updated += key[count] count += 1 print("Cipher text:",end = "") print(encrypt(plain_text.upper(),key_updated.upper()))
true
4602c2628ae813e68f997f36b18d270316e42a43
amit-kr-debug/CP
/hackerrank/Merge the Tools!.py
1,835
4.25
4
""" https://www.hackerrank.com/challenges/merge-the-tools/problem Consider the following: A string, , of length where . An integer, , where is a factor of . We can split into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string such that: The characters in are a subsequence of the characters in . Any repeat occurrence of a character is removed from the string such that each character in occurs exactly once. In other words, if the character at some index in occurs at a previous index in , then do not include the character in string . Given and , print lines where each line denotes string . Input Format The first line contains a single string denoting . The second line contains an integer, , denoting the length of each subsegment. Constraints , where is the length of It is guaranteed that is a multiple of . Output Format Print lines where each line contains string . Sample Input AABCAAADA 3 Sample Output AB CA AD Explanation String is split into equal parts of length . We convert each to by removing any subsequent occurrences non-distinct characters in : We then print each on a new line. """ def merge_the_tools(string, k): import textwrap s=string n=k lis=list(map(str,textwrap.wrap(s,n))) for i in lis: new=list(i[0]) for j in range(1,len(i)): for k in range(len(new)): if new[k] != i[j]: flag = 0 else: flag = 1 break if flag == 0: new.append(i[j]) for i in range(len(new)-1): print(new[i],end="") print(new[len(new)-1]) if __name__ == '__main__': string, k = input(), int(input()) merge_the_tools(string, k)
true
efa3c5294a1274ba4c2133c34b6aaa32fb3ad590
ayatullah-ayat/py4e_assigns_quizzes
/chapter-10_assignment-10.2.py
921
4.125
4
# 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) email_sender_list = list() for line in handle: word_list = line.split() if len(word_list) < 2: continue if not word_list: continue if not line.startswith('From '): continue email_sender_list.append(word_list[5]) item_dict = dict() for item in email_sender_list: item = item.split(':') it = item[0] item_dict[it] = item_dict.get(it, 0) + 1 for key, value in sorted(item_dict.items()): print(key, value)
true
2836445a3619bd8f3a5554d962f079cc0de9cd9a
sooty1/Javascript
/main.py
1,240
4.1875
4
names = ['Jenny', 'Alexus', 'Sam', 'Grace'] dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph'] names_and_dogs_names = zip(names, dogs_names) print(list(names_and_dogs_names)) # class PlayerCharacter: # #class object attribute not dynamic # membership = True # def __init__(self, name="anonymous", age=0): # if (age > 18): # self.name = name # self.age = age # def run(self): # print('run') # def shout(self): # print(f'my name is {self.name}') # player1 = PlayerCharacter('Tom', 10) # player2 = PlayerCharacter() # player2.attack = 50 # print(player1.shout()) # print(player2.age) #Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age def oldest(*args): return max(args) cat1= Cat("Tom", 3) cat2= Cat('Jerry', 5) cat3= Cat("filbert", 2) def oldest(*args): return max(args)aaaa print(f"The oldest cat is {oldest(cat1.age, cat2.age, cat3.age)} years old.") # 1 Instantiate the Cat object with 3 cats # 2 Create a function that finds the oldest cat # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
true
5b2267600ac663d2493599080b5bf482511015d3
nehaDeshp/Python
/Tests/setImitation.py
623
4.25
4
''' In this exercise, you will create a program that reads words from the user until the user enters a blank line. After the user enters a blank line your program should display each word entered by the user exactly once. The words should be displayed in the same order that they were entered. For example, if the user enters: first second first third second then your program should display: first second third [ use list ] ''' list=[] print("Enter Integers:") while True: num = input("") if(num == " "): break elif(list.__contains__(num)): pass else: list.append(num) print(list)
true
a15d13da749137921a636eb4acf2d56a4681131a
nehaDeshp/Python
/Tests/Assignment1.py
559
4.28125
4
''' Write a program that reads integers from the user and stores them in a list. Your program should continue reading values until the user enters 0. Then it should display all of the values entered by the user (except for the 0) in order from smallest to largest, with one value appearing on each line. Use either the sort method or the sorted function to sort the list ''' list=[] print("Enter Integers:") while True: num = int(input("")) if(num == 0): break else: list.append(num) #sort list.sort() for i in list: print(i)
true
8a61b80b3b96c4559149609d9630323a05f3a134
tanviredu/DATACAMPOOP
/first.py
292
4.34375
4
# Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1,2,3,4,5,6]) # Print out my_avg print(my_avg)
true
caaf2c8cf85b91b74b917523796029eda659131f
samithaj/COPDGene
/utils/compute_missingness.py
976
4.21875
4
def compute_missingness(data): """This function compute the number of missing values for every feature in the given dataset Parameters ---------- data: array, shape(n_instances,n_features) array containing the dataset, which might contain missing values Returns ------- n_missing: list, len(n_features) list containing the number of missing values for every feature """ n_instances,n_features = data.shape n_missing = [0]*n_features for j in range(n_features): for i in range(n_instances): if data[i,j] == '': n_missing[j] += 1 return n_missing def test_compute_missingness(): import numpy as np data = np.empty((4,9),dtype=list) data[0,0] = '' data[0,1] = '' data[1,4] = '' for i in range(6): data[3,i] = '' n_missing = compute_missingness(data) print n_missing if __name__ == "__main__": test_compute_missingness()
true
31116f0e83ba9681303f5540d51b28e8d7d0c1c3
kellyseeme/pythonexample
/220/str.py
228
4.3125
4
#!/usr/bin/env python import string a = raw_input("enter a string:").strip() b = raw_input("enter another string:").strip() a = a.upper() if a.find(b) == -1: print "this is not in the string" else: print "sucecess"
true
d66a2b7006d3bbcede5387ed1a56df930862bccb
kellyseeme/pythonexample
/221/stringsText.py
945
4.21875
4
#!/usr/bin/env python """this is to test the strings and the text %r is used to debugging %s,%d is used to display + is used to contact two strings when used strings,there can used single-quotes,double-quotes if there have a TypeError,there must be some format parameter is not suit """ #this is use %d to set the values x = "there are %d typs of people." % 10 binary = "binary" do_not = "don't" #this is use two variables to strings and use %s y= "those who know %s and those who %s." % (binary,do_not) print x print y #use %r to set x ,%s is the string,and the %r is use the repe() function print "I said: %r." % x #this is use %s to se value y print "I also said:%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" #this is use hilarious to set the string of %r print joke_evaluation % hilarious w = "this is the left side of ..." e = "a string with a right side." #use + to concate the two strings print w + e
true
5a2b8b97398fce8041886ad4920b5f7acd092ef7
kellyseeme/pythonexample
/323/stringL.py
693
4.15625
4
#!/usr/bin/env python #-*coding:utf-8 -*- #this is use the string method to format the strins #1.use the ljust is add more space after the string #2.use the rjust is add more space below the string #3.use the center is add more space below of after the string print "|","kel".ljust(20),"|","kel".rjust(20),"|","kel".center(20),"|" #the string center have more args is the width and the space or other arguments print "|","kel".center(20,"*"),"|" print "|","kel".ljust(20,"*"),"|" print "|","kel".rjust(20,"*"),"|" """ 用来整理字符串的格式,主要使用的方法为ljust,rjust和center,默认情况下使用空格 第二个参数用来表示用什么字符进行填充 """
true
0db7502613ff0c05461e17509d9b8b6abb1be3d2
kellyseeme/pythonexample
/33/using_list.py
1,053
4.34375
4
#!/usr/bin/env python """ this is for test the list function """ #this is define the shoplist of a list shoplist = ["apple","mango","carrot","banana"] #get the shoplist length,using len(shoplist) print "Ihave",len(shoplist),"items to pruchase." #this is iteration of the list,the list is iterable print "These items are:", for item in shoplist: #there have a comma at the end of the line,it's mean is ride of the newline print item, print "\nIalso have to buy rice." #this is append the function,add a shopinglinst a rice,using append #append is the last the argument shoplist.append("rice") print "My shopping list is now",shoplist print "I will sort my list now" #list is a changeable,so this is sort,and the list is changed shoplist.sort() print "Sorted shoping list is ",shoplist print "The first item I will buy is ",shoplist[0] #this is get the list of value,use the index and then get the value olditem = shoplist[0] #this is delete some of the list del shoplist[0] print "I bouthe the",olditem print "My shopping list is now",shoplist
true
a2861764344d6b0302e21b4d670addd638b13e38
CorinaaaC08/lps_compsci
/class_samples/3-2_logicaloperators/college_acceptance.py
271
4.125
4
print('How many miles do you live from Richmond?') miles = int(raw_input()) print('What is your GPA?') GPA = float(raw_input()) if GPA > 3.0 and miles > 30: print('Congrats, welcome to Columbia!') if GPA <= 3.0 or miles <= 30: print('Sorry, good luck at Harvard.')
true
06366e956623f3305dbb737d6f91ddcea542daf4
dataneer/dataquestioprojects
/dqiousbirths.py
2,146
4.125
4
# Guided Project in dataquest.io # Explore U.S. Births # Read in the file and split by line f = open("US_births_1994-2003_CDC_NCHS.csv", "r") read = f.read() split_data = read.split("\n") # Refine reading the file by creating a function instead def read_csv(file_input): file = open(file_input, "r") read = file.read() split_data = read.split("\n") no_header = split_data[1:len(split_data)] final_list = list() for i in no_header: string_fields = i.split(",") int_fields = [] for i in string_fields: int_fields.append(int(i)) final_list.append(int_fields) return final_list cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv") # Create a function that takes a list of lists argument def month_births(input_lst): # Store monthly totals in a dictionary births_per_month = {} for i in input_lst: # Label the columns month = i[1] births = i[4] # Check if item already exists in dictonary list if month in births_per_month: # Add the current number of births to the new integer births_per_month[month] = births_per_month[month] + births # If the item does not exist, create it with integer of births else: births_per_month[month] = births return births_per_month cdc_month_births = month_births(cdc_list) # This function uses day of the week instead of month def dow_births(input_lst): births_per_day = {} for i in input_lst: dow = i[3] births = i[4] if dow in births_per_day: births_per_day[dow] = births_per_day[dow] + births else: births_per_day[dow] = births return births_per_day cdc_day_births = dow_births(cdc_list) # This function is more superior because it is a generalized form def calc_counts(data, column): sums_dict = {} for row in data: col_value = row[column] births = row[4] if col_value in sums_dict: sums_dict[col_value] = sums_dict[col_value] + births else: sums_dict[col_value] = births return sums_dict
true
fb9b299eff93179ac097d797c7e5ce59bc20f63a
yugin96/cpy5python
/practical04/q5_count_letter.py
796
4.1875
4
#name: q5_count_letter.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function count_letter(str, ch) that finds the # number of occurences of a specified leter, ch, in a string, str. #main #function def count_letter(str, ch): #terminating case when string is empty if len(str) == 0: return 0 #add 1 to result if ch is equal to first character of str if str[0] == ch: return 1 + count_letter(str[1:], ch) #add 0 to result if ch is not equal to first character of str if str[0] != ch: return 0 + count_letter(str[1:], ch) #prompt user input of string and character string = str(input('Enter a string: ')) character = str(input('Enter a character: ')) print(count_letter(string, character))
true
599df5c53d26902da3f2f16cb892a0ae6501be78
yugin96/cpy5python
/practical04/q6_sum_digits.py
482
4.28125
4
#name: q6_sum_digits.py #author: YuGin, 5C23 #created: 26/02/13 #modified: 26/02/13 #objective: Write a recursive function sum_digits(n) that computes the sum of # the digits in an integer n. #main #function def sum_digits(n): #terminating case when integer is 0 if len(str(n)) == 0: return 0 else: return int(str(n)[0]) + sum_digits(str(n)[1:]) #prompt user input of integer integer = input('Enter an integer: ') print(sum_digits(integer))
true
fbd7624f47d4e14b47722923fd568c31e082d91d
Monsieurvishal/Peers-learning-python-3
/programs/for loop.py
236
4.59375
5
>>for Loops #The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects. for i in range(5): print("hello!") Output: hello! hello! hello! hello! hello!
true
c56cc5a285093da9ca9cc2265e344bfdbf03f929
Monsieurvishal/Peers-learning-python-3
/programs/for loop_p3.py
282
4.3125
4
>>Write a python script to take input from the user and print till that number. #Ex: if input is 10 print from 1 till 10. n=int(input("enter the number:")) i=0 for i in range(n): print(i) i=i+1 print("finished") #output: enter the number: 0 1 2 3 4 5 6 7 8 9 finished
true
24b146a3e423fd413124b988150d4e1ee01b4204
dell-ai-engineering/BigDL4CDSW
/1_sparkbasics/1_rdd.py
1,467
4.25
4
# In this tutorial, we are going to introduce the resilient distributed datasets (RDDs) # which is Spark's core abstraction when working with data. An RDD is a distributed collection # of elements which can be operated on in parallel. Users can create RDD in two ways: # parallelizing an existing collection in your driver program, or loading a dataset in an external storage system. # RDDs support two types of operations: transformations and actions. Transformations construct a new RDD from a previous one and # actions compute a result based on an RDD,. We introduce the basic operations of RDDs by the following simple word count example: from pyspark import SparkContext from pyspark.sql import SparkSession sc = SparkContext.getOrCreate() spark = SparkSession.builder \ .appName("Spark_Basics") \ .getOrCreate() text_file = sc.parallelize(["hello","hello world"]) counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) for line in counts.collect(): print line # The first line defines a base RDD by parallelizing an existing Python list. # The second line defines counts as the result of a few transformations. # In the third line and fourth line, the program print all elements from counts by calling collect(). # collect() is used to retrieve the entire RDD if the data are expected to fit in memory.
true
c767555ee9c73ae671ed7d37c5951dbe943c3635
hoangqwe159/DoVietHoang-C4T5
/Homework 2/session 2.py
258
4.21875
4
from turtle import * shape("turtle") speed(0) # draw circles circle(50) for i in range(4): for i in range (360): forward(2) left(1) left(90) #draw triangle # = ctrl + / for i in range (3): forward(100) left(120) mainloop()
true
fe892de04ecbf1e806c4669f14b582fd1a801564
qodzero/icsv
/icsv/csv
578
4.15625
4
#!/usr/bin/env python3 import csv class reader(obj): ''' A simple class used to perform read operations on a csv file. ''' def read(self, csv_file): ''' simply read a csv file and return its contents ''' with open(csv_file, 'r') as f: cs = csv.reader(f) cs = [row for row in cs] df = dict() for key in cs[0]: df[key] = [] df_keys = [key for key in df.keys()] for row in cs[1: ]: for i, col in enumerate(row): df[df_keys[i]].append(col) return df
true
8b9059649cbaad48bb6b53fa8a4624eb9b5819a9
aha1464/lpthw
/ex21.py
2,137
4.15625
4
# LPTHW EX21 # defining the function of add with 2 arguments. I add a and b then return them def add(a, b): print(f"ADDING {a} + {b}") return a + b # defining the function of subtract def subtract(a, b): print(f"SUBTRACKTING {a} - {b}") return a - b # defining the function of multiply def multiply(a, b): print(f"MULTIPLING {a} * {b}") return a * b # defining the function of divide def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b # print the text in the string and add a new line print(f"let's do some math with just functions!\n") # defining age, height, weight & iq by addition, subraction, multiplying and # dividing with the (the values, required) age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) # print the text with their {variable} print(f"Age: {age}, Height {height}, Weight {weight}, IQ {iq}\n") # a puzzle for the extra credit, type it in anyway # print the text below in the terminal print(f"Here is the puzzle.") # WTF, I have no idea??? Inside out: (iq, 2)(/ weight)(multiply by height) #(subtract age) add # 50/2 = 25 # 180 * 24 = 4500 # 74 - 4500 # 35 + -4426 = -4391 # what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print("That becomes: ", what, "Can you do it by hand?") print("24 + 34 / 100 - 1023") # Extra Credit: # 1. If you aren't really sure what return does, try writing a few of your own # functions and have them return some values. You can return anything that you # can put to the reight of an = # 2. At the end of hte script is a puzzle. I'm taking th return value of one # function and using it as the argument of an other funtion. I'm doing this in # a chain so that I'm kind of creating a formula using the function. It looks # really weird, but if you run the sript, you can see the results. # 3. Once you have the formula worked out for the puzzle, get in there and see # what happens when you modify the parts of the functions. Try to change it on # purpose to make another value. # 4. Do the inverse. Write a simsple forumula and use the functions in the # same way to calculate it.
true
6345bac40a37f7811ffd2cf6b011e339bdd072f7
aha1464/lpthw
/ex16.py
1,371
4.25
4
# import = the feature argv = argument variables sys = package from sys import argv # script, filename = argv # printed text that is shown to the user when running the program print(f"We're going to erase (filename).") print("If you don't want that, hit CTRL-C (^c).") print("If you do want that, hit RETURN.") # input = user input required ("prompt text goes here") input("?") # prints ("the text") print("Opening the file...") # target = open(user inputed filename in the terminal) 'W' says open this file in 'write mode' target = open(filename, 'w') # prints ("the text here") print("Truncating the file. Goodbye!") # target command truncate: empties the file. target.truncate() # prints("the text" in the terminal) print("Now I'm going to ask you for three lines.") # # line1 is the id and input gives the command that the user needs to input info line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: " # prints ("the text" in the terminal) print("I'm going to write these to the file.") # target.write(the text the user inputs in the terminal when prompted) target.write(line1) # using ("\n") starts a new line target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") # print the ("text") print("And finally, we close it.") # targer.close() closes and saves the file that has been created target.close()
true
3af1f947862099145d100d986ad158586368d47b
thetrashprogrammer/StartingOutWPython-Chapter3
/fat_and_carbs.py
1,491
4.375
4
# Programming Exercise 3.7 Calories from Fat and Carbohydrates # May 3rd, 2010 # CS110 # Amanda L. Moen # 7. Calories from Fat and Carbohydrates # A nutritionist who works for a fitness club helps members by # evaluating their diets. As part of her evaluation, she asks # members for the number of fat grams and carbohydrate grams # that they consumed in a day. Then, she calculates the number # of calories that result from the fat, using the following # formula: # calories from fat = fat grams X 9 # Next, she calculates the number of calories that result from # the carbohydrates, using the following formula: # calories from carbs = carb grams X 4 # The nutritionist asks you to write a program that will make # these calculations. def main(): # Ask for the number of fat grams. fat_grams = input('Enter the number of fat grams consumed: ') fat_calories(fat_grams) # Ask for the number of carb grams. carb_grams = input('Enter the number of carbohydrate grams consumed: ') carb_calories(carb_grams) def fat_calories(fat_grams): # Calculate the calories from fat. # calories_from_fat = fat_grams*9 calories_from_fat = fat_grams * 9 print 'The calories from fat are', calories_from_fat def carb_calories(carb_grams): # Calculate the calories from carbs. # calories_from_carbs = carb_grams * 4 calories_from_carbs = carb_grams * 4 print 'The calories from carbohydrates are', calories_from_carbs # Call the main function. main()
true
7dcc48ffebb1ae534fa973cab9d70c77e7b7a610
wade-sam/variables
/Second program.py
245
4.15625
4
#Sam Wade #09/09/2014 #this is a vaiable that is storing th value entered by the user first_name = input("please enter your first name: ") print(first_name) #this ouputs the name in the format"Hi Sam!" print("Hi {0}!".format(first_name))
true
d490e1f73448f32eb150b3994f359cffb155acc4
pankhurisri21/100-days-of-Python
/variables_and_datatypes.py
548
4.125
4
#variables and datatypes #python variables are case sensitive print("\n\nPython variables are case sensitive") a=20 A=45 print("a =",a) print("A =",A) a=20#integer b=3.33 #float c="hello" #string d=True #bool #type of value print("Type of different values") print("Type of :",str(a)+" =",type(a)) print("Type of :",str(b)+" =",type(b)) print("Type of : "+str(c)+ " =",type(c)) print("Type of : "+str(d)+" =",type(d)) #Type conversion print("New Type of:",a,end=" = ") print(type(str(a))) print("New Type of:",b,end=" = ") print(type(int(b)))
true
b2eb51f1c07dc6b03bd49499e392191e4578a2ed
rbk2145/DataScience
/9_Manipulating DataFrames with pandas/2_Advanced indexing/1_Index objects and labeled data.py
814
4.4375
4
####Index values and names sales.index = range(len(sales)) ####Changing index of a DataFrame # Create the list of new indexes: new_idx new_idx = [month.upper() for month in sales.index] # Assign new_idx to sales.index sales.index = new_idx # Print the sales DataFrame print(sales) ######Changing index name labels # Assign the string 'MONTHS' to sales.index.name sales.index.name = 'MONTHS' # Print the sales DataFrame print(sales) # Assign the string 'PRODUCTS' to sales.columns.name sales.columns.name = 'PRODUCTS' # Print the sales dataframe again print(sales) ####Building an index, then a DataFrame # Generate the list of months: months months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] # Assign months to sales.index sales.index = months # Print the modified sales DataFrame print(sales)
true
a991555e799064d6a89f9c0c1cc460fcf41ce8ea
TazoFocus/UWF_2014_spring_COP3990C-2507
/notebooks/scripts/cli.py
664
4.21875
4
# this scripts demonstrates the command line input # this works under all os'es # this allows us to interact with the system import sys # the argument list that is passed to the code is stored # in a list called sys.argv # this list is just like any list in python so you should treat it as such cli_list = sys.argv # how many elements is in the list? print 'The length of my cli list is: ', len(cli_list) # what is the list of arguments? print 'Here is my list: ', cli_list # what is the first element? print 'this is the name of my python file: ', cli_list[0] # how about the rest of the elements for cli_element in cli_list[1:]: print cli_element
true
f68f8aaf53e834b5b3297a2852518edba06ebbe0
denrahydnas/SL9_TreePy
/tree_while.py
1,470
4.34375
4
# Problem 1: Warm the oven # Write a while loop that checks to see if the oven # is 350 degrees. If it is, print "The oven is ready!" # If it's not, increase current_oven_temp by 25 and print # out the current temperature. current_oven_temp = 75 # Solution 1 here while current_oven_temp < 350: print("The oven is at {} degrees".format(current_oven_temp)) current_oven_temp += 25 else: print("The oven is ready!") # Problem 2: Total and average # Complete the following function so that it asks for # numbers from the user until they enter 'q' to quit. # When they quit, print out the list of numbers, # the sum and the average of all of the numbers. def total_and_average(): numbers = [] while True: add = input("Please give me a number, or type 'q' to quit: ").lower() if add == 'q': break try: numbers.append(float(add)) except ValueError: continue print("You entered: ", numbers) print("The total is: ", sum(numbers)) print("The average is: ", sum(numbers)/len(numbers)) total_and_average() # Problem 3: Missbuzz # Write a while loop that increments current by 1 # If the new number is divisible by 3, 5, or both, # print out the number. Otherwise, skip it. # Break out of the loop when current is equal to 101. current = 1 # Solution 3 here while current < 101: if not current % 3 or current % 5 == 0: print(current) current += 1
true