blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
72a5f79be816896fcdfbab8dd0a54f1588d25551
jeremyyew/tech-prep-jeremy.io
/code/topics/1-searching-and-sorting/M148-sorted-list.py
1,589
4.125
4
Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sortList(self, head): pass # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(self, head): current_size = 1 left = head while left: left = head while left: mid = left + current_size - 1 right = len(a) - 1 if 2 * current_size + left - 1 > len(a)-1 else 2 * current_size + left - 1 mergeTwoLists(a, left, mid, right) left = left.next current_size = 2 * current_size # Merge Function def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ node = ListNode(None) head = node while True: # better than a termination condition, because its tricky to refactor the code to pop the list for the next iteration to check, when you can't keep a reference to which list you want to pop at the end. print(node.val) if l1 is None and l2 is None: return # there is at least one non-None if l1 is None or l2 is None: if l1 is None: some = l2 else: some = l1 node.next = some return head.next # both are non-None if l1.val < l2.val: node.next = l1 l1 = l1.next else: node.next = l2 l2 = l2.next node = node.next return head.next
true
5ccb88df6a21f7a105c7c08d2551412c4cc307bb
sachin1005singh/complete-python
/python_program/findvowel.py
218
4.28125
4
#vowels program use of for loop vowel = "aeiouAEIOU" while True: v = input("enter a vowel :") if v in vowel: break print("this in not a vowel ! try again !!") print("thank you")
true
74a079f8a0c40df56f5412dd4723cb2368b3759a
kartsridhar/Problem-Solving
/halindrome.py
1,382
4.25
4
""" Given a string S. divide S into 2 equal parts S1 and S2. S is a halindrome if AT LEAST one of the following conditions satisfy: 1. S is a palindrome and of length S >= 2 2. S1 is a halindrome 3. S2 is a halindrome In case of an odd length string, S1 = [0, m-1] and S2 = [m+1, len(s)-1] Example 1: input: harshk output: False Explanation 1: S does not form a palindrome S1 = har which is not a halindrome S2 = shk which is also not a halindrome. None are true, so False. Example 2: input: hahshs output: True Explanation 2: S is not a palindrome S1 = hah which is a palindrome S2 = shs which is also a palindrome Example 3: input: rsrabdatekoi output: True Explanation 3: rsrabd, atekoi Neither are palindromic so you take each word and split again Break down rsrabd coz it's not palindromic, rsr, abd. rsr length is >=2 and is a palindrome hence it's true """ def splitString(s): return [s[0:len(s)//2], s[len(s)//2:]] if len(s) >= 2 else [] def checkPalindrome(s): return s == s[::-1] if len(s) >= 2 else False def checkHalindrome(s): print(s) if checkPalindrome(s): return True else: splits = splitString(s) if len(splits) == 0: return False else: for i in splits: return checkHalindrome(i) return False inputs = 'rsrabdatekoi' print(checkHalindrome(inputs))
true
408d751896467c077d7dbc1ac9ffe6239fed474d
kartsridhar/Problem-Solving
/HackerRank/Problem-Solving/Basic-Certification/unexpectedDemand.py
1,630
4.40625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'filledOrders' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY order # 2. INTEGER k # """ A widget manufacturer is facing unexpectedly high demand for its new product,. They would like to satisfy as many customers as possible. Given a number of widgets available and a list of customer orders, what is the maximum number of orders the manufacturer can fulfill in full? Function Description Complete the function filledOrders in the editor below. The function must return a single integer denoting the maximum possible number of fulfilled orders. filledOrders has the following parameter(s): order : an array of integers listing the orders k : an integer denoting widgets available for shipment Constraints 1 ≤ n ≤ 2 x 105 1 ≤ order[i] ≤ 109 1 ≤ k ≤ 109 Sample Input For Custom Testing 2 10 30 40 Sample Output 2 """ def filledOrders(order, k): # Write your code here total = 0 for i, v in enumerate(sorted(order)): if total + v <= k: total += v else: return i else: return len(order) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') order_count = int(input().strip()) order = [] for _ in range(order_count): order_item = int(input().strip()) order.append(order_item) k = int(input().strip()) result = filledOrders(order, k) fptr.write(str(result) + '\n') fptr.close()
true
914c7c8db0d3d316d22d899ba6756368ae4eb392
pythonmite/Daily-Coding-Problem
/problem_6_medium.py
514
4.1875
4
""" Company Name : DropBox Problem Statement : Find the second largest element in the list. For example: list :[2,3,5,6,6] secondlargestelement >>> [5] """ def findSecondLargestNum(arr:list): max = arr[0] for num in arr: if num > max: max = num secondlargest = 0 for num in arr: if num > secondlargest and num < max: secondlargest = num return secondlargest arr = [2,3,5,6,6] answer = findSecondLargestNum(arr) print(answer) # >>> 5
true
de1515c2150e80505cca6fbec738b38bc896487f
KarenRdzHdz/Juego-Parabolico
/parabolico.py
2,756
4.34375
4
"""Cannon, hitting targets with projectiles. Exercises 1. Keep score by counting target hits. 2. Vary the effect of gravity. 3. Apply gravity to the targets. 4. Change the speed of the ball. Integrantes: Karen Lizette Rodríguez Hernández - A01197734 Jorge Eduardo Arias Arias - A01570549 Hernán Salinas Ibarra - A01570409 15/09/2021 Exercises marked by ***ejercicio realizado*** """ "Libraries used" from random import randrange from turtle import * from typing import Sized from freegames import vector "Global variables used in game" ball = vector(-200, -200) speed = vector(0, 0) gravity = 25 s = 200 targets = [] count = 0 def changeGravity(value): "Set gravity to global variable" global gravity gravity = value def changeSpeed(sp): # ***Exercise 4: change speed*** "Set speed to global variable" global s s = sp def tap(x, y): "Respond to screen tap." if not inside(ball): ball.x = -199 ball.y = -199 speed.x = (x + 200) / gravity speed.y = (y + 200) / gravity def inside(xy): "Return True if xy within screen." return -200 < xy.x < 200 and -200 < xy.y < 200 def draw(): "Draw ball and targets." clear() for target in targets: goto(target.x, target.y) dot(20, 'blue') if inside(ball): goto(ball.x, ball.y) dot(6, 'red') update() def move(): "Move ball and targets." if randrange(40) == 0: y = randrange(-150, 150) target = vector(200, y) targets.append(target) for target in targets: target.x -= 0.5 target.y -= 0.5 # ***Exercise 3: add gravity to targets*** if inside(ball): speed.y -= 0.35 ball.move(speed) dupe = targets.copy() targets.clear() for target in dupe: if abs(target - ball) > 13: targets.append(target) draw() "Count balls hit" # ***Exercise 1: count balls hit*** if len(dupe) != len(targets): global count diferencia = len(dupe)-len(targets) count += diferencia style = ('Courier', 30, 'bold') write(count, font=style, align='right') # Game never ends remove condition # ***Exercise 5: Game never ends*** #for target in targets: #if not inside(target): #return ontimer(move, s) setup(420, 420, 370, 0) hideturtle() up() tracer(False) listen() onkey(lambda: changeGravity(50), 'a') # ***Exercise 2: vary the effect of gravity*** onkey(lambda: changeGravity(25), 's') onkey(lambda: changeGravity(12), 'd') onkey(lambda: changeSpeed(100), 'q') onkey(lambda: changeSpeed(50), 'w') onkey(lambda: changeSpeed(25), 'e') onscreenclick(tap) move() done()
true
627a95962abed7b46f673bf813375562b3fa1cd2
imruljubair/imruljubair.github.io
/teaching/material/List/7.py
413
4.375
4
# append() # Example 7.1 def main(): name_list = [] again = 'y' while again == 'y': name = input("Enter a name : ") name_list.append(name) print('Do you want to add another name ?') again = input('y = yes, anything else = no: ') print() print('The names you have listed: ') for name in name_list: print(name) main()
true
0c110fece3e121665c41b7f1c039c190ed1b7866
imruljubair/imruljubair.github.io
/teaching/material/List/5.py
268
4.28125
4
# Concating and slicing list # Example 5.1 list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print(list3) # Example 5.2 days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday'] mid_days = days[2:5] print(mid_days)
true
aea3ddf894c253cfe9bcdae7a3878f67bf76a5b7
softwaresaved/docandcover
/fileListGetter.py
1,118
4.375
4
import os def fileListGetter(directory): """ Function to get list of files and language types Inputs: directory: Stirng containing path to search for files in. Outputs: List of Lists. Lists are of format, [filename, language type] """ fileLists = [] for root, dirs, files in os.walk(directory): for filename in files: file_extention = filename.split(".")[-1] languageType = getLanguageType(file_extention) filename = os.path.join(root, filename) fileLists.append([filename, languageType]) return fileLists def getLanguageType(file_extention): """ Function to assign language type based on file extention. Input: file_extention: String that lists file type. Output: languageType: string listsing identified language type. """ if file_extention == 'py': return 'python' else: return 'Unknown' def printFileLists(fileLists): """ Function to print out the contents of fileLists Main use is debugging """ for fileList in fileLists: print fileList
true
384785ebd3f0e57cc68ac0cd00389f4bcfd8b245
AffanIndo/python-script
/caesar.py
702
4.21875
4
#!usr/bin/env python """ caesar.py Encrypt or decrypt text based from caesar cipher Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python """ def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift if stayInAlphabet > ord('z'): stayInAlphabet -= 26 finalLetter = chr(stayInAlphabet) cipherText += finalLetter print("Your ciphertext is: ", cipherText) return cipherText if __name__ == '__main__': plainText = input("Insert your text:\n") shift = int(input("Insert how many shift:")) caesar(plainText, shift)
true
20ffbd80d572fd4b75db8860c04c034cb6d87ab0
midephysco/midepython
/exercises2.py
250
4.125
4
#this is a program to enter 2 numbers and output the remainder n0 = input("enter a number ") n1 = input("enter another number") div = int(n0) / int(n1) remainder = int(n0) % int(n1) print("the answer is {0} remainder {1}".format(div, remainder))
true
19665f62b7fa38f9cbc82e17e02dacd6de092714
midephysco/midepython
/whileloop2.py
452
4.21875
4
#continous loop print("Adding until rogue value") print() print("This program adds up values until a rogue values is entered ") print() print("it then displays the sum of the values entered ") print() Value = None Total = 0 while Value != 0: print("The total is: {0}.".format(Total)) print() Value = int(input("Please enter a value to add to total: ")) Total = Total + Value print() print("The final total is: {0}.".format(Total))
true
cdfad3f2a3b8d22c82c203195a5c03ec456111e6
VineethChandha/Cylinder
/loops.py
987
4.125
4
# PY.01.10 introduction to the loops for a in range(1,11): # a will be valuated from 1 to 10 print("Hi") print(a) even_numbers = [x for x in range(1,100) if x%2 == 0] print(even_numbers) odd_numbers = [x for x in range(1,100) if x%2 != 0] print(odd_numbers) words = ["ram","krishna","sai"] answer = [[w.upper(),w.lower(),len(w)] for w in words] print(answer) word = ["Happy","Birthday","To","You"] word="-".join(word) #Join key word is used to join the list of the words with some specific sign or space as required print(word) Word2 = "Happy Birthday To You" split_word = Word2.split() #.split() funtion is used to make the sentance to the list of words print(split_word) # This brings out the names of friends in which letter a is present names={"male":["sandeep","rakesh","sudheer",],"female":["sravani","dolly"]} for gender in names.keys(): for friend in names[gender]: if "a" in friend: print(friend)
true
aaf7a5a0a5195ff1376ef2f0d6e6f84ffc273341
XxdpavelxX/Python3
/L3 Iteration in Python/decoder.py
1,682
4.625
5
"""Create a Python3_Homework03 project and assign it to your Python3_Homework working set. In the Python3_Homework03/src folder, create a file named decoder.py, which contains an iterator named alphabator. When passed a list, simply return objects as-is unless they are integers between 1 and 26, in which case it should convert that number to the corresponding letter. The integer-to-letter correspondence is 1=A, 2=B, 3=C, 4=D, and so on. You may use any technique you've learned in lesson 3 to execute this project. Your alphabator iterator must pass the unittest below: test_decoder.py from string import ascii_uppercase import unittest from decoder import alphabator class TestAlpha(unittest.TestCase): def test_easy_26(self): a = alphabator(range(1,27)) self.assertEqual(list(ascii_uppercase), list(a)) def test_upper_range(self): a = alphabator(range(40,50)) self.assertEqual(list(range(40, 50)), list(a)) def test_various_objects(self): l = ['python', object, ascii_uppercase, 10, alphabator] a = list(alphabator(l)) self.assertNotEqual(l[3], a[3]) self.assertEqual("J", a[3]) self.assertTrue(isinstance(a[1], object)) if __name__ == "__main__": unittest.main() Submit decoder.py and test_decoder.py when they are working to your satisfaction. """ #################################################################################################################################################################### def alphabator(lst): for num in lst: if num in range(1,27): yield chr(num+64) else: yield num
true
0a78c83f9ef57d9b72a23fe657ed93c9761f3e3e
XxdpavelxX/Python3
/L4 Basic Regular Expressions/find_regex.py
1,719
4.3125
4
"""Here are your instructions: Create a Python3_Homework04 project and assign it to your Python3_Homework working set. In the Python3_Homework04/src folder, create a program named find_regex.py that takes the following text and finds the start and end positions of the phrase, "Regular Expressions". Text to use in find_regex.py In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theoryin a set of models using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system, called Regular Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold, Ivan P. Polonsky, Ken Thompson, and Henry Spencer. Your project should meet the following conditions: •Your code must return 231 as the start and 250 as the end. •You must include a separate test_find_regex.py program that confirms that your code functions as instructed. Submit find_regex.py and test_find_regex.py when they are working to your satisfaction.""" ############################################################################################################################################################## import re a = """In the 1950s, mathematician Stephen Cole Kleene described automata theory and formal language theory in a set of models using a notation called "regular sets" as a method to do pattern matching. Activeusage of this system, called Regular Expressions, started in the 1960s and continued under such pioneers as David J. Farber, Ralph E. Griswold, Ivan P. Polonsky, Ken Thompson, and Henry Spencer.""" def searcher(): match = re.search("Regular Expressions", a) beginning = match.start() ending = match.end() return (("Starts at:%d, Ends at:%d")%(beginning, ending)) print (searcher())
true
ccc8620d0ec8f4dd1fdf13800ce16db8efa218ff
BiancaHofman/python_practice
/ex37_return_and_lambda.py
744
4.3125
4
#1. Normal function that returns the result 36 #And this result is printed def name(): a = 6 return a * 6 print(name()) #2. Normal function that only prints the result 36 def name(): a = 6 print(a * 6) name() #3. Anonymous function that returns the result 36 #And this result is printed x = lambda a: a * 6 print(x(6)) #4. Normal function that returns the result 30 #And this result is printed def multiply(): a = 6 b = 5 return a * b print(multiply()) #5. Normal function that only prints the result 30 def multiply(): a = 6 b = 5 print(a * b) multiply() #6.Anonymous function that returns result 30 #And this result is prints multiply = lambda a, b: a * b print(multiply (6,5))
true
2cf1813ba0c933c00afef4c26bec91ec7b1494ff
johnsbuck/MapGeneration
/Utilities/norm.py
1,596
4.34375
4
"""N-Dimensional Norm Defines the norm of 2 points in N dimensional space with different norms. """ import numpy as np def norm(a, pow=2): """ Lp Norm Arguments: a (numpy.ndarray): A numpy array of shape (2,). Defines a point in 2-D space. pow (float): The norm used for distance (Default: 2) Returns: (float) The distance between point a and point b with Lp Norm. """ return np.float_power(np.sum([np.float_power(np.abs(a[i]), pow) for i in range(len(a))]), 1./pow) def manhattan(a): """Manhattan Norm Arguments: a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. Returns: The distance between points a and b with L1 norm. """ return norm(a, pow=1) def euclidean(a): """Euclidean Norm Arguments: a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. Returns: The distance between points a and b with L2 norm. """ return norm(a, pow=2) def minkowski(a): """Minkowski Norm Arguments: a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. Returns: The distance between points a and b with L3 norm. """ return norm(a, pow=3) def chebyshev(a): """Chebyshev Norm Arguments: a (numpy.ndarray): A numpy array of shape (2,) or (2, 1). Defines a point in 2-D space. Returns: The distance between points a and b with L-Infinity norm. """ return np.max([np.abs(a[i]) for i in range(len(a))])
true
81a1ab2f702bd56d5379540bee0e14044661a958
Manmohit10/data-analysis-with-python-summer-2021
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
864
4.21875
4
#!/usr/bin/env python3 import math def main(): while True: shape=input("Choose a shape (triangle, rectangle, circle):") shape=str(shape) if shape=="": break elif shape=='triangle': base=float(input('Give base of the triangle:')) height=float(input('Give height of the triangle:')) print(f"The area is {base*height*0.5}") elif shape=='rectangle': base=float(input('Give width of the rectangle:')) height=float(input('Give height of the rectangle:')) print(f"The area is {base*height}") elif shape=='circle': radius=float(input('Give radius of the circle:')) print(f"The area is {math.pi*(radius**2)}") else: print('Unknown shape!') if __name__ == "__main__": main()
true
87b47edb3ac4c944e7498021311d29a683de4873
mashanivas/python
/scripts/fl.py
208
4.28125
4
#!/usr/bin/python #Function for powering def raise_to_power(base_num, pow_num): result = 1 for index in range(pow_num): result = result * base_num return result print(raise_to_power(2, 3))
true
8570e157445bcbb0d2ff72b5d3c62921d5e084fd
prahaladbelavadi/codecademy
/python/5.making-a-request.py
1,129
4.40625
4
# Making a Request # You saw a request in the first exercise. Now it's time for you to make your own! (Don't worry, we'll help.) # # On line 1, we've imported urlopen from the urllib2 module, which is the Python way of bringing in additional functionality we'll need to make our HTTP request. A module is just a collection of extra Python tools. # # On line 4, we'll use urlopen on placekitten.com in preparation for our GET request, which we make when we read from the site on line 5. (On line 6, we limit the response to specific character numbers to control the input we get back—this is what gives us our cat image.) # # We'll need your help to complete the request! # # Instructions # On line 4, declare a variable, kittens, and set it equal to calling urlopen on http://placekitten.com. No need for the "www"! # # On line 8, print the body variable so we can see some of the data we got back. from urllib2 import urlopen # Open http://placekitten.com/ for reading on line 4! kittens = urlopen('http://placekitten.com') response = kittens.read() body = response[559:1000] # Add your 'print' statement here! print body
true
ac3a6fcb8237f80f54bd88856cc669d578ea08b5
kieranmcgregor/Python
/PythonForEverybody/Ch2/Ex2_prime_calc.py
2,439
4.125
4
import sys def prime_point_calc(numerator, denominator): # Returns a number if it is a prime number prime = True while denominator < numerator: if (numerator % denominator) == 0: prime = False break else: denominator += 1 if prime: return numerator def prime_list_calc(numerator_limit, denominator): # Returns list of prime numbers from 1 to user defined limit primes = [1, 2] numerator = 3 while numerator <= numerator_limit: prime = prime_point_calc(numerator, denominator) if prime != None: primes.append(prime) if denominator == numerator: denominator == 0 numerator += 1 return primes def prime_start_calc(start, denominator): # Returns next prime after given user input not_prime = True prime = 0 numerator = start while not_prime: prime = prime_point_calc(numerator, denominator) if prime != None: not_prime = False numerator += 1 return prime def main(): numerator_empty = True lps_empty = True denominator = 2 prime = None primes = None print ("\nThis program will calculate prime numbers.") while numerator_empty: numerator = input("Please enter an integer: ") try: numerator = int(numerator) numerator_empty = False except: print ("Invalid entry, not an integer.") while lps_empty: lps = input("Is this number a [l]imit, a [p]oint or a [s]tart? ") if lps != 'l' and lps != 'p' and lps != 's': print("Invalid entry, type 'l' for limit, 'p' for point or 's' for start.") else: lps_empty = False if numerator > sys.maxsize: numerator = sys.maxsize - 10 if lps[0].lower() == 'l': numerator_limit = numerator primes = prime_list_calc(numerator_limit, denominator) elif lps[0].lower() == 'p': prime = prime_point_calc(numerator, denominator) elif lps[0].lower() == 's': start = numerator prime = prime_start_calc(start, denominator) if prime != None: print ("{} is a prime number.".format(prime)) elif primes != None: print ("The following numbers are primes.\n{}".format(primes)) elif prime == None: print ("{} is not a prime number.".format(numerator)) main()
true
58bfbf28aa758d222f0375e61b4ed2dc95c2c8da
kieranmcgregor/Python
/PythonForEverybody/Ch9/Ex2_Day_Sort.py
1,767
4.15625
4
def quit(): quit = "" no_answer = True while no_answer: answer = input("Would you like to quit? (y/n) ") try: quit = answer[0].lower() no_answer = False except: print ("Invalid entry please enter 'y' for yes and 'n' for no.") continue if quit == 'n': return True elif quit != 'y': print ("Neither 'y' nor 'n' found, exiting program") return False def open_file(fname): fpath = "../Files/" + fname try: fhand = open(fpath) except: print("Invalid file path, using default ../Files/mbox-short.txt") fpath = "../Files/mbox-short.txt" fhand = open(fpath) return fhand def search(days_of_week): search_on = True while search_on: search = input("Enter day of the week:\n").title() if search in days_of_week: print ("{} commits were done on {}".format(days_of_week[search], search)) else: print ("Your search was not found") answer = input("Would you like to continue searching? (y/n) ") if 'y' in answer.lower(): continue else: search_on = False no_quit = True days_of_week = {} while no_quit: fname = input("Please enter just the file name with extension:\n") fhand = open_file(fname) for line in fhand: if line.startswith("From "): words = line.split() if len(words) > 3: day_of_week = words[2] try: days_of_week[day_of_week] += 1 except: days_of_week[day_of_week] = 1 fhand.close() print (days_of_week) search(days_of_week) no_quit = quit()
true
86f91d794953d183366e9290564313d1dcaa594e
gmanacce/STUDENT-REGISTERATION
/looping.py
348
4.34375
4
###### 11 / 05 / 2019 ###### Author Geofrey Manacce ###### LOOPING PROGRAM ####CREATE A LIST months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december'] print(months) #####using For loop for month in months: print(month.title() + "\n") print("go for next month:") print("GOODBYE!!!!")
true
d830adc3169ec263a5043079c99d8a8a65cda037
orrettb/python_fundamental_course
/02_basic_datatypes/2_strings/02_11_slicing.py
562
4.40625
4
''' Using string slicing, take in the user's name and print out their name translated to pig latin. For the purpose of this program, we will say that any word or name can be translated to pig latin by moving the first letter to the end, followed by "ay". For example: ryan -> yanray, caden -> adencay ''' #take the users name via input user_name = input("Enter your first name:") #select the first letter fist_letter = user_name[0] #add pig latin variable pig_value = "ay" pig_latin_ver = user_name[1:]+fist_letter+pig_value #print result print(pig_latin_ver)
true
482a4ab3e78e3f5e755ea3ff9b66fc48d3e5860f
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
/7.10 Problems/5.6-17.py
367
4.1875
4
# Use a for statement to print 10 random numbers. # Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive. import random count = 1 # This keeps track of how many times the for-loop has looped print("2") for i in range(10): number = random.randint(25,35) print("Loop: ",count," Random Number: ", number) count += 1
true
b5c3a44e099edcc1974e5854b17e4b2475dc6a76
Appu13/RandomCodes
/DivideandConquer.py
678
4.1875
4
''' Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers. Return as a number. ''' def div_con(x): # Variable to hold the string total strtot = 0 # Variable to hold the digit total digitot = 0 # Iterate through the list for ch in x: # Check if the current element is of type string if isinstance(ch, str): # Convert to integer and add to string total strtot += int(ch) # Else add to digit total else: digitot += ch # return the difference return digitot - strtot
true
7a049ad9b04e1243ad1f440447d89fe112979633
Mvk122/misc
/CoinCounterInterviewQuestion.py
948
4.15625
4
""" Question: Find the amount of coins required to give the amount of cents given The second function gets the types of coins whereas the first one only gives the total amount. """ def coin_number(cents): coinlist = [25, 10, 5, 1] coinlist.sort(reverse=True) """ list must be in descending order """ cointotal = 0 while cents != 0: for coin in coinlist: if coin <= cents: cents -= coin cointotal += 1 break return cointotal def cointype(cents): coinlist = [25, 10, 5, 1] coinlist.sort(reverse=True) coincount = [[25,0], [10,0], [5,0], [1,0]] while cents != 0: for coin in coinlist: if coin <= cents: cents -= coin coincount[coinlist.index(coin)][1] += 1 break return coincount print(coin_number(50))
true
8ce075118b7aca2dd2dc8f54eb59146e8c4edaf4
Svanfridurjulia/FORRITUN-SJS-HR
/Hlutapróf 2/prófdæmi.py
1,553
4.3125
4
def sum_number(n): '''A function which finds the sum of 1..n and returns it''' sum_of_range = 0 for num in range (1,n+1): sum_of_range += num return sum_of_range def product(n): '''A function which finds the product of 1..n and returns it''' multi = 1 for num in range(1,n+1): multi = multi * num return multi def print_choices(): '''A function which prints the choices and gets the choice from the user and returns it''' print("""1: Compute the sum of 1..n 2: Compute the product of 1..n 9: Quit""") choice = input("Choice: ") return choice def choice_1(int_list): '''A function for the choice 1 which calls the sum function and prints out the sum, returns nothing''' sum_of_numbers = sum_number(int_list) print("The result is:",sum_of_numbers) def choice_2(int_list): '''A function for the choice 2 which calls the product function and prints out the product, returns nothing''' product_of_numbers = product(int_list) print("The result is:",product_of_numbers) def choices(choice, n): '''A function which calls other functions depending on what the user choice is and returns nothing''' if choice == "1": choice_1(n) elif choice == "2": choice_2(n) #Main choice = print_choices() while choice != "9": if choice == "1" or choice == "2": try: n = int(input("Enter value for n: ")) choices(choice, n) except ValueError: pass choice = print_choices()
true
7c041a0333ad9a58383c495981485c535f6aa8bd
Svanfridurjulia/FORRITUN-SJS-HR
/æfingapróf/dæmi2.py
878
4.21875
4
def open_file(filename): opened_file = open(filename,"r") return opened_file def make_list(opened_file): file_list = [] for lines in opened_file: split_lines = lines.split() file_list.append(split_lines) return file_list def count_words(file_list): word_count = 0 punctuation_count = 0 for lines in file_list: for element in lines: word_count += 1 for chr in element: if chr == "," or chr == "." or chr == "!" or chr == "?": punctuation_count += 1 return word_count + punctuation_count #main filename = input("Enter filename: ") try: opened_file = open_file(filename) file_list = make_list(opened_file) word_count = count_words(file_list) print(word_count) except FileNotFoundError: print("File {} not found!".format(filename))
true
9be417a8ba86044f1b8717d993f44660adfbf9cd
Svanfridurjulia/FORRITUN-SJS-HR
/æfing.py
1,056
4.3125
4
def find_and_replace(string,find_string,replace_string): if find_string in string: final_string = string.replace(find_string,replace_string) return final_string else: print("Invalid input!") def remove(string,remove_string): if remove_string in string: final2_string = string.replace(remove_string,"") return final2_string else: print("Invalid input!") first_string = input("Please enter a string: ") print("""\t1. Find and replace \t2. Find and remove \t3. Remove unnecessary spaces \t4. Encode \t5. Decode \tQ. Quit""") option = input("Enter one of the following: ") if option == "1": find_string = input("Please enter substring to find: ") replace_string = input("Please enter substring to replace with: ") final1_string = find_and_replace(first_string,find_string,replace_string) print(final1_string) elif option == "2": remove_string = input("Please enter substring to remove: ") final2_string = remove(first_string,remove_string) print(final2_string)
true
f0d663cbc1f64b3d08e61927d47f451272dfd746
Hiradoras/Python-Exercies
/30-May/Valid Parentheses.py
1,180
4.375
4
''' Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>). ''' def valid_parentheses(string): is_valid = None cleared = "".join(i for i in string if i=="(" or i==")") uncompletes = [] for i in range(len(cleared)): if cleared[i]=="(": uncompletes.append(cleared[i]) elif cleared[i]==")": try: uncompletes.pop() except: return False if len(uncompletes) == 0: is_valid = True else: is_valid = False return is_valid print(valid_parentheses("()")) print(valid_parentheses("())")) print(valid_parentheses("((((()"))
true
cf9270abd93e8b59cdb717deeea731308bf5528d
Hiradoras/Python-Exercies
/29-May-2021/Reverse every other word in the string.py
895
4.25
4
''' Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata. ''' def reverse_alternate(string): words = string.split() new_words = [] for i in range(0,len(words)): if i % 2 == 0: new_words.append(words[i]) else: word = words[i] new_words.append(word[::-1]) return " ".join(new_words) print(reverse_alternate("Did it work?")) ############# Or ############### def shorter_reverse_alternative(string): return " ".join([element[::-1] if i % 2 else element for i,element in enumerate(string.split())]) print(shorter_reverse_alternative("Did it work?")) ### Same function but smarter and shorted with enumerate() method.
true
dc4cfcc11c9b26f1e27874d1b9ac84291664b33c
susanbruce707/hexatrigesimal-to-decimal-calculator
/dec_to_base36_2.py
696
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 21 23:38:34 2018 Decimal to hexatrigesimal calculator. convert decimal number to base 36 encoding; use of letters with digits. @author: susan """ def dec_to_base36(dec): """ converts decimal dec to base36 number. returns ------- sign+result """ chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' sign = '-' if dec < 0 else '' dec = abs(dec) result = '' while dec > 0: dec, remainder = divmod(dec, 36) result = chars[remainder]+result return sign+result dec = int(input("please enter a Decimal number, e.g. 683248722 :> ")) A = dec_to_base36(dec) print(A)
true
58a9223e31c487b45859dd346238ee84bb2f61c8
ao-kamal/100-days-of-code
/binarytodecimalconverter.py
1,485
4.34375
4
"""Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. """ import sys print( 'This program converts a number from Binary to Decimal or from Decimal to Binary.') def binary_to_decimal(n): print(int(str(n), 2), '\n') def decimal_to_binary(n): print(format(int(n), 'b'), '\n') def convert_again(): prompt = input('Run the program again? (Y/N)\n') if prompt == 'Y': converter() elif prompt == 'N': print('Bye!') sys.exit() else: print("You typed '{0}'.'.format{0}\n") convert_again() def converter(): print('-------------------------------------------\n') choice = input( "To convert from Binary to Decimal, type 'b'.\nTo convert from Decimal to Binary, type 'd'.\n") if choice == 'b': print('---------------------------------------') print('Converting from Binary to Decimal...\n') number = input('Enter the number you want to convert: \n') binary_to_decimal(number) convert_again() elif choice == 'd': print('---------------------------------------') print('Converting from Binary to Decimal...\n') number = input('Enter the number you want to convert: \n') decimal_to_binary(number) convert_again() else: print("You typed '{0}'.".format(choice)) converter() print('\n') converter()
true
c296dab78893f00978039d1a8edee17c8d6d6b3d
lillyfae/cse210-tc05
/puzzle.py
1,812
4.125
4
import random class Puzzle: '''The purpose of this class is to randomly select a word from the word list. Sterotyope: Game display Attributes: word_list (list): a list of words for the puzzle to choose from chosen_word (string): a random word from the word list create_spaces (list of strings): a list of characters that will initially contain spaces and be filled in with player guesses ''' def __init__(self): '''Class constructor. Declares and initializes instance attributes. Args: self (Puzzle): An instance of Puzzle. ''' self.word_list = ["teach","applied","remain","back","raise","pleasant" "organization","plenty","continued","all","seldom","store" "refer","toy","stick","by","shine","field" "load","forth","well","mine","catch","complex" "useful","camera","teacher","sit","spin","wind" "drop","coal","every","friend","throw","wool" "daughter","bound","sight","ordinary","inch","pan"] self.chosen_word = self.random_word() self.create_spaces() def random_word(self): '''Gets a random word from the word list. Args: self (Puzzle): An instance of Puzzle. Returns: the word ''' return random.choice(self.word_list) def create_spaces(self): '''Creates the list of spaces Args: self (Puzzle) ''' self.spaces = [] for i in range(len(self.chosen_word)): self.spaces.append('_') def print_spaces(self): '''Prints out the spaces Args: self (Puzzle) ''' for ch in self.spaces: print(ch + " ", end='') print('\n')
true
e105386bcb9851004f3243f42f385ebc39bac8b7
KAOSAIN-AKBAR/Python-Walkthrough
/casting_Python.py
404
4.25
4
x = 7 # print the value in float print(float(x)) # print the value in string format print(str(x)) # print the value in boolean format print(bool(x)) # *** in BOOLEAN data type, anything apart from 0 is TRUE. Only 0 is considered as FALSE *** # print(bool(-2)) print(bool(0)) # type casting string to integer print(int("34")) # print(int("string")) ----> would produce error ; please donot try this
true
f64eb90364c4acd68aac163e8f76c04c86479393
KAOSAIN-AKBAR/Python-Walkthrough
/calendar_Python.py
831
4.40625
4
import calendar import time # printing header of the week, starting from Monday print(calendar.weekheader(9) + "\n") # printing calendar for the a particular month of a year along with spacing between each day print(calendar.month(2020, 4) + "\n") # printing a particular month in 2-D array mode print(calendar.monthcalendar(2020, 4)) print() # printing calendar for the entire year print(calendar.calendar(2020)) print() # printing a particular day of the week in a month in terms of integer print(calendar.weekday(2020, 4, 12)) # answer is 6, because according to python 6 is Sunday print() # finding whether a year is leap year or not print(calendar.isleap(2020)) print() # finding leap days within specific years, the year you put at the end is exclusive, 2000 and 2004 is leap year. print(calendar.leapdays(2000,2005))
true
3ed6e13c885c7e666fd318e32e3b20278581df18
kaiyaprovost/algobio_scripts_python
/windChill.py
1,076
4.1875
4
import random import math def welcome(): print("This program computes wind chill for temps 20 to -25 degF") print("in intervals of 5, and for winds 5 to 50mph in intervals of 5") def computeWindChill(temp,wind): ## input the formula, replacing T with temp and W with wind wchill = 35.74 + 0.6215*temp - 35.75*(wind**0.16) + 0.4275*temp*(wind**0.16) return(wchill) def main(): welcome() #Print a message that explains what your program does #Print table headings: for temp in range(20, -25, -5): print "\t",str(temp), print #Print table: for wind in range(5,55,5): #For wind speeds between 5 and 50 mph print wind,"\t", #Print row label for temp in range(20, -25, -5): #For temperatures between 20 and -20 degrees wchill = computeWindChill(temp, wind) print wchill,"\t", #Print the wind chill, separated by tabs print #Start a new line for each temp main()
true
9de3fd928aecb53938eb1ced384dfb9deeb3a5b9
lzaugg/giphy-streamer
/scroll.py
1,426
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Console Text Scroller ~~~~~~~~~~~~~~~~~~~~~ Scroll a text on the console. Don't forget to play with the modifier arguments! :Copyright: 2007-2008 Jochen Kupperschmidt :Date: 31-Aug-2008 :License: MIT_ .. _MIT: http://www.opensource.org/licenses/mit-license.php """ from itertools import cycle from sys import stdout from time import sleep def stepper(limit, step_size, loop, backward, bounce): """Generate step indices sequence.""" steps = range(0, limit + 1, step_size) if backward: steps.reverse() if bounce: list(steps).extend(reversed(steps)) if loop: steps = cycle(steps) return iter(steps) def display(string): """Instantly write to standard output.""" stdout.write('\r' + string) stdout.flush() def scroll(message, window, backward=False, bounce=True, loop=True, step_size=1, delay=0.1, template='[%s]'): """Scroll a message.""" string = ''.join((' ' * window, message, ' ' * window)) limit = window + len(message) steps = stepper(limit, step_size, loop, backward, bounce) try: for step in steps: display(template % string[step:window + step]) sleep(delay) except KeyboardInterrupt: pass finally: # Clean up. display((' ' * (window + len(template) - 2)) + '\r') if __name__ == '__main__': scroll('Hello Sam!', 20)
true
f8f775245f38f0553c139bf3253c449e7bf851d8
judeinno/CodeInterview
/test/test_Piglatin.py
941
4.15625
4
import unittest from app.Piglatin import PigLatinConverter """ These tests are for the piglatin converter""" class TestConverter(unittest.TestCase): """This test makes sure that once the first letters are not vowels they are moved to the end""" def test_for_none_vowel(self): self.pig = PigLatinConverter(args='jude') result = self.pig.pig_latin() self.assertEqual(result, 'udejay') """This test makes sure that once the first letter is a vowel the word way is added to the end of the word""" def test_for_vowel(self): self.pig = PigLatinConverter(args='andela') self.assertEqual(self.pig.pig_latin(), 'andelaway') """This test makes sure that an integer is not entered""" def test_for_integers(self): self.pig = PigLatinConverter(args= str(55)) self.assertEqual(self.pig.pig_latin(), 'Please enter a word') if __name__ == '__main__': unittest.main()
true
5b2887021b660dfb5bca37a6b395b121759fed0a
Kontetsu/pythonProject
/example24.py
659
4.375
4
import sys total = len(sys.argv) - 1 # because we put 3 args print("Total number of args {}".format(total)) if total > 2: print("Too many arguments") elif total < 2: print("Too less arguments") elif total == 2: print("It's correct") arg1 = int(sys.argv[1]) arg2 = int(sys.argv[2]) if arg1 > arg2: print("Arg 1 is bigger") elif arg1 < arg2: print("Arg 1 is smaller") else: print("Arg 1 and 2 are equal!") # some methods how to check the user input pattern print("string".isalpha()) print("string1".isalnum()) print("string".isdigit()) print("string".startswith('s')) print("string".endswith('g'))
true
1688c93855bda769c0e21a5cbfb463cfe3cc0299
JimVargas5/LC101-Crypto
/caesar.py
798
4.25
4
#Jim Vargas caesar import string from helpers import rotate_character, alphabet_position from sys import argv, exit def encrypt(text, rot): '''Encrypts a text based on a pseudo ord circle caesar style''' NewString = "" for character in text: NewChar = rotate_character(character, rot) NewString = NewString + NewChar return NewString def main(rot): if rot.isdigit(): text = input("Type the message that you would like to encrypt: ") #rot = int(input(Rotate by:)) rot = int(rot) print(encrypt(text, rot)) else: print("You need to enter an integer argument.") exit() if __name__ == '__main__': if len(argv) <=1: print("You need to enter an integer argument.") exit() else: main(argv[1])
true
b211b888702bbb1ebed8b6ee2b21fec7329a7b59
deyoung1028/Python
/to_do_list.py
1,738
4.625
5
#In this assignment you are going to create a TODO app. When the app starts it should present user with the following menu: #Press 1 to add task #Press 2 to delete task (HARD MODE) #Press 3 to view all tasks #Press q to quit #The user should only be allowed to quit when they press 'q'. #Add Task: #Ask the user for the 'title' and 'priority' of the task. Priority can be high, medium and low. #Delete Task: (HARD MODE) #Show user all the tasks along with the index number of each task. User can then enter the index number of the task to delete the task. #View all tasks: #Allow the user to view all the tasks in the following format: #1 - Wash the car - high #2 - Mow the lawn - low #Store each task in a dictionary and use 'title' and 'priority' as keys of the dictionary. #Store each dictionary inside an array. Array will represent list of tasks. #** HINT ** #tasks = [] # global array #input("Enter your option") tasks = [] #global array def view_tasks(): print(tasks) while True: print("Please make a choice from the following menu:") print("1 - Add Task") print("2 - Delete Task") print("3 - View all tasks ") print("q to quit") choice = input("Enter Choice:") if choice == "q": break if choice == "1": title = input("Please enter a task title:") priority = input("Please enter priority : high, medium or low - ") task = {"title": title, "priority": priority} tasks.append(task) if choice == "2": view_tasks() del_task = int(input("Chose a task to delete:" )) del tasks[del_task - 1] view_tasks() if choice == "3": view_tasks() print(tasks)
true
e41796d392658024498869143c8b8879a7916968
deyoung1028/Python
/dictionary.py
487
4.21875
4
#Take inputs for firstname and lastname and then create a dictionary with your first and last name. #Finally, print out the contents of the dictionary on the screen in the following format. users=[] while True: first = input("Enter first name:") last = input("Enter last name:") user = {"first" : first, "last": last} users.append(user) choice = input("Enter q to quit or any key to continue:") if choice == "q": break print(users)
true
74dee8921f4db66c458a0c53cd08cb54a2d1ba63
KritikRawal/Lab_Exercise-all
/4.l.2.py
322
4.21875
4
""" Write a Python program to multiplies all the items in a list""" total=1 list1 = [11, 5, 17, 18, 23] # Iterate each element in list # and add them in variable total for ele in range(0, len(list1)): total = total * list1[ele] # printing total value print("product of all elements in given list: ", total)
true
d71d9e8c02f405e55e493d1955451c12d50f7b9b
KritikRawal/Lab_Exercise-all
/3.11.py
220
4.28125
4
""" find the factorial of a number using functions""" def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) num = int(input('enter the number')) print(factorial)
true
53b8278af9a4a98b4de820d91054d80e9f1247f4
KritikRawal/Lab_Exercise-all
/3.8.py
393
4.125
4
"""takes a number as a parameter and check the number is prime or not""" def is_prime(num): for i in range(2, num): if num % i == 0: return False return True print('Start') val = int(input('Enter the number to check prime:\n')) ans = is_prime(val) if ans: print(val, 'Is a prime number:') else: print(val, 'Is not a prime number:')
true
ae6ae8cfe7e655b1ffc9617eb8d87480a97e8f27
KritikRawal/Lab_Exercise-all
/4.2.py
635
4.4375
4
""". Write a Python program to convert temperatures to and from celsius, fahrenheit. C = (5/9) * (F - 32)""" print("Choose the conversion: ") print(" [c] for celsius to fahrenheit") print(" [f] for fahrenheit to celsius") ans = input() conversion = 0 cs = "" if ans == "c": ans = "Celsius" elif ans == "f": ans = "Fahrenheit" print(f"Enter your temperature in {ans}") temp = int(input()) if ans == "Celsius": conversion = temp * (9 / 5) + 32 cs = "Fahrenheit" elif ans == "Fahrenheit": conversion = (5 / 9) * (temp - 32) cs = "Celsius" print(f"{temp} ({ans}) is {conv} ({cs})") print()
true
b9e75d0b9d9605330c54818d1dd643cc764032cf
KritikRawal/Lab_Exercise-all
/2.5.py
277
4.21875
4
"""For given integer x, print ‘True’ if it is positive, print ‘False’ if it is negative and print ‘zero’ if it is 0""" x = int(input("Enter a number: ")) if x > 0: print('positive') elif x<0: print('negative') else: print('zero')
true
99e3a484814475a5ccc0627f5d875507a5213b0c
Mattias-/interview_bootcamp
/python/fizzbuzz.py
520
4.15625
4
# Using any language you want (even pseudocode), write a program or subroutine # that prints the numbers from 1 to 100, each number on a line, except for every # third number write "fizz", for every fifth number write "buzz", and if a # number is divisible by both 3 and 5 write "fizzbuzz". def fb(): for i in xrange(1, 100): s = "" if i % 3 == 0: s = "fizz" if i % 5 == 0: s += "buzz" if not s: print i else: print s fb()
true
1aae789149cce977556e11683e898dc039bdb9ad
derek-baker/Random-CS-Stuff
/python/SetCover/Implementation.py
1,542
4.1875
4
# INSPIRED BY: http://www.martinbroadhurst.com/greedy-set-cover-in-python.html # def test_that_subset_elements_contain_universe(universe, elements): # if elements != universe: # return False # return True def compute_set_cover(universe, subsets): # Get distinct set of elements from all subsets elements = set(el for setOfEls in subsets for el in setOfEls) print('ELEMENTS:') print(elements) # if test_that_subset_elements_contain_universe(universe, elements) == False: # return None covered = set() cover = [] # Add subsets with the greatest number of uncovered points # (As a heuristic for finding a solution) while covered != elements: # This will help us to find which subset can cover at the least cost compute_cost = lambda candidate_subset: len(candidate_subset - covered) subset = max(subsets, key = compute_cost) cover.append(subset) print('\nSELECTED SUBSET: ') print(subset) print('COVERED: ') print(covered) # Perform bitwise OR and assigns value to the left operand. covered |= subset return cover def main(): universe = set(range(1, 11)) subsets = [ set([1, 2, 3, 8, 9, 10]), set([1, 2, 3, 4, 5]), set([4, 5, 7]), set([5, 6, 7]), set([6, 7, 8, 9, 10]), ] cover = compute_set_cover(universe, subsets) print('\nLOW-COST SET COVER:') print(cover) if __name__ == '__main__': main()
true
e74add4e61a90087bb085b51a8734a718fd554f7
sador23/cc_assignment
/helloworld.py
602
4.28125
4
'''The program asks for a string input, and welcomes the person, or welcomes the world if nothing was given.''' def inputname(): '''Keeps asking until a string is inputted''' while True: try: name=input("Please enter your name!") int(name) print("This is not a string! Please enter a string") except ValueError: return name def greeting(name): '''Greets the person, depending on the name''' if not name: print("Hello World!") else: print("Hello " + str(name) + "!") greeting(inputname())
true
2abe2c2de6d54d9a44b3abb3fc03c88997840e61
maria1226/Basics_Python
/aquarium.py
801
4.53125
5
# For his birthday, Lubomir received an aquarium in the shape of a parallelepiped. You have to calculate how much # liters of water will collect the aquarium if it is known that a certain percentage of its capacity is occupied by sand, # plants, heater and pump. # Its dimensions - length, width and height in centimeters will be entered by the console. # One liter of water is equal to one cubic decimeter. # Write a program that calculates the liters of water needed to fill the aquarium. length_in_cm=int(input()) width_in_cm=int(input()) height_in_cm=int(input()) percentage_occupied_volume=float(input()) volume_aquarium=length_in_cm*width_in_cm*height_in_cm total_liters=volume_aquarium*0.001 percentage=percentage_occupied_volume*0.01 liters=total_liters*(1-percentage) print(f'{liters:.3f}')
true
56a13bb22f6d53ef4e149941d2d4119cc8d4edd3
lagzda/Exercises
/PythonEx/intersection.py
450
4.125
4
def intersection(arr1, arr2): #This is so we always use the smallest array if len(arr1) > len(arr2): arr1, arr2 = arr2, arr1 #Initialise the intersection holder inter = [] for i in arr1: #If it is an intersection and avoid duplicates if i in arr2 and i not in inter: inter.append(i) return inter #Test arr1 = [54,26,93,17,77,31,44,55,20] arr2 = [54, 93, 93, 7] print intersection(arr1, arr2)
true
2c9da507053689dee6cc34724324521983ea0c8c
miroslavgasparek/python_intro
/numpy_practice.py
1,834
4.125
4
# 21 February 2018 Miroslav Gasparek # Practice with NumPy import numpy as np # Practice 1 # Generate array of 0 to 10 my_ar1 = np.arange(0,11,dtype='float') print(my_ar1) my_ar2 = np.linspace(0,10,11,dtype='float') print(my_ar2) # Practice 2 # Load in data xa_high = np.loadtxt('data/xa_high_food.csv',comments='#') xa_low = np.loadtxt('data/xa_low_food.csv',comments='#') def xa_to_diameter(xa): """ Convert an array of cross-sectional areas to diameters with commensurate units.""" # Compute diameter from area diameter = np.sqrt((4*xa)/np.pi) return diameter # Practice 3 # Create matrix A A = np.array([[6.7, 1.3, 0.6, 0.7], [0.1, 5.5, 0.4, 2.4], [1.1, 0.8, 4.5, 1.7], [0.0, 1.5, 3.4, 7.5]]) # Create vector b b = np.array([1.1, 2.3, 3.3, 3.9]) # 1. Print row 1 (remember, indexing starts at zero) of A. print(A[0,:]) # 2. Print columns 1 and 3 of A. print(A[:,(0,2)]) # 3. Print the values of every entry in A that is greater than 2. print(A[A > 2]) # 4. Print the diagonal of A. using the np.diag() function. print(np.diag(A)) # 1. First, we'll solve the linear system A⋅x=bA⋅x=b . # Try it out: use np.linalg.solve(). # Store your answer in the Numpy array x. x = np.linalg.solve(A,b) print('Solution of A*x = b is x = ',x) # 2. Now do np.dot(A, x) to verify that A⋅x=bA⋅x=b . b1 = np.dot(A,x) print(np.isclose(b1,b)) # 3. Use np.transpose() to compute the transpose of A. AT = np.transpose(A) print('Transpose of A is AT = \n',AT) # 4. Use np.linalg.inv() to compute the inverse of A. AInv = np.linalg.inv(A) print('Inverse of A is AInv = \n',AInv) # 1. See what happens when you do B = np.ravel(A). B = np.ravel(A) print(B) # 2. Look of the documentation for np.reshape(). Then, reshape B to make it look like A again. C = B.reshape((4,4)) print(C)
true
877150ed0d4fb9185a633ee923daee0ba3d745e4
nmessa/Raspberry-Pi
/Programming/SimplePython/name4.py
550
4.125
4
# iteration (looping) with selection (conditions) again = True while again: name = raw_input("What is your name? ") print "Hello", name age = int(raw_input("How old are you? ")) newage = age + 1 print "Next year you will be ", newage if age>=5 and age<19: print "You are still in school" elif age < 5: print "You have not started school yet?" elif age > 20: print "You are probably out of high school now?" answer = raw_input("Again (y/n)?") if answer != 'y': again = False
true
cd0c13a1013724e1ec7920a706ee52e2aa0e9a96
Teslothorcha/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
411
4.15625
4
#!/usr/bin/python3 """ This function will add two values casted values if necessary (int/float) and return the addition """ def add_integer(a, b=98): """ check if args are ints to add'em' """ if not isinstance(a, (int, float)): raise TypeError("a must be an integer") if not isinstance(b, (int, float)): raise TypeError("b must be an integer") return (int(a) + int(b))
true
5e6e2e5e3d29dc46c9e5a9e7bc49a5172fbbb3cb
wbsth/mooc-da
/part01-e07_areas_of_shapes/src/areas_of_shapes.py
935
4.1875
4
#!/usr/bin/env python3 import math def main(): while True: shape = input('Choose a shape (triangle, rectangle, circle): ') if shape == '': break else: if shape == 'rectangle': r_width = int(input("Give width of the rectangle: ")) r_height = int(input("Give height of the rectangle: ")) print(f"The area is {r_height * r_width}") elif shape == 'triangle': t_base = int(input("Give base of the triangle: ")) t_height = int(input("Give height of the triangle: ")) print(f"The area is {0.5*t_base*t_height}") elif shape == 'circle': c_radius = int(input("Give radius of the circle: ")) print(f"The area is {math.pi * c_radius ** 2}") else: print('Unknown shape!') if __name__ == "__main__": main()
true
d3e64c5bfe6b5508c458a2bc76e40fa6ef0f4019
nasrinsultana014/HackerRank-Python-Problems
/Solutions/Problem14.py
536
4.21875
4
def swap_case(s): characters = list(s) convertedCharacters = [] convertedStr = "" for i in range(len(characters)): if characters[i].isupper(): convertedCharacters.append(characters[i].lower()) elif characters[i].islower(): convertedCharacters.append(characters[i].upper()) else: convertedCharacters.append(characters[i]) return convertedStr.join(convertedCharacters) if __name__ == '__main__': s = input() result = swap_case(s) print(result)
true
0f28ba6d84069ffabf1a733ca4f4980c28674290
ngoc123321/nguyentuanngoc-c4e-gen30
/session2/baiq.py
480
4.15625
4
weight = float(input('Your weight in kilos: ')) # <=== 79 height = float(input('Your height in meters: ')) # <=== 1.75 BMI = weight / height ** 2 BMI = round(BMI, 1) if BMI < 16: result = 'Severely underweight.' elif 16 < BMI <= 18.5: result = 'Underweight.' elif 18.5 < BMI <= 25: result = 'Normal.' elif 25 < BMI <= 30: result = 'Overweight.' else: result = 'obese.' print('Your BMI is', BMI, end = ', ') print('that is', result) # ===> Your BMI is 25.8, that is overweight.
true
d63f3014189730c8afbe7f91add852ef729e22f0
inwk6312fall2019/dss-Tarang97
/Chapter12-Tuples/Ex12.2.py
1,579
4.21875
4
fin = open('words.txt') # is_anagram() will take a single text from 'words.txt', sorts it and lower the cases and # append the original word in the list which will be the default value of sorted_dict() values; # but, the sorted_word will be in sorted_dict() dictionary along with its value. def is_anagram(text): sorted_dict = dict() for line in text: original_word = line.strip() sorting_word = ''.join(sorted(list(original_word.lower()))) sorted_word = sorting_word sorted_dict.setdefault(sorted_word, []).append(original_word) anagrams = [] # This for loop will take key and value from sorted_dict() using dict.items(). # the length of no. of words spelled with those letters will be counted and will be stored in 'l'. # If length > 1, then (count of words formed, key(original word) , value (The words created with letters)) # will append in anagrams[] list. for k,v in sorted_dict.items(): l = len(v) if l > 1: anagrams.append((l,k,v)) return anagrams def longest_list_anagrams(text): anagrams = is_anagram(text) longest_list_anagrams = [] for l,k,v in reversed(sorted(anagrams)): longest_list_anagrams.append((l,k,v)) return longest_list_anagrams longest_list_anagrams = longest_list_anagrams(fin) print(longest_list_anagrams[:5]) # longest_list_anagrams() will take the anagrams from is_anagram() and gets the anagrams[] list # then it will get reversed and sorted and then it will append in longest_list_anagrams[].
true
c65858019b12bc00cc9733a9fa2de5fd5dda8d14
asadali08/asadali08
/Dictionaries.py
1,662
4.375
4
# Chapter 9. Dictionaries # Dictionary is like a set of items with any label without any organization purse = dict()# Right now, purse is an empty variable of dictionary category purse['money'] = 12 purse['candy'] = 3 purse['tissues'] = 75 print(purse) print(purse['candy']) purse['money'] = purse['money'] + 8 print(purse) lst = list() lst.append(21) lst.append(3) print(lst) print(lst[1]) abc = dict() abc['age'] = 21 abc['course'] = 146 print(abc) abc['age'] = 26 print(abc) # You can make empty dictionary using curly brackets/braces print('ccc' in abc) # When we see a new entry, we need to add that new entry in a dictionary, we just simply add 1 in the dictionary under that entry counts = dict() names = ['ali', 'asad','ashraf','ali','asad'] for name in names: if name not in counts: counts[name] = 1 else: counts[name] = counts[name] + 1 print(counts) if name in counts: x = counts[name] else: counts.get(name, 0) print(counts) # Dictionary and Files counts = dict() print('Enter a line of text: ') line = input('') words = line.split() print('Words:',words) print('Counting.........') for word in words: counts[word] = counts.get(word, 0) + 1 print('Counts',counts) # The example above shows how many words are there in a sentence and how many times each word has been repeated in a sentence length = {'ali': 1, 'andrew': 20, 'jayaram': 32} for key in length: print(key, length[key]) print(length.keys()) print(length.values()) for abc,ghi in length.items(): print(abc,ghi) stuff = dict() print(stuff.get('candy', -1))
true
f8327a56682bd0b9e4057defb9b016fd0b56afdd
karagdon/pypy
/48.py
671
4.1875
4
# lexicon = allwoed owrds list stuff = raw_input('> ') words = stuff.split() print "A TUPLE IS SIMPLY A LIST YOU CANT MODIFY" # lexicon tuples first_word = ('verb', 'go') second_word = ('direction', 'north') third_word = ('direction', 'west') sentence = [first_word, second_word, third_word] def convert_numbers(s): try: return int(s): except ValueError: return None print """ Create one small part of the test I give you \n Make sure it runs and fails so you know a test is actually confirming a feature works. \n Go to your source file lexicon.py and write the code that makes this test pass \n Repeat until you have implemented everything in the test """
true
80a5137b9ab2d2ec77805ef71c2513d8fcdf81a0
karagdon/pypy
/Python_codeAcademy/binary_rep.py
1,384
4.625
5
#bitwise represention #Base 2: print bin(1) #base8 print hex(7) #base 16 print oct(11) #BITWISE OPERATORS# # AND FUNCTION, A&B # 0b1110 # 0b0101 # 0b0100 print "AND FUNCTION, A&B" print "======================\n" print "bin(0b1110 & 0b101)" print "= ",bin(0b1110&0b101) # THIS OR THAT, A|B #The bitwise OR (|) operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of either number are 1. # 0b1110 # 0b0101 # ====== # 0b1111 print "OR FUNCTION, A|B" print "======================\n" print "bin(0b1110|0b0101)" print "= ",bin(0b1110|0b0101) # XOR FUNCTION, A^B #XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number where the bits of that number are turned on if either of the corresponding bits of the two numbers are 1, but not both. # 1 1 1 0 # 0 1 0 1 # = = = = # 1 0 1 1 thus 0b1011 should appear print "XOR FUNCTION" print "======================\n" print "bin(0b1110 ^ 0b101)" print "=", bin(0b1110 ^ 0b101) # XOR FUNCTION, ~A #The bitwise NOT operator (~) just flips all of the bits in a single number.This is equivalent to adding one to the number and then making it negative. print "NOT FUNCTION, ~A" print "======================\n" print "~1 =", ~1 print "~2 =", ~2 print "~3 =", ~3 print "~42 =", ~42 print "~123 =", ~123
true
729099b198e045ce3cfe0904f325b62ce3e3dc5e
karagdon/pypy
/diveintopython/707.py
579
4.28125
4
### Regex Summary # ^ matches # $ matches the end of a string # \b matches a word boundary # \d matches any numeric digit # \D matches any non-numeric character # x? matches an optional x character (in other words, it matches an x zero or one times) # x* matches x zero or more times # x+ matches x one or more times # x{n,m} matches an x character atleast n times, but not more than m times # (a|b|c) matches either a or b or c # (x) in general is a remembered group. You can get the value of what matched by using the groups() method of the object returned by re.search
true
bd00c3566cf764ca82bba1a4af1090581a84d50f
f1uk3r/Daily-Programmer
/Problem-3/dp3-caeser-cipher.py
715
4.1875
4
def translateMessage(do, message, key): if do == "d": key = -key transMessage = "" for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord("Z"): num -= 26 elif num < ord("A"): num += 26 if symbol.islower(): if num > ord("z"): num -= 26 elif num < ord("a"): num += 26 transMessage += chr(num) else: transMessage += symbol return transMessage do = input("Do you want to (e)ncrypt or (d)ecrypt? ") message = input("Type your message : ") key = int(input("Enter a key number between -26 and 26: ")) translated = translateMessage(do, message, key) print("Your translated message is : " + translated)
true
e2b0a7d7bc76ef3739eace98f62081e78df24b67
f1uk3r/Daily-Programmer
/Problem-11/Easy/tell-day-from-date.py
540
4.5
4
# python 3 # tell-day-from-date.py #give arguments for date returns day of week # The program should take three arguments. The first will be a day, # the second will be month, and the third will be year. Then, # your program should compute the day of the week that date will fall on. import datetime import calendar import sys def get_day(day, month, year): date = datetime.datetime(int(year), int(month), int(day)) print(calendar.day_name[date.weekday()]) if __name__ == '__main__': get_day(sys.argv[1], sys.argv[2], sys.argv[3])
true
8d888e53b71da82ae029c0ffc4563edc84b8283d
EdwardMoseley/HackerRank
/Python/INTRO Find The Second Largest Number.py
661
4.15625
4
#!/bin/python3 import sys """ https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list Find the second largest number in a list """ #Pull the first integer-- we don't need it junk = input() def secondLargest(arg): dat = [] for line in arg: dat.append(line) dat = dat[0].split(' ') i = 0 while i < len(dat): dat[i] = int(dat[i]) i += 1 dat.sort() #Find the first integer that is not the maximum integer while decrementing for j in reversed(range(len(dat))): if dat[j] is not max(dat): return dat[j] print(secondLargest(sys.stdin))
true
bbe8b6100246aa2f58fca457929827a0897e9be5
arickels11/Module4Topic3
/topic_3_main/main_calc.py
1,637
4.15625
4
"""CIS 189 Author: Alex Rickels Module 4 Topic 3 Assignment""" # You may apply one $5 or $10 cash off per order. # The second is percent discount coupons for 10%, 15%, or 20% off. # If you have cash-off coupons, those must be applied first, then apply the percent discount coupons on the pre-tax # Then you add tax at 6% and shipping according to these guidelines: # # up to $10 dollars, shipping is $5.95 # $10 and up to $30 dollars, shipping is $7.95 # $30 and up to $50 dollars, shipping is $11.95 # Shipping is free for $50 and over def calculate_order(price, cash_coupon, percent_coupon): if price < 10.00: if (price - cash_coupon)*(1 - (percent_coupon / 100)) < 0: return 5.95 # if coupons get price to under zero, customer only pays shipping costs else: return round((((price - cash_coupon)*(1 - (percent_coupon / 100)))*1.06) + 5.95, 2) elif 10.00 <= price < 30.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 7.95, 2) elif 30.00 <= price < 50.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06) + 11.95, 2) elif price >= 50.00: return round((((price - cash_coupon) * (1 - (percent_coupon / 100))) * 1.06), 2) else: print("Please correct your input") if __name__ == '__main__': initial_price = float(input("What is the price?")) cash = float(input("What is the cash discount, $5 or $10?")) percent = float(input("What is the percent discount, 10%, 15%, or 20%?")) final_price = float(calculate_order(initial_price, cash, percent)) print(final_price)
true
27006f8290968a5d89a8d0d25355538212718075
Manny-Ventura/FFC-Beginner-Python-Projects
/madlibs.py
1,733
4.1875
4
# string concatenation (akka how to put strings together) # # suppose we want to create a string that says "subscribe to ____ " # youtuber = "Manny Ventura" # some string variable # # a few ways... # print("Subscribe to " + youtuber) # print("Subscribe to {}".format(youtuber)) # print(f"subscribe to {youtuber}") adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous Person: ") noun1 = input("Noun: ") noun2 = input("Noun: ") place = input("Make a name for a place: ") number = input("Number : ") madlib = f"My time on earth is absolutely {adj}! All i want to do is {verb1} \n\ and {verb2} because I miss my home planet. Back home in the land of {place}, \n\ we had {noun1}'s running around all the time. Not only that, but some {noun2}'s \n\ even got along with the them! It was a crazy time, and I want to go back... \n\ I just... I miss my kids man. \n\ I wasn't there for them like I should have. Heck, LOOK WHERE I AM NOW. \n\ Its a scary feeling not being sure if I ever will be a good dad man, or ever was. \n\ Its not like wanting to be is enough. And its not fair to try and explain \n\ The hardships I go through to be there for them. There kids you know? \n\ Im supposed to not make it seem so scary, but what's scary is that \n\ They probably learned that life is scary and sometimes those that \n\ want to be there for them wont. Tough as nails, but it breaks my heart, \n\ cause its not fair to them. They should not have to tough BECAUSE of me. \n\ I hope at least they know I do love them, and that I am just a bad father \n\ I owe them at least that. Love all {number} of ya, \n\ \n\ Pops" print(madlib)
true
de25e31fa817bc6347566c021edc50f1868de959
gohjunyi/RegEx
/google_ex.py
1,167
4.125
4
import re string = 'an example word:cat!!' match = re.search(r'word:\w\w\w', string) # If-statement after search() tests if it succeeded if match: print('found', match.group()) # 'found word:cat') else: print('did not find') # i+ = one or more i's, as many as possible. match = re.search(r'pi+', 'piiig') # found, match.group() == "piii" # Finds the first/leftmost solution, and within it drives the + # as far as possible (aka 'leftmost and largest'). # In this example, note that it does not get to the second set of i's. match = re.search(r'i+', 'piigiiii') # found, match.group() == "ii" # \s* = zero or more whitespace chars # Here look for 3 digits, possibly separated by whitespace. match = re.search(r'\d\s*\d\s*\d', 'xx1 2 3xx') # found, match.group() == "1 2 3" match = re.search(r'\d\s*\d\s*\d', 'xx12 3xx') # found, match.group() == "12 3" match = re.search(r'\d\s*\d\s*\d', 'xx123xx') # found, match.group() == "123" # ^ = matches the start of string, so this fails: match = re.search(r'^b\w+', 'foobar') # not found, match == None # but without the ^ it succeeds: match = re.search(r'b\w+', 'foobar') # found, match.group() == "bar"
true
f01d7fab6569e318399eee144b7310d39433d061
ammalik221/Python-Data-Structures
/Collections/Queues_using_queue_module.py
411
4.1875
4
""" Queues Implementation in Python 3.0 using deque module. For implementations from scratch, check out the other files in this repository. """ from collections import deque # test cases # make a deque q = deque() # add elements q.append(20) q.append(30) q.append(40) # output is - 10 20 30 40 print(q) # remove elements from queue # output is 10 and 20 respectively print(q.popleft()) print(q.popleft())
true
73c2bcf27da231afe7d9af4425683c006799e7a9
razzanamani/pythonCalculator
/calculator.py
1,515
4.375
4
#!usr/bin/python #Interpreter: Python3 #Program to create a functioning calculator def welcome(): print('Welcome to the Calculator.') def again(): again_input = input(''' Do you want to calculate again? Press Y for YES and N for NO ''') # if user types Y, run the calculate() function if again_input == 'Y': calculate() #if user types N, say bye elif again_input == 'N': print('Thank You for using Calculator') #if user types another key, run the same funtion again else: again() def calculate(): operation = input(''' Please type the math operation you would like to complete: + for addition - for substraction * for multiplication / for division % for modulo ''') number_1 = int(input('Enter the first number :')) number_2 = int(input('Enter the second number :')) #Addition if operation == '+': print('{} + {} = '.format(number_1,number_2)) print(number_1 + number_2) #Substraction elif operation == '-': print('{} - {} = '.format(number_1,number_2)) print(number_1 - number_2) #Multiplication elif operation == '*': print('{} * {} ='.format(number_1,number_2)) print(number_1 * number_2) #Division elif operation == '/': print('{} / {} = '.format(number_1,number_2)) print(number_1/number_2) #else operation else: print('You have not typed a valid operator,please run the program again.') #calling the again() function to repeat again() #calling the welcome funtion welcome() #calling the calculator function outside the function calculate()
true
ee1e7bff3095782f4886eeefc0558543c091ddc6
williamsyb/mycookbook
/thread_prac/different_way_kill_thread/de04.py
1,153
4.59375
5
# Python program killing # a thread using multiprocessing # module """ Though the interface of the two modules is similar, the two modules have very different implementations. All the threads share global variables, whereas processes are completely separate from each other. Hence, killing processes is much safer as compared to killing threads. The Process class is provided a method, terminate(), to kill a process. Now, getting back to the initial problem. Suppose in the above code, we want to kill all the processes after 0.03s have passed. This functionality is achieved using the multiprocessing module in the following code. """ import multiprocessing import time def func(number): for i in range(1, 10): time.sleep(0.01) print('Processing ' + str(number) + ': prints ' + str(number * i)) # list of all processes, so that they can be killed afterwards all_processes = [] for i in range(0, 3): process = multiprocessing.Process(target=func, args=(i,)) process.start() all_processes.append(process) # kill all processes after 0.03s time.sleep(0.03) for process in all_processes: process.terminate()
true
353a3606af9aa9b5c5065edaa2e35d88f9e8ec5f
Imsurajkr/Cod001
/challenge2.py
662
4.1875
4
#!/usr/bin/python3 import random highestNumber = 10 answer = random.randint(1, highestNumber) print("Enter the number betweeen 1 and {}".format(highestNumber)) guess = 0 #initialize to any number outside of the range while guess != answer: guess = int(input()) if guess > answer: print("please Select Lower Number") # guess = int(input()) elif guess < answer: print("Please Select Higher Number ") # guess = int(input()) elif guess == 0: print("Thanks For playing") break else: print("You guessed it Great") break else: print("Great You successfully Guessed on 1st attemp")
true
6ca787eac5185c966f539079a8d2b890d9dc6447
OldPanda/The-Analysis-of-Algorithms-Code
/Chapter_2/2.4.py
897
4.15625
4
""" Random Hashing: Data structure: a key array X with entries x_i for 0 <= i <= N-1 and a corresponding record array R. Initial conditions: the number of entries, k, is zero and each key location, x_i, contains the value empty, a special value that is not the value of any key. Input: a query, q. Output: a location i such that q = x_i if there is such an i (i.e., q is in the table) or i such that x_i contains empty and the hash algorithm would look in location x_i when looking for q. """ import numpy as np X = np.random.randint(10, size=10) R = np.random.randint(100, size=10) # A simple function def f(h, q): return (h*2 + q)%10 def random_hashing(q): h = 0 while True: h = h + 1 i = f(h, q) if X[i] == 0: return False elif X[i] == q: return True if __name__ == "__main__": print X print "Query 5: ", random_hashing(5) print "Query 6: ", random_hashing(6)
true
2ca5b9fd677edf64a50c6687803c91b721bee140
basakmugdha/Python-Workout
/1. Numeric Types/Excercise 1 (Number Guessing Game)/Ex1c_word_GG.py
848
4.375
4
#Excercise 1 beyond 3: Word Guessing Game from random_word import RandomWords def guessing_game(): '''returns a random integer between 1 and 100''' r = RandomWords() return r.get_random_word() if __name__ == '__main__': print('Hmmmm.... let me pick a word') word = guessing_game() guess = input(f"Guess the word ({len(word)} characters) : ") # only 6 guesses so the game is less tedious #the for loop can be replaced with 'while True:' for the original trap style game for _ in range(5): if guess>word: print("You're far ahead in the dictionary") elif guess == word: print("YOU GUESSED IT!") break else: print("You're far behind in the dictionary") word = input('Guess again :') print(word+' is the word!')
true
c26c3fa52692454bd47cfab92253715ed461f4f2
DiegoRmsR/holbertonschool-higher_level_programming
/0x03-python-data_structures/3-print_reversed_list_integer.py
223
4.28125
4
#!/usr/bin/python3 def print_reversed_list_integer(my_list=[]): if not my_list: pass else: for list_reverse in reversed(my_list): str = "{:d}" print(str.format(list_reverse))
true
8ba63fdd070ef490570285c17d8669b8d8ffb5b0
lukelu389/programming-class
/python_demo_programs/2020/prime_number.py
273
4.375
4
# write a python program to check if a number is prime or not number = int(input('enter a number:')) n = 1 counter = 0 while n <= number: if number % n == 0: counter += 1 n += 1 if counter > 2: print('not prime number') else: print('prime number')
true
3404c6cc7af2350bf12592921226a9f4a87da618
lukelu389/programming-class
/python_demo_programs/2021/example_20210319.py
1,529
4.1875
4
# s = 'abcdefgh' # print(s[0:2]) # print(s[:2]) # implicitly start at 0 # print(s[3:]) # implicitly end at the end # # # slice from index 4 to the end # print(s[4:]) # to achieve the conditional, need to use if keyword # a = 6 # b = 5 # if b > a: # print('inside if statement') # print('b is bigger than a') # # exit the if # print('program finish') # a = a + 1 # input = -9 # if input > 0: # print('positive') # else: # print('not positive') # a = 2 # b = 3 # using if, else statement, print the bigger number # if a > b: # print(a) # else: # print(b) # a = 3 # b = 2 # # given two variables, print the positive variables # if a > 0 # print(a) # # if b > 0: # print(b) # given a variable, print the variable if it is the even number # hint: use % operator to find the even or odd # a = 3 # if a % 2 == 0: # print("a is an even number") # else: # print("a is an odd number") # number = 0 # if number > 0: # print("positive") # elif number < 0: # print("negative") # else: # print("zero") # because input() takes all value as string, need convert to int # by using int() # a = int(input("enter the value for a:")) # b = int(input("enter the value for b:")) # # if a > b: # print("a is bigger") # elif a < b: # print("b is bigger") # else: # print("a is equal to b") a = int(input("enter a value for a: ")) if a > 0: print("a is positive") if a % 2 == 0: print("a is even") else: print("a is odd") else: print("a is negative")
true
1d4bac21899ddd993ad41cdf80a0c2ad350b8104
lukelu389/programming-class
/python_demo_programs/2021/example_20210815.py
1,644
4.1875
4
# class Person: # def __init__(self, name): # self.name = name # def method1(self): # return 'hello' # p1 = Person('jerry') # print(p1.name) # Person.method1() # class = variables + methods # variable: static variable vs instance variable # method: static method vs instance method # class is customized data structure # class is the blueprint of object, we use class to create object class Person: # constructor def __init__(self, name, age): # instance variable is created in the constructor self.name = name self.age = age # instance method def say_hi(self): return 'hi' p1 = Person('jerry', 10) p2 = Person('tom', 20) print(p1.name) print(p1.age) print(p2.name) print(p2.age) p1.say_hi() p2.say_hi() class Student: def __init__(self, student_name, student_id): self.student_name = student_name self.student_id = student_id def get_info(self): return self.student_name + ":" + str(self.student_id) def __str__(self): return self.student_name peter = Student('peter', 1) print(peter.get_info()) print(peter) class Grade: def __init__(self): self.grades = [] ''' Give two dictionaries, create thrid dictionary with the unique key and value from both dictionaries d1 = {'a': 1, 'b': 3, 'c': 2} d2 = {'a': 2, 'b': 2, 'd': 3} d3 = {'c': 2, 'd': 3} ''' d1 = {'a': 1, 'b': 3, 'c': 2} d2 = {'a': 2, 'b': 2, 'd': 3} d3 = {} for key1, value1 in d1.items(): if key1 not in d2: d3[key1] = value1 for key2, value2 in d2.items(): if key2 not in d1: d3[key2] = value2 print(d3)
true
6d7f89a6f38bcb3765ff3e6f5a954bfed6b27f3c
lukelu389/programming-class
/python_demo_programs/2020/factorial.py
231
4.15625
4
# use a loop to calculate n*(n-1)*(n-2)*(n-3)*...2*1, # and return the result def factorial(n): result = 1 while n > 0: result = result * n n -= 1 return result print(factorial(5)) print(factorial(3))
true
ea53f0ecbeee4c3c1a35d5a2d2569b8a70cf4ea2
lukelu389/programming-class
/python_demo_programs/2020/example_20201018.py
1,389
4.125
4
# homework # write a python function takes two lists as input, check if one list contains another list # [1, 2, 3] [1, 2] -> true # [1] [1, 2, 3] -> true # [1, 2] [1, 3] -> false def contain(list1, list2): # loop through list1 check if each element in list1 is also in list2 list2_contains_list1 = True for i in list1: if i not in list2: list2_contains_list1 = False # loop through list2 check if each element in list2 is also in list1 list1_contains_list2 = True for i in list2: if i not in list1: list1_contains_list2 = False return list1_contains_list2 or list2_contains_list1 # print(contains([1, 2, 3], [1, 2])) # print(contains([1], [1, 2, 3])) # print(contains([1, 2], [1, 3])) # l = [[1, 2], 3] # print(1 in l) # print([1, 2] in l) # write a python function that takes a list and a int, check if list contains two values that sum is the input int # case1 [1, 2, 3], 4 -> True # case2 [1, 2, 3], 10 -> False # case3 [1, 3, 5], 4 -> True # case4 [4, 2, 1], 5 -> def pair_sum(list, sum): i = 0 while i < len(list): j = i + 1 while j < len(list): if list[i] + list[j] == sum: return True j += 1 i += 1 return False # write a python function that takes a list and a int, check if list contains two values that diff is the input int
true
9e63c534debc5b8bb2adcfd7493ce18e8acd1bf7
lukelu389/programming-class
/python_demo_programs/2020/example_20201025.py
1,532
4.25
4
# # write a python function that takes a list and a int, check if list contains any two values that diff of the two values # # is the input int # # [1, 2, 3] 1 -> true # # [1, 2, 3] 4 -> false # # def find_diff(list, target): # for i in list: # for j in list: # if j - i == target: # return True # # return False # # # l = ["1", "2", "3"] # print(l) # l[0] = 100 # print(l) # # s = 'abc' # # question: what's the similar part between list and string # # 1. contains multiple items # # [1, 2, 3] '123' # # 2. index # # 3. loop # # 4. len() # # different: list -> mutable(changeable), string -> immutable(unchangeable) # # list = [1, 2, 3] # # string = 'abc' # # string[0] = 'w' # # string_new = string + 'w' # this does not change the string, it creates a new string # print(string) # print(string_new) # # print(list.count(3)) # a = [1, 2, 3] b = 1, 2, 3 # print(type(a)) print(type(b)) x, y = b # unpack print(x) print(y) # print(z) # # write a function takes a list and tuple, check if all values in tuple also in the list # def contains(l, t): # for i in t: # if i not in l: # return False # return True # # # write a function that takes a tuple as input, return a list contains the same value as tuple # def tuple_to_list(tuple): # list = [] # for i in tuple: # list.append(i) # return list # write a function that takes a list and a value, delete all the values from list which is equal to the given value # [1, 2, 2, 3] 2 -> [1, 3]
true
a0b7bbca5f8d4cbd1638a54e0e7c5d78302139f8
vijaykanth1729/Python-Programs-Interview-Purpose
/list_remove_duplicates.py
776
4.3125
4
''' Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. ''' original = [] def remove_duplicates(my_list): print("Original data: ", my_list) data = set(my_list) original.append(data) def using_loop(my_list): y = [] for i in my_list: if i not in y: y.append(i) print("Using loop to remove duplicates: ",y) remove_duplicates([1,2,3,4,5,4,2]) using_loop([1,2,3,4,5,4,2]) print("Using set function to remove duplicates:", original)
true
bb3c2b979426ab217b7cf3bbdadb12d4c8aa2e05
ThtGuyBro/Python-sample
/Dict.py
307
4.125
4
words = {"favorite dessert": "apple pie","never eat": "scallop","always have" : "parachute","don't have" :"accident","do this" : "fare","bug" : "flea"} print(words['bug']) words['parachute']= 'water' words['oar']= 'girrafe' del words['never eat'] for key, value in words.items(): print(key)
true
8320e270cc0ef7f8767336dfcb0dcf7ffe538e01
tocodeil/webinar-live-demos
/20200326-clojure/patterns/04_recursion.py
658
4.15625
4
""" Iteration (looping) in functional languages is usually accomplished via recursion. Recursive functions invoke themselves, letting an operation be repeated until it reaches the base case. """ import os.path # Iterative code def find_available_filename_iter(base): i = 0 while os.path.exists(f"{base}_{i}"): i += 1 return f"{base}_{i}" print(find_available_filename_iter('hello')) # --- # Recursive code def find_available_filename_rec(base, i=0): name = f"{base}_{i}" if not os.path.exists(name): return name return find_available_filename_rec(base, i + 1) print(find_available_filename_rec('hello'))
true
fc0d283efec47c1f9a4b19eeeff42ba58db258c7
EdmondTongyou/Rock-Paper-Scissors
/main.py
2,479
4.3125
4
# -*- coding: utf-8 -*- """ Edmond Tongyou CPSC 223P-01 Tues March 9 14:47:33 2021 tongyouedmond@fullerton.edu """ # Importing random for randint() import random computerScore = 0 ties = 0 userScore = 0 computerChoice = "" userChoice = "" # Loops until the exit condition (Q) is met otherwise keeps asking for # one of three options (R, P, S), every loop the computer choice is # decided via randint and then compares the user choice to the # computer choice. If user wins, adds 1 to userScore same with computer # win. If a tie is found adds 1 to the ties. If the inputted letter is # not R P S or Q then the loop repeats until a valid option is inputted while 'Q' not in userChoice: computerChoice = random.randint(0, 2) print ("Please input one: (R, P, S, Q) > ", end = " ") userChoice = input() userChoice = userChoice.upper() if 'R' in userChoice or 'P' in userChoice or 'S' in userChoice: if computerChoice == 0: print("Computer chose Rock", end = '. ') if 'R' in userChoice: print("Call it a draw.") ties += 1 elif 'P' in userChoice: print("You win.") userScore += 1 else: print("Computer wins.") computerScore += 1 elif computerChoice == 1: print("Computer chose Paper", end = '. ') if 'R' in userChoice: print("Computer wins.") computerScore += 1 elif 'P' in userChoice: print("Call it a draw.") ties += 1 else: print("You win.") userScore += 1 else: print("Computer chose Scissors", end = '. ') if 'R' in userChoice: print("You win.") userScore += 1 elif 'P' in userChoice: print("Computer wins.") computerScore += 1 else: print("Call it a draw.") ties += 1 elif 'Q' in userChoice: continue else: print("Invalid option, input again.") continue # Prints out the results for each score then compares the scores to see who won # or if a tie was found. print("Computer: " , computerScore) print("You: ", userScore) print("Ties: ", ties) if computerScore > userScore: print("Computer Won!") elif computerScore < userScore: print("You Won!") else: print("It's a tie!")
true
ca9040e2f67a9ef6e1e15e9b5fa73c8df6295877
mileuc/100-days-of-python
/Day 10: Calculator/main.py
1,544
4.3125
4
from art import logo from replit import clear def calculate(operation, first_num, second_num): """Takes two input numbers, a chosen mathematical operation, and performs the operation on the two numbers and returns the output.""" if operation == '+': output = first_num + second_num return output elif operation == '-': output = first_num - second_num return output elif operation == '*': output = first_num * second_num return output elif operation == '/': output = first_num / second_num return output else: return "Invalid operator chosen." print(logo) initial_calc = True while initial_calc == True: num1 = float(input("What's the first number? ")) subsequent_calc = True print("+\n-\n*\n/") while subsequent_calc == True: operator = input("Pick an operation: ") num2 = float(input("What's the second number? ")) result = calculate(operator, num1, num2) print(f"{num1} {operator} {num2} = {result}") if type(result) == float or type(result) == int: y_or_n = input(f"Type 'y' to continue calculating with {result},\nor type 'n' to start a new calculation: ").lower() if y_or_n == "n": subsequent_calc = False clear() elif y_or_n == 'y': num1 = result else: subsequent_calc = False initial_calc = False print("Sorry, you didn't enter 'y' or 'n'.") else: subsequent_calc = False initial_calc = False print("Sorry, you entered an invalid operator.")
true
7e6caaea40c2ca56d00cf95dce934fb338a55ca1
dlingerfelt/DSC-510-Fall2019
/FRAKSO_MOHAMMED_DSC51/loops-week5.py
2,983
4.53125
5
''' File: Loops.py Name: Mohammed A. Frakso Date: 12/01/2020 Course: DSC_510 - Introduction to Programming Desc: This program will contain a variety of loops and functions: The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user. Define a function named performCalculation which takes one parameter. The parameter will be the operation being performed (+, -, *, /). This function will perform the given prompt the user for two numbers then perform the expected operation depending on the parameter that's passed into the function. This function will print the calculated value for the end user. Define a function named calculateAverage which takes no parameters. This function will ask the user how many numbers they wish to input. This function will use the number of times to run the program within a for loop in order to calculate the total and average. This function will print the calculated average. ''' import operator # Function to do math operations def calc(number1: float, number2: float, op: str) -> float: operands = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} return operands[op](number1, number2) # Function to get the valid input number def get_number(message: str) -> float: number = 0 while number == 0: try: number: float = float(input(message)) break except ValueError: print('Invalid input please try again!') continue return number # This function will perform math operations based on operation entered def performCalculation(operation: str): number1 = get_number('Enter first number: ') number2 = get_number('Enter second number: ') output = calc(number1, number2, operation) print("the output is " + str(output), end="\n") # This function will calculate total and average of numbers def calculateAverage(): num = int(input('How many numbers you want to enter? ')) total_sum = 0 for n in range(num): number = get_number('Please enter the number: ') total_sum += number avg = total_sum / num print("the average is " + str(avg), end="\n") # Display the welcome statement def main(): print('Welcome to the math calculator:') print("Enter '+', '-', '*', '/', 'avg' for math operations, and 'cancel' for quiting the program", end="\n") while True: operation: str = input("Enter your choice \n") if operation == 'cancel': break if ("+" == operation) or ("-" == operation) or ("*" == operation) or ("/" == operation): performCalculation(operation) elif operation == 'avg': calculateAverage() else: print("Invalid input entered please try again", end="\n") if __name__ == '__main__': main()
true
88333bcf49ae0f01c6f7d4cca37c1dae5ddb64a2
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/final/WeatherDisplay.py
1,791
4.34375
4
# File : WeatherDisplay.py # Name : Pradeep Jaladi # Date : 02/22/2020 # Course : DSC-510 - Introduction to Programming # Desc : Weather Display class displays the weather details to output. class WeatherDisplay: def __init__(self, desc, city, country, temp, feels_like, min_temp, max_temp, lat, lon, wind): """ Initialize the model variables """ self._desc = desc self._city = city self._country = country self._temp = temp self._feels_like = feels_like self._min_temp = min_temp self._max_temp = max_temp self._lat = lat self._lon = lon self._wind = wind def print_report(self): """ Prints the details to the output screen """ print('---------------------------------------------------------------------------------------') print('Current temperature is : %df' % self.__convert_temp(self._temp)) print('outside it looks like : {}'.format(self._desc)) print('Current it feels like : %df' % self.__convert_temp(self._feels_like)) print('Wind outside is : %d miles per hour' % self.__convert_wind(self._wind)) print('City : {}, {}'.format(self._city, self._country)) print('coordinates are : [{}, {}]'.format(self._lat, self._lon)) print('Today the temperatures are High as %df and low as %df' % ( self.__convert_temp(self._max_temp), self.__convert_temp(self._min_temp))) print('---------------------------------------------------------------------------------------') def __convert_temp(self, kelvin: float) -> float: """ converts the temperature from kelvin to f """ return 9 / 5 * (kelvin - 273.15) + 32 def __convert_wind(self, meter: float) -> float: """ converts the wind from meter to miles per hour """ return meter * 2.2369363
true
433d5b3ed946f1f84893a9eed708b49e902af6c0
dlingerfelt/DSC-510-Fall2019
/NERALLA_DSC510/NERALLA_DSC510_WEEK11.py
2,521
4.15625
4
''' File: NERALLA_DSC510_WEEK10.py Name: Ravindra Neralla Course:DSC510-T303 Date:02/23/2020 Description: This program is to create a simple cash register program. The program will have one class called CashRegister. The program will have an instance method called addItem which takes one parameter for price. The method should also keep track of the number of items in your cart. The program should have two getter methods. getTotal – returns totalPrice getCount – returns the itemCount of the cart The program must create an instance of the CashRegister class. The program should have a loop which allows the user to continue to add items to the cart until they request to quit. The program should print the total number of items in the cart. The program should print the total $ amount of the cart. The output should be formatted as currency. ''' import locale # Creating class of CashRegister to calculate the total cost class CashRegister: def __init__(self): self.__totalItems = 0 self.__totalPrice = 0.0 # Creating a method to return total price of the shopping cart def getTotal(self) -> float: return self.__totalPrice # creating a method to return total number of items in the shopping cart def getCount(self) -> int: return self.__totalItems # Create a method to add items to the shopping cart def addItem(self, price: float): self.__totalPrice += price # Adding each item price in the shopping cart self.__totalItems += 1 # Adding item count in shopping cart def main(): print('Welcome to the cash register. To know your total purchase price please enter q ') # creating an object using CashRegister() class register = CashRegister() locale.setlocale(locale.LC_ALL, 'en_US.utf-8') while True: try: operation: str = input('Enter the price of your item : ') # At the end of shopping, enter q to calcualte total price and total items in cart if operation == 'q': break price = float(operation) register.addItem(price) except ValueError: print('The price is not valid. Please try again') total_price: float = register.getTotal() total_count: int = register.getCount() print('Total number of items added to your shopping cart : {}'.format(total_count)) print('Total price of items is : {}'.format(locale.currency(total_price, grouping=True))) if __name__ == '__main__': main()
true
78eee39d5b2e07f640f8be3968acdec0b7c8e13f
dlingerfelt/DSC-510-Fall2019
/Safari_Edris_DSC510/Week4/Safari_DSC510_Cable_Cost.py
1,951
4.4375
4
# File : Safari_DSC510_Cable_Cost.py # Name:Edris Safari # Date:9/18/2019 # Course: DSC510 - Introduction To Programming # Desc: Get name of company and length in feet of fiber cable. compute cost at $.87 per foot. display result in recipt format. # Usage: Provide input when prompted. def welcome_screen(): """Print welcome screen""" # Welcome Screen print("Welcome to Fiber Optics One.") # Get Company name print("Please tell us the name of your company") def compute_cost(Cable_Length,CableCostPerFoot): """Compute cable cost""" # Compute Installation cost at CableCostPerFoot cents return float(Cable_Length) * CableCostPerFoot welcome_screen() Company_Name = input('>>>') print("Thank You.") print("Now, please tell us the length in feet of cable you need. Enter 'q' to exit.") Cable_Length = input('>>>') # Use while to run program until user enters 'q' while Cable_Length.lower() != 'q': if not Cable_Length.isnumeric(): # Make sure value is numeric print("PLease enter a valid number.") else: # Compute Installation Installation_Cost = compute_cost(Cable_Length, 0.87) Tax = Installation_Cost*.083 # Tax rate is 8.3% Installation_Cost_PlusTax = Installation_Cost + Tax # Print out the receipt print("Thank You. Here's your receipt.") print("Company Name: " + Company_Name) print("Cable Length: " + Cable_Length) print("Cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost, '.2f')) + ".") print("Tax at 8.3% is $: " + str(format(Tax, '.2f')) + ".") print("Total cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost_PlusTax, '.2f')) + ".") print("Please enter another length in feet of cable you need. Enter 'q' to exit.") Cable_Length = input('>>>') # Exit the program print("Thank You. Please come back.")
true
d2587b87036af1d39d478e5db8c6d03b19c6da83
dlingerfelt/DSC-510-Fall2019
/SMILINSKAS_DSC510/Temperatures.py
1,290
4.21875
4
# File: Temperatures.py # Name: Vilius Smilinskas # Date: 1/18/2020 # Course: DSC510: Introduction to Programming # Desc: Program will collect multiple temperature inputs, find the max and min values and present the total # number of values in the list # Usage: Input information when prompted, input go to retrieve the output import sys temperature = [] # list for temperatures to be stored number = [] # list for input variable count = 0 # int variable for keeping count of loops while number != 'go': # go is set up as sentinel value to break the input try: # to not add go or any ineligible value into the program, if error: the exception will run line 17 number = int(input('Enter a temperature or to run program enter go:')) temperature.append(number) # append adds the parameter to the end of temperature count = count + 1 # counts the loops except ValueError: # if line 15 triggers error run the below block of code print('The highest temperature is:' + str(max(temperature))) # max() determines the maximum value print('The lowest temperature is:' + str(min(temperature))) # min() determines the minimum value print('The number of values entered is:' + str(count)) sys.exit() # exits the program
true
7faffa27e0944548717be676c521fcb8ed1653a8
dlingerfelt/DSC-510-Fall2019
/FRAKSO_MOHAMMED_DSC51/week6-lists.py
1,257
4.46875
4
''' File: lists.py Name: Mohammed A. Frakso Date: 19/01/2020 Course: DSC_510 - Introduction to Programming Desc: This program will work with lists: The program will contains a list of temperatures, it will populate the list based upon user input. The program will determine the number of temperatures in the program, determine the largest temperature, and the smallest temperature. ''' # create an empty list temperature_list = [] while True: print('\n Please enter a temperature:') #print('Enter "finished" once you are done with all temparatures: \n') input_temperature = input('please type "finished" when you have entered all temperatures') if input_temperature.lower() == 'finished': break try: temperature_list.append(float(input_temperature)) except ValueError: input_temperature = input('Oops... Please enter a numeric value!') temperature_list.append(float(input_temperature)) # printing argest, smallest temperatures and how many temperatures are in the list. print('The largest temperature is: ', max(temperature_list), 'degrees') print('The smallest temperature is: ', min(temperature_list), 'degrees') print('The total temperatures input is: ', len(temperature_list))
true
42d37509986bc3233ab711cef2496ab4fa17602a
dlingerfelt/DSC-510-Fall2019
/Ndingwan_DSC510/week4.py
2,921
4.28125
4
# File: week4.py # Name: Awah Ndingwan # Date: 09/17/2019 # Desc: Program calculates total cost by multiplying length of feet by cost per feet # Usage: This program receives input from the user and calculates total cost by multiplying the number of feet # by the cost per feet. Finally the program returns a summary of the transaction to the user cost_per_feet_above_100feet = 0.80 cost_per_feet_above_250feet = 0.70 cost_per_feet_above_500feet = 0.50 length_above_100 = 100.0 length_above_250 = 250.0 length_above_500 = 500.0 # calculate and return cost def calculate_cost(cost, feet): return cost * feet class FiberCostCalculator: def __init__(self, company_name="", num_of_feet=0, installation_cost=0, cost_per_feet=0.87): self.company_name = company_name self.number_of_feet = num_of_feet self.installation_cost = installation_cost self.cost_per_feet = cost_per_feet self.get_input() self.compute_total_cost() self.show_receipt() # Get amd validate input from user def get_input(self): # printing welcome message message = "******** WELCOME ********" print(message) self.company_name = input("Enter Company name: ") while True: try: self.number_of_feet = float(input("Enter number of feet for fiber optic cable(ft): ")) except ValueError: print("Not Valid! length of feet cannot be a String. Please try again.") continue else: break # compute installation cost for user def compute_total_cost(self): if length_above_100 < self.number_of_feet < length_above_250: self.cost_per_feet = cost_per_feet_above_100feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) elif length_above_250 < self.number_of_feet < length_above_500: self.cost_per_feet = cost_per_feet_above_250feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) elif self.number_of_feet > length_above_500: self.cost_per_feet = cost_per_feet_above_500feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) else: self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) # Print receipt details def show_receipt(self): print('********************') print(' Receipt ') print(' ****************** ') print(f'Company Name: {self.company_name}') print(f'Cost Per Feet: ${float(self.cost_per_feet)}') print(f'Length of feet to be installed: {self.number_of_feet} feet') print("Total cost: $" + format(round(float(self.installation_cost), 2), ',.2f')) if __name__ == "__main__": fiberCostCalculator = FiberCostCalculator()
true
8c70251443a384255c610a8a96d4977c5da28947
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/TEMPERATURE_OPERATIONS.py
1,536
4.53125
5
# File : MATH_OPERATIONS.py # Name : Pradeep Jaladi # Date : 01/11/2020 # Course : DSC-510 - Introduction to Programming # Assignment : # Program : # Create an empty list called temperatures. # Allow the user to input a series of temperatures along with a sentinel value which will stop the user input. # Evaluate the temperature list to determine the largest and smallest temperature. # Print the largest temperature. # Print the smallest temperature. # Print a message tells the user how many temperatures are in the list. def print_values(temperatures): length: int = len(temperatures) # there are couple of ways to determine the min & max of the list -> using max & min function or sort the list and get 0, max length element print('There are total %d temperature values ' % length) print('The lowest temperature is %g and the highest temperature is %g' % (min(temperatures), max(temperatures))) def main(): print("Welcome to temperature calculator program ....") # Declaration of empty temperatures list temperatures = []; # Getting the temperature values while True: temperature: str = input("Enter the temperature [%d] : " % len(temperatures)) if temperature == 'q': break try: temperatures.append(float(temperature)) except ValueError: print("Oops! Invalid temperature. Try again...") # printing the desired calucations print_values(temperatures) if __name__ == '__main__': main()
true
f5428333663e7da9d39bdff3e25f6a34c07ebd08
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 3.1 - Jonathan Steen.py
1,186
4.34375
4
# File: Assignment 3.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 12/9/2019 # Course: DSC510 - Introduction to Programing # Desc: Program calculates cost of fiber optic installation. # Usage: The program gets company name, # number of feet of fiber optic cable, calculate # installation cost, bulk discount and print receipt. #welcome statement and get user input print('Welcome to the fiber optic installation cost calculator.') companyName = input('Please input company name.\n') fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n') #if statement to calculate bulk discount fiberOpticCost = 0 if float(fiberOpticLength) > 499: fiberOpticCost = .50 elif float(fiberOpticLength) > 249: fiberOpticCost = .70 elif float(fiberOpticLength) > 99: fiberOpticCost = .80 elif float(fiberOpticLength) < 100: fiberOpticCost = .87 #calculate cost totalCost = float(fiberOpticLength) * float(fiberOpticCost) #print receipt print('\n') print('Receipt') print(companyName) print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot') print('Total: ' + '${:,.2f}'.format(totalCost))
true
af093e824555df86dc56d2b1b581270fd1671d1c
dlingerfelt/DSC-510-Fall2019
/Stone_DSC510/Assignment2_1/Assignment2_1.py
751
4.21875
4
# 2.1 Programming Assignment Calculate Cost of Cabling # Name: Zachary Stone # File: Assignment 2.1.py # Date: 09/08/2019 # Course: DSC510-Introduction to Programming # Greeting print('Welcome to the ABC Cabling Company') # Get Company Name companyName = input('What is the name of you company?\n') # Get Num of feet feet = float(input('How any feet of fiber optic cable do you need installed?\n')) # calculate cost cost = float(feet*0.87) # print receipt print("********Receipt********") print('Thank you for choosing ABC Cable Company.\n') print('Customer:', companyName) print('Feet of fiber optic cable:', feet) print('Cost per foot:', '$0.87') print('The cost of your installation is', '${:,.2f}'.format(cost)) print('Thank you for your business!\n')
true
edc28c6d0a7bd72d9a875d7716f8957874455fd0
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 4.1 - Jonathan Steen.py
1,364
4.15625
4
# File: Assignment 4.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 12/17/2019 # Course: DSC510 - Introduction to Programing # Desc: Program calculates cost of fiber optic installation. # Usage: The program gets company name, # number of feet of fiber optic cable, calculate # installation cost, bulk discount and prints receipt. #welcome statement and get user input print('Welcome to the fiber optic installation cost calculator.') companyName = input('Please input company name.\n') fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n') #if statement to calculate bulk discount fiberOpticCost = 0 if float(fiberOpticLength) > 499: fiberOpticCost = .50 elif float(fiberOpticLength) > 249: fiberOpticCost = .70 elif float(fiberOpticLength) > 99: fiberOpticCost = .80 elif float(fiberOpticLength) < 100: fiberOpticCost = .87 #define function to calculate cost def calculateCost(x, y): global totalCost totalCost = float(x) * float(y) return totalCost #call calcution function calculateCost(fiberOpticLength, fiberOpticCost) #print receipt print('\n') print('Receipt') print(companyName) print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot') print('Total: ' + '${:,.2f}'.format(totalCost))
true