blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
92a95550ba855ab2bd5de559c3808e5841e34b02
eloydrummerboy/Udemy
/Deep_Learning_PreReq_Numpy/Exercise5.py
962
4.4375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 30 22:15:07 2017 @author: eloy """ #Excercise 5: Create a function that tests whether or not #a matrix is symmetrical. # Do it the "hard" way and again utilizing numpy functions import numpy as np # Manual Mode def is_symmetric_manual(matrix): for row in range(0,matrix.shape[0]): for col in range(0,matrix.shape[1]): if matrix[row][col] != matrix[col][row]: return False return True # Numpy Method def is_symmetric_np(matrix): if np.array_equal(matrix,matrix.transpose()): return True else: return False non_sym_matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]) sym_matrix = np.array([[1,2,3,4],[2,2,5,6],[3,5,7,8],[4,6,8,9]]) print(is_symmetric_manual(non_sym_matrix)) print(is_symmetric_manual(sym_matrix)) print(is_symmetric_np(non_sym_matrix)) print(is_symmetric_np(sym_matrix))
true
f0e2bf67b6749a8585cb41e3ff066bfd3f0255ff
NaraJulia/programacao-orientada-a-objetos
/listas/lista-de-exercicio-05/Questao13.py
390
4.125
4
QUESTAO 13 def moldura(lin,col): print("+","-"*col,"+") for x in range(lin): print("|"," "*col,"|") print("+","-"*col,"+") col = input("Nmero de Colunas: ") lin = input("Nmero de Linhas: ") if col == "": col = '1' if lin =="": lin = '1' col = int(col) lin = int(lin) if col == 0: col = 1 elif col > 20: col = 20 if lin == 0: lin = 1 elif lin > 20: lin = 20 moldura(lin,col)
false
d3ee95b2f84a374cc585eae6b5f5946dba6d809e
faizsh/Assignments-SA
/ASSIGNMENT NUMBER 8/Assignment 8.1.py
500
4.15625
4
#WAP to get max and min value in a dictionary D={} D.setdefault('Math',input('Enter your marks for Math')) D.setdefault('Chem',input('Enter your marks for Chem')) D.setdefault('Phy',input('Enter your marks for Phy')) D.setdefault('Mech',input('Enter your marks for Mech')) D.setdefault('Java',input('Enter your marks for Java')) print(D) a=max(D.values()) b=min(D.values()) print('The maximum value from the above string is',a) print('The minimum value from the above string is',b)
true
26c91a0fc589129846b3da744fb003f267418c23
faizsh/Assignments-SA
/ASSIGNMENT NUMBER 9/Assignment 9.1.py
709
4.28125
4
#Using user define function WAP to find whether the given number is armstrong or not def Armstrong(no): t=no s=0 while(no!=0): r=no%10 s=(s+(r**3)) no=no//10 return s==t n=int(input('Enter the number:')) if(Armstrong(n)): print('Number is armstrong number') else: print('Number is not an armstrong number') '''OR the other logic is def Armstrong(no): t=no s=0 while(no!=0): r=no%10 s=(s+(r**3)) no=no//10 return s n=int(input('Enter the number:')) a=Armstrong(n) if(Armstrong(n)==n): print('Number is armstrong number') else: print('Number is not an armstrong number')'''
false
2012932634c3e2b798ac1d9d8474b76eeca5cc04
fwparkercode/P2_SP20
/Notes/NotesA/10_plotting.py
641
4.125
4
import matplotlib.pyplot as plt import random plt.figure(1) # create a new window/plot plt.plot([120, 40, 10, 0]) # plot y against the index plt.plot([1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25, 36]) # plot x vs y plt.figure(2) # make second window x1 = [x for x in range(1, 11)] y1 = [y ** 2 for y in x1] plt.plot(x1, y1, color='green', marker='*', markersize=10, linestyle=':', alpha=0.5, label="myPlot") # title axes label unit numbers key (TALUNK) plt.xlabel('time (seconds)') plt.ylabel('excitement level (YAYS)') plt.title('Example Plot') plt.axis([0, 11, 0, 120]) # [xmin, xmax, ymin, ymax] plt.show() # opens the window/plot
true
30f607fcef165d8c2612cec0ee3ee44fe9e1318e
fwparkercode/P2_SP20
/Labs/Scraping Lab/scraping-lab.py
1,554
4.15625
4
# SCRAPING PROBLEMS # Twitter Scraping (15pts) # Go to your favorite follow on Twitter. (not someone who posts explicit materials please) # Inspect the twitter feed in Chrome. # You'll notice that the tweets are stored in a ordered list <ol></ol>, and individual tweets are contained as list items <li></li>. # Use BeautifulSoup and requests to grab the text contents of last 5 tweetslocated on the twitter page you chose. # Print the tweets in a nicely formatted way. # Have fun. Again, nothing explicit. # print("{} {}!".format("Hello", "World")) # Weather Scraping (15pts) # Below is a link to a 10-day weather forecast at weather.com # Pick the weather for a city that has the first letter as your name. # Use requests and BeautifulSoup to scrape data from the weather table. # Print a synopsis of the weather for the next 10 days. # Include the day and date, description, high and low temp, chance of rain, and wind. (2pts each) # Print the weather for each of the next 10 days to the user in a readable sentences. # You can customize the text as you like, but it should be readable as a sentence without errors. (5pts) # You will need to target specific classes or other attributes to pull some parts of the data. # Sample sentence: # Wednesday, April 4 will be Partly Cloudy/Windy with a High of 37 degrees and a low of 25, humidity at 52%. There is 0% chance of rain with winds out of the WNW at 22 mph. # if the sentence is a little different than shown, that will work; do what you can. Don't forget about our friend string.format()
true
58a7704cd980f8d5da2748b1b28bdfd565282b80
sakuraihisaya/nlp_hitting100
/03.py
1,006
4.15625
4
###################################################################################################################### # 03. 円周率 # # "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."という文を単語に分解し,# # 各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ. # ###################################################################################################################### # coding:utf-8 target = u'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.' result = [] # words = target.split(' ') # for word in words: # result.append(len(word) - word.count(',') - word.count('.')) # print(result) words = [len(w.strip(',.')) for w in target.split()] print(words)
false
42caf8c6beaf6f2f62a19d008004f5c74ab04d6f
Sevansu/PythonBasicPrograms
/ConceptUnderstandingViaPrograms/SumofNumberWithConstrains.py
1,111
4.4375
4
'''Write a module that gets a sequence of integers from the user, and, when complete, displays a report showing the sum, number of integers entered and an average. Here are some details: - The number of integers entered is variable. The user enters a carriage return(\r) (no data entry) to signify the end of entry. - If the user enters anything other than an integer or empty value (carriage return only), a message must be displayed indicating “Invalid entry” and the user must re-enter a valid value. - After each entry, the user should see a message to enter an integer.Note:-To get output in end type \r''' y=[] sum=0 while True: value = input('Enter the number : ') if (value.isdigit()): y.append(int(value)) elif (value != None): for i in y: sum += i avg = sum / len(y) print ("sum of given number is ",sum,"And Number of integer entered is ",len(y),"And average number of given number is ", avg) break else: print("Warning !!! Enter only interger number") break
true
4588cfe2c3d1c5ca9da842acb10448b6bd69eae1
Athie9104/python-exersises
/dictionary.py
1,099
4.375
4
this_dict={"brand": "Ford", "model": "Mustang", "year":"1964"} #print(this_dict) # printing all the items of a dictionary '''for x in this_dict: print(x)''' # printing all the key names '''for x in this_dict: print(this_dict[x])'''# print values one by one without keys '''for x in this_dict.values(): print(x)'''# to return all the all the values '''for x, y in this_dict.items(): print(x, y)'''# to print key and its value '''if "odel" in this_dict: print("Yes, 'model' is one of the keys in this_dict Dictionary") '''# to check if the value exists in the dictionary '''this_dict["color"]="red" print(this_dict)'''# adding items to a dictionary '''this_dict.pop("model") print(this_dict)'''# removing items from a dictionary '''this_dict.popitem() print(this_dict)'''# removing the last item from a dictionary '''del this_dict["model"] print(this_dict)'''# REMOVES ITEM WITH SPECIFIED KEY NAME '''this_dict.clear() print(this_dict)'''# this will make dictionary to be empty '''mydict=this_dict.copy() print(mydict)'''# to copy or make a duplicate of the dictionary
true
de617afab3e139ca157de3e4db1502d4eb14e45f
recto/swift_nav
/src/application.py
2,551
4.21875
4
""" Fibonacci and FizzBuzz """ from __future__ import print_function import sys import math def fib(nth): """ Fibonacchi Number :param nth: nth :return: return n Fibonacchi numbers. """ nums = [0, 1, 1] if nth == 0: return [0] elif nth == 1: return [0, 1] elif nth == 2: return nums for _ in xrange(3, nth + 1): if nums[-2] < sys.maxint - nums[-1]: nums.append(nums[-1] + nums[-2]) else: raise OverflowError("Fibonacchi number will exceed max integer value, {0}. \ Please decrease 'n', {1}.".format(sys.maxint, nth)) return nums def is_prime(num): """ Check if the given number is prime number. :param num: input number :return: return True if num is prime. Otherwise, False. """ if num in [0, 1]: return False elif num == 2: return True # even numbers are not prime number. eliminate them first. if num%2 == 0: return False # check if num can be divided by odd number greater than equals 3 up to # sqrt(num) + 1. for i in xrange(3, int(math.sqrt(num)) + 1, 2): if num%i == 0: return False return True def fizz_buzz(nth): """ Play Fizz buzz with a bit tweaked rule as below: generating the first n Fibonacci numbers F(n), printing ... - ... "Buzz" when F(n) is divisible by 3. - ... "Fizz" when F(n) is divisible by 5. - ... "FizzBuzz" when F(n) is divisible by both 3 and 5. (this rule is added according to general fizz buzz game.) - ... "BuzzFizz" when F(n) is prime. - ... the value F(n) otherwise. :param nth: nth parameter for Fibonacchi number """ nums = [] try: nums = fib(nth) except OverflowError as err: print(err) sys.exit() results = [] for nth in xrange(0, len(nums)): if nums[nth] in [0, 1]: results.append((nums[nth])) elif nums[nth]%3 == 0 and nums[nth]%5 == 0: results.append("FizzBuzz") elif nums[nth]%3 == 0: results.append("Buzz") elif nums[nth]%5 == 0: results.append("Fizz") elif is_prime(nums[nth]): results.append("BuzzFizz") else: results.append((nums[nth])) return results if __name__ == "__main__": if len(sys.argv) <= 0: sys.exit("Please specify the number for Fibonachii. e.g. application.py 10") print(*fizz_buzz(int(sys.argv[1])), sep=", ")
false
bd75359c415ae869c3bdcb94de7cf15f2d8f4211
jayakasadev/MiniFlow
/src/nodes/Linear.py
713
4.21875
4
from .Neuron import Neuron class Linear(Neuron): def __init__(self, inputs, weights, bias): Neuron.__init__(self, inputs) # NOTE: The weights and bias properties here are not # numbers, but rather references to other neurons. # The weight and bias values are stored within the # respective neurons. self.weights = weights self.bias = bias def forward(self): """ Set self.value to the value of the linear function output. Your code goes here! """ self.value = self.bias.value for i in range(len(self.inbound_neurons)): self.value += self.inbound_neurons[i].value * self.weights[i].value
true
427c8b69410799359dbabc0d7eedef2a0ae1f279
jtrieudang/CodingDojo-Algorithm
/Looping_thru_dictionary.py
381
4.28125
4
my_list = [ { "name": "bags of coffee", "quantity": 4, "price": 5 }, { "name": "bags of rice", "quantity": 2, "price": 2.5 } ] def iterate_through_dictonaries(input_list): for element in my_list: # this is the item for key, val in element.items(): print(key, "-", val)
true
a85dc8ac663e1a3d116c172a05e0e5649c55a16d
hadassah0987/python-crash-course
/cars.py
970
4.5
4
cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) #sort puts the items in the list in alphabetical order permanantly cars.sort(reverse=True) print(cars) #reverse=True puts the item in the list in opposite alphabetical order. for example the list starts with z instead of a. #sorted puts the items in the list alphabetically but not permanantly. print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list again:") print(cars) cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse() print(cars) #reverse just changes the order randomly and permanately but not in alphabetical order. car = ['bmw', 'audi', 'toyota', 'subaru'] len(cars) #len finds the length of the list. for example for cars the len is 4. cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title())
true
884965a66e1cab6e40db100ac65ba40d23f3b81b
claudiayunyun/yunyun_hackerrank
/python/MutateString.py
523
4.28125
4
# two ways to change an immutable string at specific position # 1 to convert the string to a list and then change the value. # 2 to slice the string and join it back. # change an immutable string use replace() def mutate_string(string, position, character): l = list(string) l[position] = character return ''.join(l) # return string[:position] + character + string[position+1:] if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
true
6b09d95e90cb1417b6450a6d9f515767313fb9ce
jacobshilling/whateveryouwant
/jacobmadlib.py
846
4.1875
4
print ("Welcome to Jacob Shilling's madlib.") noun = input ("Enter noun: ") name = input ("Enter boy name: ") animal = input ("Enter animal: ") girlname = input ("Enter girl name: ") adjective = input ("Enter adjective: ") food = input ("Enter a food item: ") emotion = input ("Enter emotion: ") famousperson = input ("Enter famous person: ") place = input ("Enter place: ") print ('Once upon a time, there was a %s named %s, and he was madly in love with a %s named %s. However, %s was very %s, and one day accidentely ate %s, which she was allergic to, and she dropped dead immediately. %s was %s, and decided he would go for a long walk on the beach to clear his mind. On the beach, he met %s, who kidnapped him and sold him into slavery in %s.' % (noun, name, animal, girlname, girlname, adjective, food, name, emotion, famousperson, place))
true
7fc172d403aa5915eb4aea2ca24ba3a92ba12bdd
NajmusShayadat/Complete-Python-3-Bootcamp
/02-Python Statements/02GussingGame.py
2,655
4.28125
4
# Guessing Game Challenge # Let's use while loops to create a guessing game. # # The Challenge: # Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are: # # If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS" # On a player's first turn, if their guess is # within 10 of the number, return "WARM!" # further than 10 away from the number, return "COLD!" # On all subsequent turns, if a guess is # closer to the number than the previous guess return "WARMER!" # farther from the number than the previous guess, return "COLDER!" # When the player's guess equals the number, tell them they've guessed correctly and how many guesses it took! # Generating a random number between 1 and 100. from random import randint p = randint(1, 100) # Printing instruction and asking for an input print("WELCOME TO GUESS ME!") print("I'm thinking of a number between 1 and 100") print("If your guess is more than 10 away from my number, I'll tell you you're COLD") print("If your guess is within 10 of my number, I'll tell you you're WARM") print("If your guess is farther than your most recent guess, I'll say you're getting COLDER") print("If your guess is closer than your most recent guess, I'll say you're getting WARMER") print("LET'S PLAY!") # Guess Numbers are stored in variable gns, counting the number of guesses using variable gns and i gns = [] i = 0 while True: # Asking for an input gn = int(input("\nPlease enter your guess! ")) # Count of the number of input i += 1 # Checking the input is within the limit or not, if not, asking for input again if gn < 1 or gn > 100: print('\nOUT OF BOUNDS! Please try again!') continue # Checking if the number guessed correctly, if guessed correctly, the loop breaks. elif gn == p: print(f'\n*** Congratulations ***\n\nThe number is {gn}.\n\nYou have guessed correctly.\nYou have taken {i} guesses') break # appending new inputs in a list to compare later for warmer or colder! gns.append(gn) # if there are more than one guess latest guess is compared with the previous one # for only one input len(gns) > 1 returns False. and the condition moves to else section if len(gns) > 1: if abs(p - gn) < abs(p - gns[-2]): print('\nyou are getting WARMER!') else: print('\nyou are getting COLDER!') # The first guess is compared with the actual number to check the difference is bigger than 10 or not else: if abs(p - gn) < 10: print('\nWARM!') else: print('\nCOLD!')
true
79df55149b1d23b4eeb7bbd977335e5376810f38
LONG990122/PYTHON
/第一阶段/2. Python01/day02/exercise/07_absolute.py
627
4.1875
4
# 练习: # 写程序,输入一个数 # 1) 用if语句计算出这个数的绝对值并打印出来 # 2) 用条件表达式计算出这个数的绝对值并打印出来 n = int(input("请输入一个数: ")) # 1) 用if语句计算出这个数的绝对值并打印出来 # 方法1 # if n < 0: # absolute = -n # else: # absolute = n # 方法2 absolute = n if absolute < 0: absolute = -absolute print("if语句计算的绝对值是:", absolute) # 2) 用条件表达式计算出这个数的绝对值并打印出来 absolute = -n if n < 0 else n print("条件表达式计算的绝对值是:", absolute)
false
b20b69c2895a7b95bc33bd97204618b0d3bbf8c5
LONG990122/PYTHON
/第一阶段/5. OOP/day03/exercise/01_mylist.py
742
4.15625
4
# 练习: # 已知list 列表类中没有insert_head方法, # 写一个自定义的类MyList,继承自list类,在MyList类内添加 # class MyList(list): # def insert_head(self, value): # '''以下自己实现,将Value插入到列表的开始处''' # 如: # L = MyList(range(1,5)) # print(L) # [1,2,3,4] # L.insert_head(0) # print(L) # [0,1,2,3,4] # L.append(5) # print(L) # [0,1,2,3,4,5] class MyList(list): def insert_head(self, value): '''以下自己实现,将Value插入到列表的开始处''' self.insert(0, value) L = MyList(range(1, 5)) print(L) # [1,2,3,4] L.insert_head(0) print(L) # [0,1,2,3,4] L.append(5) print(L) # [0,1,2,3,4,5]
false
e509e55f0864e37fa6d75df5d27a64d825bf6918
Sam40901/Selection
/Selection revision exercises 4.py
299
4.15625
4
print("this program will ask for two numbers and display the bigger number.") first_number = int(input("please enter your first number: ")) second_number = int(input("please enter your second number: ")) if first_number > second_number: print(first_number) else: print(second_number)
true
8131b15b33a6d0c53e56f81d95f787b36bf44268
xaneeshax/PRP
/to_do_list.py
2,607
4.46875
4
''' Define a function called to_do that takes two inputs: action and activity Actions: ‘remove’, ‘add’, ‘pop first’ Activity: the name of the activity to_do(‘remove’, ‘eat pizza’) → removes the pizza from the list to_do(‘add’, ‘eat pizza’) → should add pizza to the list to_do(‘pop first’, None) → should pop the first element of the list ''' # The main list that I want to make changes to to_do_list = [] def to_do(action, activity): if action == 'add': # Which list function can I use to add an item to my list? # What if the user is adding something that's already in the list? # What function can I use to check if a value is already in the list? pass elif action == 'remove': # Which list function can I use to remove an item from my list? # What if the user is removing something that's not in the list? # What function can I use to check if a value is already in the list? pass elif action == 'pop first': # Which list function can I use to remove the first item of my list? # What if the list is empty? # How can I check if my list is empty or not? pass else: print('this request is not supported') to_do('add', 'eat pizza') # will add 'eat pizza' to the list to_do('add', 'wash my hair') # will add 'wash my hair' to the list to_do('remove', 'wash my hair') # will remove 'wash my hair from the list to_do('pop first', None) # will pop the first element, 'eat pizza' from list # The to_do list will now be empty to_do_list = [] def to_do(action, activity): if action == 'add': if activity in to_do_list: print('already in the list') else: to_do_list.append(activity) elif action == 'remove': if activity in to_do_list: to_do_list.remove(activity) else: print('this activity is not in the list') elif action == 'pop first': if len(to_do_list) != 0: to_do_list.pop(0) else: print('the to do list is empty') else: print('this request is not supported') to_do('add', 'eat dinner') print(to_do_list) to_do('add', 'wash my hair') print(to_do_list) to_do('add', 'wash my hair') print(to_do_list) to_do('remove', 'wash my hair') print(to_do_list) to_do('pop first', None) print(to_do_list)
true
7f376bde79db9306fe9f56b56927f44c0c980c0e
c34647016/280201004
/lab3/5.py
453
4.1875
4
m=input("Please enter a month with capital first letter :") d=int(input("Please enter a day:")) if m == "January" or m == "February" or m == "December" and d >= 21 or m == "March" and d < 20 : print("Winter") elif m == "March" and d >= 20 or m == "April" or m == "May" or m == "June" and d < 21 : print("Spring") elif m == "June" and d >= 21 or m == "July" or m == "August" or m == "September" and d < 22 : print("Summer") else : print("Fall")
false
afb9e9fa3453475d7597677e17d60d4199fa5c4d
Paulsify/You-Gonna-Learn-Today
/0x2-Data_types.py
2,436
4.375
4
""" In this file you will learn about variables and types of data that can be stored in those variables Variables are a way for you to store data and then reference it later The syntax of which is: name_of_variable = data There are a few data types that can be stored in a variable 1. Integers - Integers are whole numbers without a decimal point. They are also called int or ints 2. Floating point - Floating point numbers are numbers that have a decimal point. They are also called float numbers or floats 3. Strings - Strings are a sequence or string of characters. It is often used to print text to the screen like was done in Hello_World.py. These are simply called strings 4. Boolean - Variables that are boolean can either be 'True' or 'False'. Often shortened to bool or bools Less common than the other three types. """ #---------------------------------------------------------------------------------------------------- # A small example of assigning different varable types. integer = 7 # Integers can be as big as you want as long as there are no decimal points floating_point = 6.9 # As with integers any amount of numbers can be added before and after the decimal points string = 'Spam is delicious' # When assigning a string quotes are used. Either single quotes or double. NOTE:With double it is easier to add apostrophes. boolean = True #In python it is required for a boolean to be either True or False to be capitilized because python is case sensitive a, b, c, d = 1, 2.3, 'Bacon is also good', False # It is possible to assign multiple variables at a time NOTE: Try to name the variable in a way that lets you remeber what it is for print('This is a integer: ', integer) #When printing more than one thing, be sure to seperate each with a comma print('This is a float: ', floating_point) print('This is a string: ', string) print('This is a Boolean: ', boolean) print('All the variables: ', a, ' ', b, ' ', c, ' ', d) # Adding spaces can make the output more readable. ''' Try changing the values and see the output ! NOTE: Boolean can only be True or False Python is usually read by the computer line by line, top to bottom. If you want to change a variable after assigning it earlier in the program then make sure it is the same type. There are ways to convert between the data types but thats for another file '''
true
09572ea6995bacc296e7d6a2257d9e4b01a22bf3
pratika1505/TribeVibe
/Python/Factorial.py
301
4.28125
4
# Python 3 program to find # factorial of given number def factorial(n): if n < 0: return 0 elif n == 0 or n == 1: return 1 else: fact = 1 while(n > 1): fact *= n n -= 1 return fact # Driver Code num = int(input('enter any number')) print("Factorial of",num,"is",factorial(num))
true
b6b3ccaa664cbc4d8a738662d8f3992700c8af22
nkukadiya89/learn-python
/accessingListItems.py
374
4.25
4
# Accessing List Items by different ways numbers = list(range(20)) #below code return value from start to end - 1 number = numbers[0:3] print(number) #use for every X number get from list everysecondele = numbers[::2] print(everysecondele) #Reverse list everysecondele = numbers[::-1] print(everysecondele) #Reverse list reverseList = numbers[2::-1] print(reverseList)
true
e211f7d4d665a210cb89bd6fc94f93450fbf8513
xiaohaiguicc/CS5001
/Course_case/2018_9_18/test_average.py
648
4.125
4
#Method 1: # def main(): # counter = 0 # sum = 0 # while True: # number = input("Input a value:") # counter += 1 # if(number == "Done"): # print("All done") # break # sum += float(number) # average = sum/counter # print("Average so far:",average) #Method 2: def main(): counter = 0 average = 0.0 value = input("Input a value:") while(value != "done"): temp = average * counter + float(value) counter += 1 average = temp/counter print("Average so far:",average) value = input("Input a value:") main()
true
58ecb17a245d752a1234b451af0ff110a9f86b6b
xiaohaiguicc/CS5001
/Course_case/2018_9_11/fact.py
674
4.28125
4
print("We present the following facts for your", "extracurricular edification:") # numerical characters can be part of a string print("Letters in the Hawaiian alphabet: 12") # concatenating strings with numbers results in a string print("Total number of Japaense hiragana:", 46) # concatenating numbers and strings with plus require # explicitly "casting" the number to a string using str() print("Total number of Japanese katakana: " + str(46)) # arithmetic and other expressions can be evaluated within # a string. print("672", "+", "5", "=", str(672 + 5)) print(1, "is the loneliest number") print("The speed limit on the highway in France is", 130, "km/h")
true
1eae1b91b77b73db576799174a1fc76eb6ce42ac
griever255/CompSci_Python_6.0001
/Lec2/finger_exercises.py
949
4.15625
4
############################# ## Finger Exercise 1 and 2 ## ############################# # # Ask the user for ten integers # integers = [] # for i in range(10): # integers.append(int(input("Enter integer number " + str(i+1) + ": "))) # # Determine the largest odd integer in integers # largest_odd = 0 # for i in integers: # if i % 2 == 1 and i > largest_odd: # largest_odd = i # # Print the largest odd, or if there's no odds # if largest_odd != 0: # print("The largest odd integer is:", largest_odd) # else: # print("None of these numbers are odd") ####################### ## Finger Exercise 3 ## ####################### # Given a string of comma-separated decimals, print the sum s = "1.23,2.4,3.123" sum = 0 index_start = 0 index_end = 0 for c in s: if c == ",": sum += float(s[index_start:index_end]) index_start = index_end+1 index_end += 1 sum += float(s[index_start:len(s)]) print(sum)
true
8a498b1b5fdff128a078ac1323202cfc20403b9b
PurityMaina/DS-Algos
/sorting/insertion_sort.py
770
4.21875
4
#travaerse through array #compare with the next element #if smaller, shift elements in the sorted sublist # insert value in the sorted sublist. def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): element_to_sort = arr[i] sorted_element = i-1 while sorted_element >= 0 and element_to_sort < arr[sorted_element]: arr[sorted_element + 1] = arr[sorted_element] #add item to sorted array sorted_element -= 1 # incrementally sort down the list arr[sorted_element + 1] = element_to_sort #if it is greater than, move up and add to sorted element # Driver code to test above arr = [12, 11, 13, 5, 6] insertionSort(arr) for i in range(len(arr)): print("% d" % arr[i]) #O(n)
true
9500244673783d7244a36652fcf8c1e7318c7583
PurityMaina/DS-Algos
/challanges/permutations.py
891
4.25
4
# produces all permutations (ways to arrange) of a given list of items # ________________ Using Itertools ________________ import itertools def permutations(n): for i in itertools.permutations(n): print(i) n = ['A', 'B', 'C'] permutations(n) # ________________ Using Loops ________________ def permutation(n): if len(n) == 0: return [] # one permuatation is possible if len(n) == 1: return [n] temp = [] for i in range(len(n)): # Iterate the input index = n[i] # Generate the remaining list given index remaining = n[:i] + n[i+1:] # stop at current element + start at the next element # Generate permutation for remaining elements starting with p for p in permutation(remaining): temp.append([index] + p) return temp n = ['A', 'B', 'C'] for p in permutation(n): print(p)
true
fb29a2331e84c4007535568abd67faa36dd9665c
Javaria-Ghafoor/MMP-II
/Numerical Accuracy/Variables/3_Integers.py
1,422
4.25
4
# dividing with zero exception try: print("Let's calculate x/y :P") x = input('Enter x: ') y = input('Enter y: (enter 0 :3)') z = x / y # exception thrown on this line if y == 0 print(z) except: print('you cannot divide with zero') # Integer Operations: """ playing with '+', '-', '*', '/' operators while learning how the value returned by the expression on the right side of the assignment operator '=' is assigned to the left hand side """ x = 3 print(x) x = x + 6 - 2*x print(x) y = int(4/x) # because I want y to be an integer print(y) # the remainder operator '%' x = -2 y = -5 % x print(y) # note that the remainder is of the same sign as of the divisor x # Built in Functions: x = abs(-3) # absolute (positive) value print(x) x = int(4.56) # type conversion to int print(x) x = divmod(-5, 3) # divmod(a, b) => (a/b, a%b) note: the output is a tuple print(x) x = pow(3, 6) # pow(a, b) => 3^6 or 3**6 # Formatted Output: """ %d or %<width>d note: if width is too small, the minimum necessary width to print the certain integer is used e.g. printing 12345678 in width 3 (as portrayed in code ahead) results in 12345678 to take its minimum required amount of width i.e. 8 to be printed """ print('%d %d' % (123, 12345678)) print('%7d %3d' % (123, 12345678))
true
33677a4b49b67b35d67e9e41fb72965a753246c1
staufferl16/Programming111
/filestats.py
940
4.28125
4
""" Author: Leigh Stauffer Project Number: 4-1 File Name: filestats.py This program prompts the user for a file name and outputs the number of characters, words, and lines in the file. If the file does not exist, however, the program will retrun an "ERROR: File does not exist!" message. """ #Import necessary files to use the isfile function import os.path #Gather inputs and set temporary variables for calculations about file stats fileName = input( "Enter the file name: ") word = 0 character = 0 lines = 0 #Performing functions for calculating and printing the file stats if not os.path.isfile(fileName): print( "ERROR: the file does not exist!") else: inputFile = open( fileName, "r") for line in inputFile: character += len( line) word += len( line.split()) lines += 1 print( "There are", character, "characters.") print( "There are", word, "words.") print( "There are", lines, "lines.")
true
6484b06e1ff5e3da1f47a61fcc022a1b114dcaae
DomenOslaj/geography-game
/game.py
1,165
4.375
4
# A local gaming company contacted you to build a game for them. It is a simple geography quiz where a user has to # guess the capital city of some country import random capital_city_dict = {"Austria": "Vienna", "Slovenia": "Ljubljana", "Italy": "Rome", "Germany": "Berlin", "Croatia": "Zagreb", "Hungary": "Budapest"} # ask user for capital city of that state def user_guess(): guess = input("Game: What is the capital city of {0}? \n".format(random_state)) print("User: {0}". format(guess)) return guess.lower() # play game def play_game(guess): while True: if capital_city_dict[random_state].lower() == guess(): print("Game: You are correct!") break else: print("Game: Not correct, try again.") # opening selection while True: # chose random state random_state = random.choice(list(capital_city_dict)) selection = input("Would you like to A) play a game, B) exit: ") if selection.lower() == "a": play_game(user_guess) elif selection.lower() == "b": break else: print("Only A) and B) possibilities to choose from!")
true
2994c6b2bb23ab40a284167bf6fc69d247882c3d
eduardo-jh/HW18-Matrix-algebra-in-biosystems
/q2_jacobi.py
2,009
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ BE523 Biosystems Analysis & Design HW18 - Question 2. Jacobi method to solve x = A⁻¹*b Created on Sun Mar 21 02:52:49 2021 @author: eduardo """ import numpy as np def jacobi(A, b, N=25, x=None): """ Solves the equation Ax=b via the Jacobi iterative method, max iterations approach A: array, the matrix b: array, the vector N: int, max iterations x: array, initial iteration for x""" # Create an initial guess if needed if x is None: x = np.zeros(len(A[0])) # Create a vector of the diagonal elements of A and substract them from A D = np.diag(A) R = A - np.diagflat(D) # Iterate for N times for i in range(N): x = (b - np.dot(R, x)) / D return x def jacobi_conv(A, b, maxiter=25, tol=1e-3, x=None): """ Solves the equation Ax=b via the Jacobi iterative method, tolerance approach A: array, the matrix b: array, the vector maxiter: int, max iterations tol: float, max tolerance x: array, initial iteration for x""" # Create an initial guess if needed if x is None: x = np.zeros(len(A[0])) # Create a vector of the diagonal elements of A and substract them from A D = np.diag(A) R = A - np.diagflat(D) x_prev = x + 2*tol # Use 2*tol to make sure it is greater than tol diff = abs(max(x-x_prev)) # The max value of the array of differences iters = 0 while diff > tol and iters < maxiter: iters += 1 x_prev = x x = (b - np.dot(R, x)) / D diff = abs(max(x-x_prev)) # print(iters, x, diff, (x-x_prev)) return x A = np.array([[2, 1], [5, 7]]) b = np.array([11, 13]) guess = np.array([1, 1]) print("Using the max iterations approach") x = jacobi(A, b, 25, guess) print("A :") print(A) print("b :", b) print("x :", x) print("Using the convergence approach") x = jacobi_conv(A, b, 25, 1e-3, guess) print("A :") print(A) print("b :", b) print("x :", x)
true
f075caacc1f58a8eacab2925dcfc04209dc17c1d
NagiLam/MIT-6.00.1x_2018
/Week 2/PS2_Problem1.py
1,639
4.21875
4
""" Problem Set 2 - Problem 1 Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal monthlyPaymentRate - minimum monthly payment rate as a decimal For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print Remaining balance: 813.41 instead of Remaining balance: 813.4141998135 So your program only prints out one thing: the remaining balance at the end of the year in the format: Remaining balance: 4784.0 A summary of the required math is found below: Monthly interest rate= (Annual interest rate) / 12.0 Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance) Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) """ remainBalance = 0 monthlyInterestRate = annualInterestRate / 12.0 tempBalance = balance minMonthlyPay = 0 monUnpaid = 0 for i in range (12): minMonthlyPay = monthlyPaymentRate * tempBalance monUnpaid = tempBalance - minMonthlyPay tempBalance = monUnpaid + (monthlyInterestRate * monUnpaid) remainBalance = round(tempBalance, 2) print("Remaining Balance: " + str(round(remainBalance, 2)))
true
6b0276f8959bd340aa4b552e53a3efea615555ae
omaryahir/taller_python
/sentenciaif.py
989
4.1875
4
# -*- encoding: utf8 -*- print "Comparador de años" fecha1=int(raw_input("¿En que año estamos?:")) fecha2=int(raw_input("Escriba un año cualquiera:")) """ La siguiente parte utiliza sentencias condicionales encadenadas (el orden no es importante): """ if fecha1 > fecha2: print("Desde el año %s han pasado %s años" % (fecha2, (fecha1-fecha2))) elif fecha1 < fecha2: print("Para llegar al año %s faltan %s años" % (fecha2, (fecha2-fecha1))) else: print("¡Son el mismo año!") """ El siguiente programa es para la diferencia entre fechas de un año """ if fecha1 - fecha2 == 1: print("Desde el año %s han pasado 1 año " % (fecha2)) elif fecha1 > fecha2: print("Desde el año %s han pasado %s años " % (fecha2, fecha1-fecha2)) elif fecha1 - fecha2 == -1: print("Para llegar al año %s falta 1 año " % (fecha2)) elif fecha1 < fecha2: print("Para llegar al año %s faltan %s años " % (fecha2, fecha2-fecha1)) else: print("¡Son el mismo!")
false
649344dbf77413bf7b2a1c87b4f6a3a0c7ae0af7
Chris-Draper/interview-prep
/leet-code/easy/reverseWordsShort.py
548
4.28125
4
''' Given a string, you need to reverse the order of characters in each word within a sentence while still reserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string. ------------------ Spend time understanding the one liner solutions for this problem 1. return " ".join(map(lambda x: x[::-1], s.split())) 2. return ' '.join([i[::-1] for i in s.split()]) '''
true
b23fd7377870d43da754148ffaa92e23227e6d0d
naswfd/data_structures_-_algorithms
/palindrome_unary
375
4.34375
4
#!/usr/bin/env python3.6 def is_palindrome(s): return all(s[i] == s[~i] for i in range(len(s)//2)) print(is_palindrome("tattarrattat")) #~ is the bitwise complement operator in python which essentially calculates -x - 1 #So for i = 0 it would compare s[0] with s[len(s) - 1], for i = 1, s[1] with s[len(s) - 2] #all will return True only when all the elements are True
false
ff499ea31c549fb8aff0ef22b609e69d457c4f94
bhargav-inthezone/Ineuron_assignments
/python_basic_programming_assignment/Programming_Assignment6/Question5.py
291
4.1875
4
'''Question5) Write a program to find cube sum of 1st n natural numbers?''' n = int(input("Enter a natural number:")) def cube_sum(num): sum = 0 for i in range(1,num+1): sum += i**3 return sum if n<=0: print("Enter a natural number :") else: print(cube_sum(n))
true
7d399d984d740cc791f3b627c334031091df4f96
bhargav-inthezone/Ineuron_assignments
/python_basic_programming_assignment/Programming_Assignment4/Question5.py
219
4.25
4
'''Question5) Write a program to sum of natural numbers?''' number = int(input("Enter a natural number:")) sum = 0 for i in range(1,number+1): sum = sum+i print("Sum on Natural numbers for the given number = ", sum)
true
9d2b94bfb5a0f74f41e4738d754f91bec97a2d5a
bhargav-inthezone/Ineuron_assignments
/python_basic_programming_assignment/Programming_Assignment7/Question3.py
737
4.40625
4
'''Question3 ) Write a program for array rotation?''' n = int(input("Enter the number of elements required: ")) array = [] for i in range(0, n): element = input("Enter the element: ") array.append(element) print("Before rotation :" , "\narray = ", array) steps = int(input("Enter a positive number for left rotation and a negative number for right rotation: ")) size = len(array) def rotate_array(array , steps, size): if steps >0: array[:] = array[steps:size] + array[0:steps] elif steps <0: steps = size + steps array[:] = array[steps:size] + array[0:steps] else: array = array return array print("After rotation :" , "\narray = ", rotate_array(array, steps, size))
true
1ac19f126acbdc2aa8121f2606be0e8714677f99
tiilde/RAD_em_Python
/Manipulando-Strings/deTrasPraFrente.py
234
4.28125
4
# 5. Faça um programa que leia o nome do usuário e mostre o nome de trás para frente, utilizando somente letras maiúsculas. nomeUsuario = input('Digite seu nome: ') nomeInvertido = nomeUsuario[:: -1].upper() print(nomeInvertido)
false
0e109ec452f15c01a98313cfb022bb556a4a6698
tiilde/RAD_em_Python
/Manipulando-Strings/imprimirVertical.py
417
4.15625
4
# 6. Faça um programa que leia o nome do usuário e o imprima na vertical, em forma de escada, usando apenas letras maiúsculas. # Exemplo: # Nome = Vanessa # Resultado gerado pelo programa: # V # VA # VAN # VANE # VANES # VANESS # VANESS A nomeConcatenado = '' nome = input('Digite seu nome: ') for l in range(0, len(nome)): nomeConcatenado = nomeConcatenado + nome[l] print(nomeConcatenado.upper())
false
1e60e28bb94b0595a1646c32862a65fd772a58b6
andrewwhite5/CS-Unit-5-Sprint-3-Algorithms
/module2_Recursive-Sorting/quick_sort.py
1,337
4.40625
4
# helper function conceptual partitioning def partition(data): # takes in a single list and partitions it in to 3 lists left, pivot, right # create 2 empty lists (left, right) left = [] right = [] # create a pivot list containing the first element of the data pivot = data[0] # for each value in our data starting at index 1: for value in data[1:]: # check if value is less than or equal to the pivot if value <= pivot: # append our value to the left list left.append(value) # otherwise (the value must be greater than the pivot) else: # append our value to the right list right.append(value) # returns the tuple of (left, pivot, right) return left, pivot, right # quick sort that uses the partitioned data def quicksort(data): # base case if the data is an empty list return an empty list if data == []: return data # partition the data in to 3 variables (left, pivot, right) left, pivot, right = partition(data) # recursive call to quicksort using the left # recursive call to quicksort using the right # return the concatination quicksort of lhs + pivot + quicksort of rhs return quicksort(left) + [pivot] + quicksort(right) print(quicksort([5, 9, 3, 7, 2, 8, 1, 6]))
true
9bbf6f4556f2ca65b29995117e23094130f59212
dabarreto/automate_boring_stuff
/python/04_basic_flow_control_concepts.py
881
4.25
4
# Boolean Values # Comparison Operators # Boolean Operators # Boolean data type has only two values: True and False. # Like any other value, boolean values are used in expression and can be stored in variables. spam = True # Comparison Operators # ---------------------------------- # == Equal to # != Not equal to # < Less than # < Greater than # <= Less than or equal to # >= Greater than or equal to # ---------------------------------- 42 == 42 42 == 'Hello' 2 != 3 42 < 100 42 >= 100 42 <= 42 myAge = 26 myAge < 30 42 == '42' 42.0 == 42 # Boolean Operators: and, or, not. # The "and" operator evaluates an expression to rue if both boolean values are True. Otherwise it evaluates to False. True and True True and False False and True # The "or" operator # The "not" operator myAge = 26 myPet = 'cat' myAge > 20 and myPet == 'cat'
true
bdc6ed4396b1597e584af34a87fae3c71949b786
PramilaPuttu/Python-for-Everybody
/Programming for Everybody (Getting Started with Python)/Week 5/Chapter3-Assignment3.1.py
657
4.28125
4
3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly. hrs = raw_input("Enter Hours:") h = float(hrs) rate = raw_input("Enter Rate:") r = float(rate) if h>40: result = 40*r+(h-40)*r*1.5 else: result = h*r print (result)
true
d3645b113a8d4d27aabb2a3f4728052c11e05aa5
yannickbf-prog/python
/p6e1.py
387
4.125
4
#Yannick p6e1 Escribe un programa que te pida palabras y las guarde en una lista. Para terminar de introducir palabras, simplemente pulsa Enter. El programa termina escribiendo la lista de palabras. palabras=[] entrada=input("pasame una palabra") while(entrada!=""): palabras.append(entrada) entrada=input("pasame una palabra") print("la lista de palabras es ",palabras)
false
2641c4dcae1640ef81fd29881a15b453ea80deba
yannickbf-prog/python
/p7e4.py
428
4.3125
4
#Yannick p7e4 Escribe un programa que pida una frase, y le pase como parámetro a una función dicha frase. La función debe sustituir todos los espacios en blanco de una frase por un asterisco, y devolver el resultado para que el programa principal la imprima por pantalla def nuevaFrase(frase1): frase1 = frase1.replace(" ", "*") print(frase1) frase = input("Escribe una frase ") nuevaFrase(frase)
false
0ea75d81511a442641e4a596011ef2331d2d4274
2020rkessler/main-folder
/Project_Two.py
2,515
4.15625
4
#Psuedocode # #classwork_grade = input("Whats your total class work grade?")/100 # #homework_grade = input("Whats your total homework grade?")/100 # #class_participation_grade = int(input("Whats your total class participation grade?"))/100 # #test_grade = input("Whats your total test grade?")/100 # #number_of_tests = input("How many tests how you taken thus far?") # #test_aim = input("What do you aim to get on your next test?")/100 # #new_test_grade = number_of_tests/(number_of_tests+1) *(test_grade) + (1/(number_of_tests+1)*test_aim # #test_weighting = 0.50 #classwork_weighting = 0.15 #homework_weighting = 0.25 #class_participation_wieghting = .10 # #total_grade = new_test_grade * test_weighting + classwork_grade * classwork_weighting + homework_grade*homework_weighting + class_participation_grade *class_participation_wieghting # #total_grade = total_grade*100 # #print ("If you got a " + test_aim +" on the next test, your total grade would be " + total_grade + "%") # def get_user_input(): #get the grades for each section and convert them into a decimal classwork_grade = int(input("Whats your total class work grade?\n"))/100 homework_grade = int(input("Whats your total homework grade?\n"))/100 class_participation_grade = int(input("Whats your total class participation grade?\n"))/100 test_grade = int(input("Whats your total test grade?\n"))/100 number_of_tests = int(input("How many tests how you taken thus far?\n")) test_aim = int(input("What do you aim to get on your next test?\n"))/100 #Calculates the new test score based on what the user hopes to get on their next test new_test_grade = ((number_of_tests/(number_of_tests+1))*(test_grade)) + ((1/(number_of_tests+1))*(test_aim)) #The weighting for tests,classwork,hoemwork, and class participation test_weighting = 0.50 classwork_weighting = 0.15 homework_weighting = 0.25 class_participation_wieghting = .10 #Calculates the total grade total_grade = ((new_test_grade * test_weighting) + (classwork_grade * classwork_weighting) + (homework_grade*homework_weighting) + (class_participation_grade *class_participation_wieghting)) #converts back to a integer total_grade = int(total_grade*100) return test_aim, total_grade #Print the results def print_results(): test_aim, total_grade = get_user_input() print ("If you got a " + str(test_aim * 100) +" on the next test, your total grade would be " + str(total_grade) + "%") print_results()
true
bed36ddc923387717345edabdab5e715372fa06e
2020rkessler/main-folder
/array/code_a_long.py
935
4.53125
5
# Arrays are cool # Created an array arr = ['Estelle', 'Ben', 'Lauren', 'Patches', 'Kyle', "meow"] # how do indexes work? # access last element print("I am the last element", arr[-1]) # access the first element print("I am the first element", arr[0]) # get len of Array print("I have", len(arr), "elements in me") # pop to remove last element arr.pop() print(arr) # remove a certain element arr.remove('Kyle') print(arr) # add something to an array arr.append('Woof') print(arr) # For loop for name in arr: print(name) # While loop count = 0 while len(arr) < count: print(count) count = count + 1 arr2 = ['bork', 'boof', 'foobar', 'fish'] arr3 = arr + arr2 print(arr3) # For loop for name in arr3: print(name) # add to array arr3.append('add me') print(arr3) arr = ['kyle', 'lauren', 'estelle', 'ben'] for names in arr: # turn str into arr name_change = list(names) # cap the first letter name
true
059aa7b20a88c89ffd3b81ce0d537a72b5e67ee9
lincolnjohnny/py4e
/2_Python_Data_Structures/Week_4/example_09.py
347
4.21875
4
# Find the average from the elements of a numeric list numlist = list() while True : inp = input('Enter a number: ') if inp == 'done' : break try: value = float(inp) except: print('Invalid number') continue numlist.append(value) average = sum(numlist)/len(numlist) print('Average is', average)
true
9d5f1d3b206b5723408fade18faa526b54c15e0c
babin-adhikari/8-bit-adder-Python
/convert.py
804
4.1875
4
# Function to change Decimal Number To Binary Number def decimalToBinary(number): # Initializing Variables bit=[] counter=0 actualBinary=[] #Setting counter != 8 so that the binary number be of 8 digits while counter!=8: remainder=number%2 bit.append(remainder) number=number//2 #Quotient linxa counter+=1 # Reversing the List bit to get the required Binary Output for i in range(len(bit)-1,-1,-1): actualBinary.append(bit[i]) return actualBinary # Function to change the List to String def listToString(List): actualNumber="" for i in range(len(List)): actualNumber=actualNumber+str(List[i]) # Returning the int value of the String so that only the true addition is Displayed return actualNumber
true
97a94fd08ff970796e1e4032aae643ed98175058
Melissapdx/calculator-2
/arithmetic_new.py
1,654
4.25
4
"""Math functions for calculator.""" def check_user_input(list1): for i in list1: if not i.isdigit(): print "not a valid number please enter a number" return False return True def make_list_into_float(list1): """ makes list of strings into list into list of floats """ return [float(num) for num in list1] def add(list1): """Return the sum of the two input integers.""" return sum(list1) def subtract(list1): """Return the second number subtracted from the first.""" return list1[0]-sum(list1[1:]) def multiply(list1): """Multiply the two inputs together.""" product = 1 for i in list1: product = i * product return product def divide(list1): """Divide the first input by the second, returning a floating point.""" # Need to turn at least one argument to float for division to # not be integer division quotient = list1[0] for i in list1[1:]: quotient = quotient / i return quotient def square(list1): """Return the square of the input.""" # Needs only one argument return [num*num for num in list1] def cube(list1): """Return the cube of the input.""" # Needs only one argument return [num * num * num for num in list1] def power(list1): """Raise num1 to the power of num and return the value.""" ans = list1[0] for i in list1[1:]: ans = ans ** i return ans # ** = exponent operator def mod(list1): """Return the remainder of num / num2.""" remainder = list1[0] for i in list1[1:]: remainder = remainder % i return remainder
true
2131741c3ac01a8f64cd7a8bf102a094beeff7ed
fykss/python-sandbox
/algorithms/sorting/merge_sort.py
1,059
4.1875
4
# https://www.youtube.com/watch?v=qf82-r9hl2Y&t=992s # https://www.geeksforgeeks.org/python-program-for-merge-sort/ def merge(A: list, B: list): C = [0] * (len(A) + len(B)) # i - index for list A # k - index for list B # n - index for list C i = k = n = 0 while i < len(A) and k < len(B): if A[i] <= B[k]: C[n] = A[i] i += 1 else: C[n] = B[k] k += 1 n += 1 # Copy the remaining elements of A[], if there are any while i < len(A): C[n] = A[i] i += 1 n += 1 # Copy the remaining elements of B[], if there are any while k < len(B): C[n] = B[k] k += 1 n += 1 return C def merge_sort(A: list): if len(A) <= 1: return middle = len(A) // 2 L = [A[i] for i in range(middle)] R = [A[i] for i in range(middle, len(A))] merge_sort(L) merge_sort(R) C = merge(L, R) for i in range(len(A)): A[i] = C[i] B = [5, 2, 7, 3, 1] merge_sort(B) print(*B)
false
93ecd67c7a6a08ac933261f87c474d88b3e8f8a5
fykss/python-sandbox
/data_structures/dictionary/dict_method.py
1,793
4.75
5
# Dictionary method: https://www.geeksforgeeks.org/python-dictionary/ # 1. fromkeys(seq,value):- This method is used to declare a new dictionary from the sequence mentioned in its arguments. # 2. update(dic):- This function is used to update the dictionary to add other dictionary keys. # 3. has_key():- This function returns true if specified key is present in the dictionary, else returns false. # 4. get(key, def_val) :- This function return the key value associated with the key mentioned in arguments. If key is not present, the default value is returned. # 5. setdefault(key, def_value):- This function also searches for a key and displays its value like get() but, it creates new key with def_value if key is not present. # 6. values(): - This function returns a list of all the values available in a given dictionary. # 7. keys(): - Returns list of dictionary dict’s keys # 8. items(): - Returns a list of dict’s (key, value) tuple pairs # 1 numbers = [1, 2, 3, 4, 5] new_dict1 = dict.fromkeys(numbers, 0) # using dict. comprehension new_dict2 = {i: 0 for i in numbers} print(f"New dict 1: {new_dict1}") print(f"New dict 2: {new_dict2}") # using fromkeys() to convert sequence to dict res_dict2 = {key: list(numbers) for key in numbers} print(f"The newly created dict with list values: {str(res_dict2)}") # 5 # Method has two cases: 1) if the key is in dictionary 2) when key is not in the dictionary dict_names = {'A': 'Anna', 'B': 'Bob', 'C': 'Charly'} third_value = dict_names.setdefault('C') print(f"Dictionary: {dict_names}") # Method returns the value of a key print(f"Third_value: {third_value}") fourth_value = dict_names.setdefault('D', 'Dima') print(f"Dictionary: {dict_names}") # Set new (key, value) to the dictionary print(f"Fourth_value: {fourth_value}")
true
a17f26b5611181e6cbc983f6a713582766e236ea
fykss/python-sandbox
/basic/08-functions/main.py
1,410
4.25
4
def printme(str): "This prints a passed string into this function" print(str) return printme("Vlad") # Keyword arguments def printme1(str): "This prints a passed string into this function" print(str) return printme1(str="My string") # Default arguments def printinfo(name, age=35): "This prints a passed info into this function" print("Name: ", name) print("Age ", age) return printinfo(age=50, name="miki") printinfo(name="miki") # Variable-length arguments def printinfo1(arg1, *vartuple): "This prints a variable passed arguments" print("Output is: ") print(arg1) for var in vartuple: print(var) return printinfo1(10) printinfo1(70, 60, 50) # The Anonymous Functions def sum(arg1, arg2): return arg1 + arg2 print("Value of total : ", sum(10, 20)) print("Value of total : ", sum(20, 20)) # Global vs. Local variables total1 = 0 # This is global variable. def sum1(arg1, arg2): # Add both the parameters and return them." total1 = arg1 + arg2 # Here total is local variable. global total2 # Here total is local variable. total2 = arg1 + arg2 print("Inside the function local total : ", total1) print("Inside the function local total : ", total2) return total1 sum1(10, 20) print("Outside the function global total : ", total1) print("Outside the function global total : ", total2)
true
569cc020714eb382cde37cdf8187deb3ba8e862c
MiguelCF06/PythonProjects
/ListsPython/GroceryListApp.py
1,661
4.21875
4
import datetime print("Welcome to the Grocery List App.") now = datetime.datetime.now() print("Current Date and Time: ", end="") print(now.strftime("%m/%d\t%H:%M")) Groceries = ["Meat", "Chesse"] print("You currently have Meat and Cheese in your list.") print() Groceries.append(input("Type of food to add to the grocery list: ").title()) Groceries.append(input("Type of food to add to the grocery list: ").title()) Groceries.append(input("Type of food to add to the grocery list: ").title()) print() print("Here is your grocery list:") print(Groceries) print("Here is your grocery list sorted:") Groceries.sort() print(Groceries) print() print("Simulating grocery shopping...") print() print("Current grocery list: {} items".format(len(Groceries))) print(Groceries) bought = input("What food did you just buy: ").title() Groceries.remove(bought) print("Removing {} from list...".format(bought)) print() print("Current grocery list: {} items".format(len(Groceries))) print(Groceries) bought = input("What food did you just buy: ").title() Groceries.remove(bought) print("Removing {} from list...".format(bought)) print() print("Current grocery list: {} items".format(len(Groceries))) print(Groceries) bought = input("What food did you just buy: ").title() Groceries.remove(bought) print("Removing {} from list...".format(bought)) print() print("Current grocery list: {} items".format(len(Groceries))) print(Groceries) print() print("Sorry, the store is out of {}".format(Groceries[1])) Groceries[1] = input("What would you like instead: ").title() print() print("Here is what remains in your grocery list:") Groceries.sort(reverse=True) print(Groceries)
true
038ff6e817b2a546dc964bdb861c3cc5c19d354d
MiguelCF06/PythonProjects
/Functions/LoanCalculator.py
2,492
4.1875
4
from matplotlib import pyplot def setLoan(): loanAmount = float(input("Enter the loan amount: ")) interest = float(input("Enter the interest rate: "))/100 monthlyPayment = float(input("Enter the desired monthly payment amount: ")) loanInfo = { "Principal": loanAmount, "Rate": interest, "Monthly Payment": monthlyPayment, "Money Paid": 0, } return loanInfo def showInfo(loanInfo, iter): print("\n-----Loan information after {} months.-----".format(iter)) for key, value in loanInfo.items(): print("{}: {:.3f}".format(key, value)) print() def interestAm(loan): loan["Principal"] = loan["Principal"] + loan["Principal"] * loan["Rate"]/12 def makePayment(loan): loan["Principal"] -= loan["Monthly Payment"] if loan["Principal"] > 0: loan["Money Paid"] += loan["Monthly Payment"] else: loan["Money Paid"] += loan["Monthly Payment"] + loan["Principal"] loan["Principal"] = 0 def summary(loan, months, initialLoan): print("Congratulations! You paid off your loan in {} months!".format(months)) print("Your initial loan was ${:.2f} at a rate of {:.2f}%".format(initialLoan, loan["Rate"]*100)) print("Your monthly payment was ${:.2f}.".format(loan["Monthly Payment"])) print("You spent ${:.2f} in total.".format(loan["Money Paid"])) interest = loan["Money Paid"] - initialLoan print("You spent ${:.2f}".format(interest)) def createGraph(data, loan): xValues = [] yValues = [] for point in data: xValues.append(point[0]) yValues.append(point[1]) pyplot.plot(xValues, yValues) pyplot.title("{}% Interest With {} Monthly Payment".format(loan["Rate"]*100, loan["Monthly Payment"])) pyplot.xlabel("Month Number") pyplot.ylabel("Principal of Loan") pyplot.show() print("Welcome to the Loan Calculator App\n") myLoan = setLoan() months = 0 initialLoan = myLoan["Principal"] showInfo(myLoan, months) dataPlot = [] input("Press 'Enter' to begin paying off your loan.") while myLoan["Principal"] > 0: if myLoan["Principal"] > initialLoan: break months += 1 interestAm(myLoan) makePayment(myLoan) dataPlot.append((months, myLoan["Principal"])) showInfo(myLoan, months) if myLoan["Principal"] <= 0: summary(myLoan, months, initialLoan) createGraph(dataPlot, myLoan) else: print("\nYou will NEVER pay off your loan!!!") print("You cannot get ahead of the interest! :-(")
true
44cc45164e738424375ba206fef51bb4838aed85
MiguelCF06/PythonProjects
/MoreLoops/FactorGenerator.py
692
4.1875
4
print("Welcome to the Factor Generator App\n") flag = True while flag: factors = [] number = int(input("Enter a number to determine all factors of that number: ")) print() print("The factors of {} are:".format(number)) for i in range(1, number + 1): if number % i == 0: factors.append(i) for factor in factors: print(factor) print() print("In summary:") for i in range(int(len(factors)/2)): print("{} * {} = {}".format(factors[i], factors[-i-1], number)) print() answer = input("Run again? (y/n): ").lower() if answer != "y": flag = False print("Thank you for using the program. Have a great day.")
true
9461f9bb221e92cbe5d26547357bda517df0b634
MiguelCF06/PythonProjects
/ListsPython/GradeSorter.py
854
4.1875
4
print("Welcome to the Grade Sorter App") print() grades = [] print() grades = [] grades.append(int(input("What is your first grade (0-100): "))) grades.append(int(input("What is your second grade (0-100): "))) grades.append(int(input("What is your third grade (0-100): "))) grades.append(int(input("What is your fourth grade (0-100): "))) print() print("Your grades are: {}".format(grades)) print() grades.sort(reverse=True) print("Your grades from highest to lowest are: {}".format(grades)) print() print("The lowest two grades will now be dropped") lowerGrade1 = grades.pop() lowerGrade2 = grades.pop() print("Removed grade: {}".format(lowerGrade1)) print("Removed grade: {}".format(lowerGrade2)) print() print("Your remaining grades are: {}".format(grades)) grades.sort() best = grades.pop() print("Nice work! Your highest grade is a {}".format(best))
true
e1bc458ff5d7af08fe6aa52b1a77397660e4a54c
lungen/algorithms
/chapter-4/423-01-palindromChecker.py
1,705
4.375
4
""" Write a function that takes a string as a parameter and returns True if the string is a palindrome, False otherwise. Remember that a string is a palindrome if it is spelled the same both forward and backward. for example: radar is a palindrome. for bonus points palindromes can also be phrases, but you need to remove the spaces and punctuation before checking. for example: madam i’m adam is a palindrome. Other fun palindromes include: • kayak • aibohphobia • Live not on evil • Reviled did I live, said I, as evil I did deliver • Go hang a salami; I’m a lasagna hog. • Able was I ere I saw Elba • Kanakanak – a town in Alaska • Wassamassaw – a town in South Dakota """ # kayak def palindromChecker(s): s = str(s) s = s.lower() #remove punctation recursive def remove_puncation(string): if len(string) == 1: if string[0] in "',.;:" or string[0] == ' ': return '' else: return string[0] else: if string[0] in "',.;:" or string[0] == ' ': return remove_puncation(string[1:]) else: return string[0] + remove_puncation(string[1:]) s = remove_puncation(s) if len(s) == 1: return True else: if s[0] == s[-1]: return palindromChecker(s[1:-1]) else: return False #print(palindromChecker('kayak')) #print(palindromChecker('aibohphobia')) #print(palindromChecker('aibohphobia')) print(palindromChecker('live not on evil')) print(palindromChecker("Reviled did I live, said I, as evil I did deliver'"))
true
cc90012c15eaef0c750234a02676072d68e1e1cd
python-practice-b02-927/kuleshov
/lab2/ex5.py
431
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 10 09:44:48 2019 @author: student """ import turtle def square(a): for i in range(4): turtle.forward(a) turtle.right(90) n = 10 a = 30 c = 30 turtle.shape('turtle') for i in range(n): square(a) turtle.penup() turtle.backward(c) turtle.left(90) turtle.forward(c) turtle.right(90) turtle.pendown() a += 2*c
false
12e21a4feb5eb6faa245bf19d3696f90e36b67be
maithili16/Final-Year-Project
/mouse-click.py
347
4.125
4
# How to add mouse events import tkinter as tk def left_click(event): print("leftClick") def right_click(event): print("rightClick") w = tk.Tk() f = tk.Frame(w, width=300, height=300) l = tk.Label(w, text="Hello world") f.bind("<Button-1>", left_click) f.bind("<Button-3>", right_click) f.pack() l.pack() # event loop w.mainloop()
false
56b4dc65bc2a7d3cbc0aebbeed73f91ea818b6c5
perezsergioace/programming-concepts-class
/midterm-programs/bonus-question.py
928
4.5625
5
# BONUS 10 Points: (Partial points possible for this bonus) # Write a program that converts Celsius temperatures to Fahrenheit temperatures. The formula is as follows: # F = C + 32 # The program should ask the user to enter a temperature in Celsius, then display the temperature converted to Fahrenheit. # To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32. # Example: (30°C x 1.8) + 32 = 86°F # Initializing variables celsius = 0.0 fahrenheit = 0.0 # Asking useer to enter a temperature in celsius celsius = float(input('Enter Celsius Temperature to be converted: ')) # Calculating the conversion from celsius to fahrenheit by taking the celcius entered multiplying it by 1.8 and then adding 32 fahrenheit = (celsius * 1.8) + 32 # Displaying the temperature converted to Fahrenheit print('The temperature converted to Fahrenheit is:', int(fahrenheit), 'degrees')
true
a83497606fece0b2e97694642eabd2e2aeb2021a
squiddefeater/python-projects
/waffles.py
525
4.15625
4
like_waffles = input("Do you like waffles?") if likes_waffles == 'yes': print ("yeah we like waffles!") likes_pancakes = input("do you like pancakes") if likes_pancakes == 'yes': print("yeah we like pancakes") likes_french_toast = input("do you like french toast") if likes_french_toast == 'yes': print("yeah we like pancakes") else: print("french toast is BOSS") else: print("well we like pancakes") else: print("well we like waffles")
false
cc1ae1dcc12132f8b092aa732a99d349e8ff6395
ww35133634/chenxusheng
/ITcoach/sixstar/基础班代码/3_while循环/lx_09_if分支语句语法格式三.py
805
4.125
4
""" 演示if分支语句语法格式三 """ # if 条件: # 代码片段 # elif: # 代码片段 # 多种情况的应用场景,,,bobo,,周一到周日,,七天,,七种情况,,七种计划,, # elif else if 多种情况 day = input('今天是周几:') if day == '周一': print('bobo选择了读书') elif day == '周二': print('bobo选择了看电视') elif day == '周三': print('bobo选择了打游戏') elif day == '周四': print('bobo选择了爬山') elif day == '周五': print('bobo选择了去露营') elif day == '周六': print('bobo选择了学习') elif day == '周日': print('bobo选择了休息') else: # 前面都不满足 那么我就来执行 可有可无 print('请按照正规的方式输入')
false
af6b610ec1fdefe0f84cf85ebb030d43b5010ab6
ww35133634/chenxusheng
/ITcoach/sixstar/基础班代码/5_列表-元组/列表/lx_03_列表的常规操作.py
1,573
4.34375
4
""" 列表的操作 """ # 0 1 2 3 4 5 # list1 = [1,2,3,4,5,6] # 保存多个数据的容器,, # 使用append去添加数据 并且是默认添加到最后的 # list1.append(8) # ctrl 鼠标点击 返回值 # print(list1) # 使用insert插入数据,, # list1.insert(4,8) # 插入(索引,数据) # print(list1) # 在列表1后面列表2 # list1 = [1,2,3,4,5,6] # list2 = [7,8,9] # list1.extend(list2) # print(list1) # pop 删除 默认最后一位 # list1 = [1,2,3,4,5,6] # list1.pop() # print(list1) # 列表清空 # list1 = [1,2,3,4,5,6] # list1.clear() # print(list1) # remove 删除第一个指定的数据 # list1 = [1,2,3,4,5,1] # list1.remove(1) # print(list1) # len(列表)列表的长度里面有多少个数据 和count() # list1 = [1,2,3,4,5,6] # print(len(list1)) # list1 = [1,2,3,1,1,2,4,5] # print(list1.count(1)) # 使用sort()排序 # list1 = [1,2,5,3,4,6] # list1.sort() # 进行了排序之后,,升序的效果 # print(list1) # list1 = [1,2,5,3,4,6] # list1.sort(reverse= True) # 降序的效果 # print(list1) # 列表推导式 # list1 = [for i in range(1,101)] # for 循环 # for i in range(1,11): # range(1,11)包前不包后1,2,3,4,5,6,7,8,9,10 # print(i) # 被控制着执行次数 # 列表推导式 # 创建一个列表1-100 # list1 = [1,2,3,4,.....,100] # i for循环得到数据给i # list1 = [i for i in range(1,101)] # print(list1) # i for循环得到数据给i 只拿偶数 list1 = [i for i in range(1,101) if i % 2 == 0] print(list1)
false
33aa2db16351bd2350dceca2580a88cfc5aa4539
ww35133634/chenxusheng
/ITcoach/sixstar/基础班代码/11_模块和包-函数深入/函数进阶/lx_02_关键字参数.py
699
4.28125
4
""" 关键字参数 """ # def demo(a = 1, b = 2): # print(a) # 1 5 # print(b) # 2 10 # # demo(5) # 默认形参 # def demo(a = 1, b = 2): # print(a) # 1 5 # print(b) # 2 10 # # # 关键字参数 关键字实参 # demo(b = 5) # b = 5 # 没有默认参数的形况下 位置形参 def demo(a, b): print(a) # 1 5 print(b) # 2 10 # 位置实参 关键字参数 关键字实参 # demo(1, b = 5) # b = 5 # 位置参数不能够跟在关键字参数的后面 demo(b = 5, a =1) # b = 5 , 1 # 顺序关系:没有默认参数的形况下 位置实参 关键字实参
false
8f765cad6e147f3184806b62d59ec66f1ab40634
ww35133634/chenxusheng
/ITcoach/sixstar/基础班代码/6_字符串/lx_06_字符串的查询与替换.py
1,379
4.125
4
""" 演示字符串的查询与替换 """ """ find(字符串, 开始索引, 结束索引) 查询 rfind(字符串, 开始索引, 结束索引) 右侧查询 index(字符串, 开始索引, 结束索引) 查询 rindex(字符串, 开始索引, 结束索引) 右侧查询 replace(原字符, 新字符, 替换数量) 替换 expandtabs() \t替换空格 """ # 01234567891011 21 str1 = 'hello python, hello world' # 根据数据拿到他的索引值 # print(str1.find('o')) # 默认从索引0开始寻找 找到一个就满足了 # print(str1.find('a',5,11)) # right 从右边开始 # print(str1.rfind('o')) # 默认从右边开始 找到一个就满足了 # index 就是找不到就发脾气 就报错, find -1 # index(字符串, 开始索引, 结束索引) # rindex(字符串, 开始索引, 结束索引) # replace(原字符, 新字符, 替换数量) 替换 正则也有会替换 str1 = 'hello python, hello world' # print(str1.replace('o','O')) # 默认全部替换 print(str1.replace('o','O',-2)) # expandtabs() \t替换空格 # # print(str1.find('a')) # 不存在 得到-1 # print(str1.index('a')) # 不存在 报错 异常处理的东西
false
dfa6f83a85e950376bb6b0211fbca386e2f0b6ab
Misaelsky/pythoncrs
/Operacionesmat/operacionesmat.py
640
4.1875
4
# Realizar sum print("Escribe un numero:") num1 = input() num2 = input("Escribe otro numero:") # Operacion de suma suma = float(num1) + float(num2) resta = float(num1) - float(num2) multiplicacion = float(num1) * float(num2) division = float(num1) / float(num2) potencia1 = float(num1) ** float(num2) potencia2 = pow(float(num1), float(num2)) raiz_cuad = pow(float(num1), float(1/2)) raiz_cub = pow(float(num1), float(1/3)) residuo = float(num1) % float(num2) # Impresiones print(suma) print(type(suma)) print(resta) print(multiplicacion) print(division) print(potencia1) print(potencia2) print(raiz_cuad) print(raiz_cub) print(residuo)
false
ca5f65aeccac84eee497c439d6ce5c691583767b
mjhcodes/pdxcodeguild
/python/lab4.py
987
4.125
4
import random def printPrediction(): """randomly selects a prediction from the list of options""" predictions = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"] print(f"\n{random.choice(predictions)}\n") # welcome message - displayed once print("\nWelcome to Magic 8 Ball!") def main(): """prompts user for question, displays prediction, then asks whether to repeat or not""" while True: input("\nWhat is your question? ") printPrediction() repeat = input("Would you like to ask another question? (Enter 'done' to exit) ").lower() if repeat == "done": print("\nIt is written...\n") break main()
true
f1d75f397ba294ba299707474d6438919e90c4e2
mjhcodes/pdxcodeguild
/python/practice1.py
1,575
4.1875
4
# Practice 1 - Fundamentals # Problem #1 def is_even(num): """accepts number and returns True, if the number is even; else, False""" if num % 2 == 0: return True else: return False # print(is_even(5)) # print(is_even(6)) # ---------------------------------------------------------------- # Problem #2 def opposite(a, b): """accepts two numbers and checks if one is positive and the other is negative; if so, returns True; else, returns False""" if (a < 0 and b >= 0) or (a >= 0 and b < 0): return True else: return False # print(opposite(10, -1)) # print(opposite(2, 3)) # print(opposite(-1, -1)) # ---------------------------------------------------------------- # Problem #3 def near_100(num): """accepts a number and returns True, if the number is less than 10 from 100; else, returns False""" num = abs(100 - num) if num < 10: return True else: return False # print(near_100(50)) # print(near_100(99)) # print(near_100(105)) # ---------------------------------------------------------------- # Problem #4 def maximum_of_three(a, b, c): """accepts three numbers and returns the maximum""" max_num = max(a, b, c) return max_num # print(maximum_of_three(5, 6, 2)) # print(maximum_of_three(-4, 3, 10)) # ---------------------------------------------------------------- # Problem #5 def print_powers_of_2(): """prints out the powers of 2 from 2^0 to 2^20""" i = 0 while i <= 20: if i == 20: print(2 ** i, end="\n") break print(2 ** i, end=", ") i += 1 # print_powers_of_2()
true
006ac91a8273e487516f11ad6e1f808cfebd333f
saurabhshastri/python-training
/container_data_types/iterator.py
1,034
4.3125
4
numbers = [1,2,3,4,5] # print(dir(numbers)) # it = iter(numbers) # print(it) # print(it.__next__()) # print(it.__next__()) # print(next(it)) # print(next(it)) # print(next(it)) # print(it.__next__()) # all dunder methods called be called as a normal function as well.. # eg: instead of it.__next__() we can also use next(it) #custome iterator # Fibonacci series: 0 1 1 2 3 5 8 13 class Fibonacci: def __init__(self, max): self.max = max self.prev = 0 self.cur = 1 def __iter__(self): return self def __next__(self): if self.prev < self.max: result = self.prev self.prev, self.cur = self.cur, self.prev+self.cur return result else: raise StopIteration f = Fibonacci(35) for i in f: print(i) # it = iter(f) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it)) # print(next(it))
false
2a3f40f7b979fdadd43662125ba6322afb5b403b
Ashaba42/Official-JTC-Class-Code
/Challenges/05_bootcamp_scripts/nested_loop_practice.py
1,686
4.5625
5
# loops inside loops days = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday', 'sunday'] # outer loop for day in days: print(day) # for each day, print each letter individually # inner loop for letter in day: print(letter) # not nested, put prints first letter of each day for day in days: print(day) print(day[0]) # outer loop for day in days: print(day) # for each day, print each letter individually # inner loop for letter in day: print(letter.upper()) # nested loops with range() for outer_var in range(3): for inner_var in range(4): print(f'outer: {outer_var}, inner: {inner_var}') # multiple loops, no nesting for outer_var in range(3): print(f'outer: {outer_var}') for inner_var in range(4): print(f'inner: {inner_var}') # printing the looping variable after the loop is done print(inner_var) print(inner_var) print(inner_var) print(inner_var) # logic inside loops days = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday', 'sunday'] # loop through days, print whether it's weekend or not for day in days: #if the day variable starts with s if day.startswith('s'): print(f'{day} is a weekend') else: print(f'{day} is a weekday') # XTREME NESTING # loop through days, print whether it's weekend or not # if it is a weekday, print 'contains o' if th letter o is in the day for day in days: #if the day variable starts with s if day.startswith('s'): print(f'{day} is a weekend') else: print(f'{day} is a weekday') if 'o' in day: print('contains o') else: print('no o') # break 'breaks you out of the loop' for day in days: print(day) if day.startswith('w'): break print('done with loop')
true
f88643628739e6e2a905ed4647011097f81a3b1c
rosanmaharjan21/pythonclass
/assignment.py
1,687
4.21875
4
# assignment num 1 to login # userName: "admin" # password: "admin002" # # userName = str(input("Enter the userName: ")) # password = str(input("Enter the password: ")) # if userName == "admin" and password == "admin002": # print("welcome") # else: # print("Enter the valid username and password") # # assignment num 2 to find simple interest # principle = int(input("Enter the principle amount: ")) # time = int(input("Enter the time: ")) # rate = int(input("Enter the rate: ")) # SI = (principle * time * rate) / 100 # # print("The Simple Interest is ", SI) # assignment no 3 preparing markSheet studentName = str(input("Enter the name of student: ")) print("The name of student is", studentName) englishMarks = int(input("Enter the marks scored in English: ")) if englishMarks>100: print("Please enter marks between 0-100") mathMarks = int(input("Enter the marks scored in Math: ")) scienceMarks = int(input("Enter the marks scored in Science: ")) nepaliMarks = int(input("Enter the marks scored in Nepali: ")) socialMarks = int(input("Enter the marks scored in Social: ")) totalMarks = englishMarks + mathMarks + scienceMarks + nepaliMarks + socialMarks percentage = (totalMarks / 500) * 100 print("The total marks you scored is: ", totalMarks) print("The percentage you scored is: ", percentage) if englishMarks < 35 or mathMarks < 35 or scienceMarks < 35 or nepaliMarks < 35 or socialMarks < 35: print("You are fail") else: print("You are pass") if percentage < 45: print("Third") elif percentage < 60: print("second") elif percentage < 75: print('first') else: print("top") if englishMarks < 35: print("Your are fail in english")
true
2bd75a5690aebb35365cab23b379d3fa6588d46b
ttur/PythonInBrowser
/public/examples/session2/flower.py
2,202
4.5
4
##### FILE ##### # flower.py # Let's draw a flower import turtle t = turtle.Turtle() ##### INFO ##### # Firstly, let's make the drawing a bit faster. # It's possible to adjust the speed of the turtle with commad 'speed(0)' # In addition, the drawing color can be changed. t.speed(0) t.color("red") ##### EXERCISE ##### # Let's draw something that perhaps resembles a flower # It's handy to use a for loop for that. petalwidth = 50 # add / change here any number between 10 and 200 direction1 = 181 # you can modify these later, but now leave them with values 181 direction2 = 178 # and 178 for i in range (100): # Let's start with going forward the amount of petalwidth # and add the value of the iterator. # That will give us nice shape for the petals t.forward(petalwidth + i) # Let's turn back t.left(direction1) # and draw the same length t.forward(petalwidth + i) # The for loop now repeats this drawing 100 times. # Click 'Run' and see what happens. # It's possible to change the color of drawing in the middle of code # Uncomment the following line # t.color("green") # Then uncomment the following lines # Which does the same drawing as the first for loop # but this time with different color and turning to direction2. # for i in range (0, 100): # t.forward(petalwidth+i) # t.left(direction2) # t.forward(petalwidth + i) # Click again 'Run' and see what kind of flower is going to appear. # Then uncomment all the following lines and see what kind of flower there is. # t.color("blue") # for i in range (0, 100): # t.forward(petalwidth+i) # t.left(direction1) # t.forward(petalwidth + i) # t.color("pink") # for i in range (0, 100): # t.forward(petalwidth + i) # t.left(direction1) # t.forward(petalwidth + i) # t.color("orange") # for i in range (0, 100): # t.forward(petalwidth+i) # t.left(direction1) # t.forward(petalwidth + i) # t.color("yellow") # for i in range (0, 100): # t.forward(petalwidth + i) # t.left(direction2) # t.forward(petalwidth + i) # When you've drawn the first version of the flower # feel free to change the values of petalwidth and direction1 and direction2. # and see how they affect the drawing.
true
370e5444b9b12e9a709f8cc1c67a60db88696e83
ttur/PythonInBrowser
/public/examples/session1/calculator.py
880
4.53125
5
##### FILE ##### # calculator.py # Let's use code as our calculator ##### EXERCISE ##### # 1. Our code is trying to be really clever. # On the previous exercise we gave numbers as integers # and our code thought we wanted an integer back. # Let's try again, and print the following results print 1/2 print 1.0/2.0 print 1/2.0 print 1.0/2 # When using only integers in calculations python returns integers as a result. # We can avoid that, and receive decimal answers # by using one or more decimal numbers in calculations. # 2. Now make your own equation with decimal numbers and print the result of it # 3. Take '#' away and run your code. Try to understand what it does. # print 3.0 ** 2.0 # 4. Take '#' away and run your code. Try to understand what it does. # print 3.0 % 2.0 # TIP! If you don't figure exercises 3 and 4 out # try changing the numbers and think again.
true
781019e6b244c4f6fb3fb30a6e600f5cabb3ac24
kamran1231/Fibonacci-series-program-using-function
/fibonacciseries.py
439
4.3125
4
def fibonacci_number(num): a = 0 b = 1 if num == 0: print('enter the number greater than 0') elif num == 1: print(a) elif num == 2: print(a,b) else: print(a,b,end = ' ') for i in range(num-2): c = a + b a = b b = c print(b,end= ' ') fibonacci_number(num = int(input('enter the number: ')))
false
1256a9497cd09dd5b32d219f38b7379f03e2d32c
janaharajan/python-30-days-internship-tasks
/day4.py
827
4.3125
4
#write a program to create a list of n integer values and do the following L1=['2','3','4','5','6'] # a) add an item in to the list (using function) L1.append('7') print(L1) ['2', '3', '4', '5', '6', '7'] # b) delete(using function) L1.remove('3') print(L1) ['2', '4', '5', '6', '7'] # c) store the largest number frrpm the list to a variable print(max(L1)) 7 # d) store the smallest number from the list to a variable print(min(L1)) 2 #create a tuple and point the reverse of the created tuple tuple = ('1','2','3','home','3.14') reversedtuples = tuple[::-1] print(reversedtuples) ('3.14', 'home', '3', '2', '1') #create a tuple and convert tuple into list tuple = ('45','56','67','3.45','home') list = list(tuple) print(type(list)) <class 'list'> print(list) ['45', '56', '67', '3.45', 'home']
true
0bb92a5cffc978d15987427f79dcdb0cf327ff41
Selina0w0/Word-Counter-for-Docx
/Word Counter.py
2,204
4.28125
4
from docx import Document def separate_punc(word_list): # Separates punctuations and numbers from words. # Takes in a list of words possibly with punctuations and returns a list with the words, numbers, and punctuations separated. # new_list is used as temporary list of separated words. # digit_list is used as a variable to concatenate consecutive numbers in str format. return_word_list = [] for word in word_list: print(f'word: {word}') new_list = [] digit_list = '' for letter in word: if letter.isdigit(): digit_list += letter elif digit_list == '': # When there is no stored numbers if letter.isalpha(): new_list.append(letter) else: new_list += [' ', letter, ' '] else: # When there is stored numbers if letter.isalpha(): new_list += [' ', digit_list, ' '] digit_list = '' new_list.append(letter) else: new_list += [' ', digit_list, ' '] digit_list = '' new_list += [' ', letter, ' '] letter_str = ''.join(new_list) letter_list = letter_str.split() return_word_list += letter_list return return_word_list def count_words(file_name): # Count how many times each word is used in a docx file. Takes in a directory of file and returns dictionary with {word:number of word used}. count_dict = {} document = Document(file_name) for paragraph in document.paragraphs: words = paragraph.text.lower().split() words = separate_punc(words) for word in words: if word in count_dict: count_dict[word] += 1 else: count_dict[word] = 1 return(count_dict) # Running file_name = input("Enter the file directory:") # Sorts the dictionary of words in the order of most used to least used. sorted_dict = dict(sorted(count_words(file_name).items(), key=lambda word: word[1], reverse=True)) print(sorted_dict)
true
141fe6de70a6f0806b1fc9d938125a443c0b893a
carlawalker/softwareengineering
/lregress_expenses_abroad.py
1,428
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Regressions Module | Expenses on tourism made in other countries. Objective: find the coefficients between the exchange rate and varible "expenses_abroad". End Result: graph plot and main indicators. """ # Import sklearn, matplotlib and numpy with the usual conventions # sklearn and matplotlib are important for our regression and the ploting # numpy is required for the calculation of the coefficents from sklearn import linear_model import matplotlib.pyplot as plt import numpy as np # Import dataset from the Datamanagement Module from datamanagement import dataset # Plot the two variables against each other, x remains the same, y can be changed # @var x_df = DataFrame column for base "exchange_rate" # @var y_df = DataFrame column variable y-value x_df = dataset.loc[:,["exchange_rate"]] y_df = dataset.loc[:,["expenses_abroad"]] # Create linear regression object regr = linear_model.LinearRegression() regr.fit(x_df, y_df) # Plot outputs and show the graph plt.scatter(x_df, y_df, color='black') plt.plot(x_df, regr.predict(x_df), color='blue', linewidth=3) plt.show() # Calculate coefficients print('Coefficients: \n', regr.coef_) # The mean squared error print("Mean squared error: %.2f" % np.mean((regr.predict(x_df) - y_df) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(x_df, y_df))
true
dfb207a790afc0264061c4323fd6c1a0fe3c76b5
Siwangi/PythonDSA
/fibonacci-20th-april.py
690
4.21875
4
""" #print fibonacci number number = int(input("Enter the number: ")) a = 0 b = 1 sum = 0 count = 0 while count < number: print(a) sum = a + b a = b b = sum count = count+1 """ """ # print number from 500 to 1 a = 500 num = 0 while num < 500: sum = a - num print(sum) num = num + 1 """ """ # print number from 500 to 1 a = 1 num = 0 while num < 500: sum = a + num print(sum) num = num +1 """ """ # print prime number """ a = int(input("Enter any number: ")) count = 1 num = 0 while count < a+1: if a % count == 0: num = num + 1 count=count + 1 if num == 2: print("number is prime") else: print("Number is not prime")
false
2dbc5f7a05fa9141382efc921b41a39faa6a640c
Siwangi/PythonDSA
/practice_13thmay.py
2,551
4.3125
4
def calculator(): print("ME == Show the Menu") print("A == Addition") print("S == Subtraction") print("D == Division") print("MU == Multiplication") print("Q == Quit") userChoice = input("Enter your Choice: ") userChoice = userChoice.upper() return userChoice def Menu(): print("Menu") def Addition(): print("Enter the numbers below to Add") try: userInput = int(input("how many numbers do you want to add: ")) count = 0 sum = 0 while count < userInput: userInput1 = int(input("Enter the number: ")) sum = sum + userInput1 count = count +1 print("Addition: ", sum) except ValueError: print("Error Message: You can only enter Numbers") def Subtraction(): print("Enter the numbers below to Subtract") try: userInput = int(input("Enter the first number: ")) userInput1 = int(input("Enter the second number : ")) sub = userInput - userInput1 print("Subtraction: ", sub) except ValueError: print("Error Message: You can only enter Numbers") def Division(): print("Enter the numbers below to Divide") try: userInput = int(input("Enter the numerator: ")) userInput1 = int(input("Enter the denominator: ")) while userInput1 == 0: print("Denominator cannot be zero") userInput1=int(input("Enter the denominator: ")) div=userInput / userInput1 print("Division: ", div) except ValueError: print("Error Message: You can only enter Numbers") def Multiplication(): print("Enter the numbers below to Multiply") try: userInput = int(input("How many numbers do you want to multiply: ")) count = 0 prod = 1 while count < userInput: userInput1 = int(input("Enter the number: ")) prod = prod * userInput1 count = count +1 print("Multiplication: ", prod) except ValueError: print("Error Message: You can only enter Numbers") def main(): while True: userChoice = calculator() if userChoice == 'ME': Menu() elif userChoice == 'A': Addition() elif userChoice == 'S': Subtraction() elif userChoice == 'D': Division() elif userChoice == 'MU': Multiplication() elif userChoice == "Q": exit() else: print("Please choose options only") main()
true
c9f8d145c5049f9bd227b70f0d68aae23323a28c
Siwangi/PythonDSA
/practice_summation_of_prime.py
515
4.15625
4
userInput = int(input("Upto how many primes you wanna print: ")) def Prime(userInput): count = 1 sum = 0 while count <= userInput: if userInput % count == 0: sum = sum + 1 count = count + 1 if sum == 2: return "prime" else: return "not prime" count = 1 prime = [] sum = 0 while count <= userInput: ifPrime = Prime(count) if ifPrime == "prime": prime.append(count) sum = sum + count count = count + 1 print(prime, sum)
true
f25e56c371bda5424ef696305363321a48e22748
Yogesh-Singh-Gadwal/YSG_Python
/Core_Python/Day-11/15.py
315
4.15625
4
# String # 3. strip() method removes any whitespace from the beginning or the end s1 = 'micky' print(len(s1)) print() s1 = ' micky ' print(len(s1)) print() s2 = s1.strip() print(len(s2)) print(s2) print() s1 = ' micky ' print(len(s1)) s2 = s1.lstrip() print(len(s2)) print(s2)
false
6e1f9e623ebc7c167b63ecfd3d75ae2824f7b13a
Yogesh-Singh-Gadwal/YSG_Python
/Core_Python/Day-3/12.py
360
4.1875
4
# Dynamic Value pro1 = float(input('Enter user value-1 : ')) pro2 = float(input('Enter user value-2 : ')) pro3 = float(input('Enter user value-3 : ')) print() print('Product-1 Cost is : ',pro1) print('Product-2 Cost is : ',pro2) print('Product-3 Cost is : ',pro3) print('-------------------') print() print('Total Amount is : ',pro1+pro2+pro3)
false
59d950e9a9ff6e1478c6d7517cfc825c24308730
Yogesh-Singh-Gadwal/YSG_Python
/Core_Python/Day-11/17.py
236
4.3125
4
# String # 7. The replace() method replaces a string with another string s1 = 'disney world' s2 = s1.replace('w','Z') print(s2) print() s1 = 'disney world' s2 = s1.replace('world','micky').replace('disney','India') print(s2)
false
abceeced71b1470063bf173318593b0fa8211aa3
pradeesh848/python_repo
/partition.py
1,843
4.46875
4
import sys def check_partition(half, n, arr): """ Function to check if the list is partitionable This is achieved with the help of nested loops Each element in the list is added with remaining elements one by one to see if the sum is equal to the param 'half' :param half: sum of all integers in the list divided by 2 :param n: length of the list :param arr: the list to be partitioned :return: True is list can be partitioned """ # outer loop: n times for i in range(n - 1, -1, -1): count = 0 # check if half is greater than the element; if yes add the element to count if (arr[i]) <= half: count += arr[i] # return true if count is equal to half if count == half: return True # inner loop: i-1 times for j in range(i - 1, -1, -1): # check if half is greater than count + element; if yes added the element to existing count if (count + arr[j]) <= half: count += arr[j] # return true if count is equal to half if count == half: return True return False try: # fetch list from user arr = [int(x) for x in input("Enter list of integers separated by comma(ex-1,2,3):").split(",")] except: print("INVALID INPUT") sys.exit() # find sum of the given list sum = int(sum(arr)) # check if the sum can be divided into two equal halves AND check is the list is partitionable # using the in-built function sorted() to sort the array if sum % 2 == 0 and check_partition((sum / 2), len(arr), sorted(arr)): print("Given list", arr, " is partitionable") else: print("Given list", arr, " is NOT partitionable")
true
e95fd501044b897bd9c6007d86a09c299dbc4130
mccaune/talking-about-practice
/python-for-everyone-exercises/p4e_9_2_dict_mail_day_of_week.py
821
4.21875
4
""" Exercise 2: Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter). Sample Line: From stephen.marquard@uct.ac.za Sat Jan Sample Execution: python dow.py Enter a file name: mbox-short.txt {'Fri': 20, 'Thu': 6, 'Sat': 1} """ d = {} fhand = open('mbox-short.txt') for line in fhand: line = line.strip() words = line.split() if line.startswith('From:'): continue if line.startswith('From'): d[words[2]] = d.get(words[2], 0) + 1 # if words[2] not in d: # d[words[2]] = 1 # else: # d[words[2]] += 1 print(d)
true
c9fd9fc63a016332a2dba3c7dc69bb98bf07c572
sagibon/FirstPractice.py
/first_package/Fibonacci.py
326
4.1875
4
num1 = 0 num2 = 1 num3 = 1 iterations = int(input("How much numbers in fibonacci sequence to display: \n")) if iterations>=0: print(0) for i in range(iterations): print(num3) num3 = num1 + num2 num1 = num2 num2 = num3 else: print("There are no negative sequesces u piece of crap")
true
9a05cecdce70acaefc46c3b479b4c60b9d807cdc
sagibon/FirstPractice.py
/first_package/Loops4experis.py
1,030
4.1875
4
"""lowest = 100000 while(True): inpt = int(input("enter a number: ")) if inpt > 0 and inpt<lowest: lowest = inpt if inpt == 0: break print(f"the lowest real integer is {lowest}")""" #targil 2 lolaot 4 """num = int(input("enter a number to show his left digit")) while num >= 10: num//=10 print(num)""" #תרגיל 3 לולאות 4 """highest=0 count = 0 while count!=7: num = int(input("Enter a number: ")) if num > highest: highest = num highestcount = count count+=1 print(f"Highest is {highest} in location {highestcount}")""" #תרגיל 4 לולאות 4 """digits = 1 num = int(input("enter a number to reverse")) numcheck = num regularnum = num #check digits while numcheck >= 10: numcheck//=10 digits+=1 count = digits numcheck = 0 while digits>0: num = regularnum num = (num // (10 ** (digits-1)) % 10) numcheck+=(num*10**(count-digits)) digits-=1 print(f"the reversed number is {numcheck} and the double is {numcheck*2}")"""
true
2453ef24f4bd6c4f3824ea824eb93e710662bad2
chjlarson/Classwork
/python/hw1/celsius_to_fahrenheit.py
440
4.59375
5
# Christopher Larson # CSCI 238 Homework #1, Problem #4 # celsius_to_fahrenheit.py # 9/1/13 # # This program converts degrees in Celsius # to degrees in Fahrenheit. print('Celsius to Fahrenheit converter') # Get the degrees in Celsius celsius = float(input('Enter temperature in Celcius: ')) # Convert Celsius to Fahrenheit fahrenheit = (9/5) * celsius +32 # Display the conversion to Fahrenheit print('Temperature in Fahrenheit is ',fahrenheit)
false
14cea5326aa79ede58c7367f7a75475d9c0d1df1
chjlarson/Classwork
/python/lab12/test_polynomial.py
2,079
4.28125
4
# Christopher Larson & Robert Pitts # CSCI 238 Lab #12, Problem #2 # test_polynomial.py # This program will test the function polynomial def main(): print('This program tests the polynomial function.\n') print('Testing the polynomial p(x) = 1 + 3x + 2x^2\n') result = polynomial([1, 3, 2], 1) if result == 6: print('Correct: p(1) is 6') else: print('ERROR: p(1) is %d instead of 6' % result) result = polynomial([1, 3, 2], 2) if result == 15: print('Correct: p(2) is 15') else: print('ERROR: p(2) is %d instead of 15' % result) result = polynomial([1, 3, 2], 3) if result == 28: print('Correct: p(3) is 28') else: print('ERROR: p(3) is %d instead of 28' % result) print('\nTesting the polynomial p(x) = -3 + x - 3x^2\n') result = polynomial([-3, 1, -3], 1) if result == -5: print('Correct: p(1) is -5') else: print('ERROR: p(1) is %d instead of -5' % result) result = polynomial([-3, 1, -3], 2) if result == -13: print('Correct: p(2) is -13') else: print('ERROR: p(2) is %d instead of -13' % result) result = polynomial([-3, 1, -3], 3) if result == -27: print('Correct: p(3) is -27') else: print('ERROR: p(3) is %d instead of -27' % result) print('\nTesting the polynomial p(x) = 1 + 3x^2 - 2x^3 + x^4\n') result = polynomial([1, 0, 3, -2, 1], 1) if result == 3: print('Correct: p(1) is 3') else: print('ERROR: p(1) is %d instead of 3' % result) result = polynomial([1, 0, 3, -2, 1], 2) if result == 13: print('Correct: p(2) is 13') else: print('ERROR: p(2) is %d instead of 13' % result) result = polynomial([1, 0, 3, -2, 1], 3) if result == 55: print('Correct: p(3) is 55') else: print('ERROR: p(3) is %d instead of 55' % result) def polynomial(a, x): """Return value of polynomial a when evaluated at x.""" sum = 0 for i in range(len(a)): sum += a[i] * x**i return sum main()
false
14dd44d6e6c03414ba262b3411f3c0d94589060b
chjlarson/Classwork
/python/other/point3.py
1,502
4.1875
4
# point3.py """Provide the Point class.""" class Point(object): """Represent a point in 2-D coordinates.""" def __init__(self, x_value=0, y_value=0): """Create a new point. Arguments: x_value (default 0) y_value (default 0) """ self.__x = x_value self.__y = y_value def get_x(self): """Return the x coordinate of the point.""" return self.__x def get_y(self): """Return the y coordinate of the point.""" return self.__y def set_point(self, x_value, y_value): """Set the point to the new values. Arguments: x_value (default 0) y_value (default 0) """ self.__x = x_value self.__y = y_value def __eq__(self, other): """Return whether or not the two points have same data.""" return self.__x == other.__x \ and self.__y == other.__y def __add__(self, other): """Return a third point created by adding two points.""" return Point(self.__x + other.__x, \ self.__y + other.__y) def __iadd__(self, other): """Add the second point to the first point.""" self.__x += other.__x self.__y += other.__y return self def __str__(self): """Create a string representation in format (%.2f, %.2f).""" return '(%.2f, %.2f)' % (self.__x, self.__y)
true
00786582a634e2beca5bf9b5499215336e91a5de
chjlarson/Classwork
/python/hw4/election_year.py
1,679
4.34375
4
# Christopher Larson # CSCI 238 Homework #4, Problem #2 # election_year.py # 9/25/13 # # This program will calculate which years are election years def main(): print('This program tests the is_election_year() function') print('for determining presidential election years.\n') if is_election_year(2000): print('Correct: 2000 was an election year') else: print('ERROR: 2000 should have been an election year') if not is_election_year(2011): print('Correct: 2011 was not an election year') else: print('ERROR: 2011 should not have been an election year') if is_election_year(2012): print('Correct: 2012 was an election year') else: print('ERROR: 2012 should have been an election year') # Although it is poor practice to write a condition like this # below, I need it here to catch a subtle error that students # sometimes make if is_election_year(2013) == False: print('Correct: 2013 is not an election year') else: print('ERROR: 2013 should not be an election year') if not is_election_year(2014): print('Correct: 2014 is not an election year') else: print('ERROR: 2014 should not be an election year') if not is_election_year(2015): print('Correct: 2015 is not an election year') else: print('ERROR: 2015 should not be an election year') if is_election_year(2016): print('Correct: 2016 is an election year') else: print('ERROR: 2016 should be an election year') def is_election_year(year): if year % 4 == 0: result = True else: result = False return result main()
false
d13e70ab1cb4dfd2a9cc4a75c4d99b752302268f
chjlarson/Classwork
/python/lab10/rolling_dice.py
817
4.1875
4
# Christopher Larson & Robert Pitts # CSCI 238 Lab#10, Problem #1 # rolling_dice.py # 10/3/13 # # This program rolls two dice a number of times and determines hiw many times # a number the user inputs is rolled. import dice NUM_ROLLS = 1000 def main(): print('This program rolls two dice %d times and' %NUM_ROLLS) print('determines the number of times a certain number occurs.\n') number = int(input('Enter a number from 2 to 12: ')) while number > 12 or number < 2: print('Error, number must be between 2 and 12') number = int(input('Enter a number from 2 to 12: ')) count = 0 for i in range(NUM_ROLLS): die1, die2 = dice.roll_dice() if die1 + die2 == number: count += 1 print('Out of %d rolls, %d occurs %d times.' % (NUM_ROLLS, number, count)) main()
true
809a240ec5b89475c179535b21f932afa8cf1609
chjlarson/Classwork
/python/hw2/monthly_payment.py
908
4.46875
4
# Christopher Larson # CSCI 238 Homework#2 Problem #5 # monthly_payment.py # 9/11/13 # # This program will calculate the monthly payment of something. def main(): print('This will calculate how much your monthly payments will be. \n') principle = float(input('Enter the amount you are borrowing: ')) annual_interest = float(input('Enter the annual' \ + ' interest rate in percentage: ')) months = int(input('Enter the total number of expected payments: ')) monthly_payments = payments(principle, annual_interest, months) print(('At an annual interest rate of %.1f%%, your ' \ + 'payments will be \n $%.2f per month for ' \ + '%d months.') % (annual_interest, monthly_payments, months)) def payments(num1, num2, num3): monthly_interest = num2 / (100 * 12) result = num1 * (monthly_interest / (1 - (1 + monthly_interest)**(- num3))) return result main()
true
9fd10d88ddefdef572a5f8f7dfe0ad872663052a
Ady-6720/python3
/ex.8.4.py
1,108
4.4375
4
""" 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() function. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order. You can download the sample data at http://www.pythonlearn.com/code/romeo.txt """ #output: #['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', #'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', #'through', 'what', 'window', 'with', 'yonder'] fname = input("Inter file name : ") try : fhand = open(fname) except: print("file, [",fname, "] is not found") exit() w_list = list() for line in fhand : line = line.rstrip() lsplit = line.split() #print(lsplit) for word in lsplit : if word not in w_list : w_list.append(word) else : continue w_list.sort() print(w_list)
true
1bd799877f98a57207fe9540b150e68497a2cb72
ksentrax/think-py-2e--my-solutions
/exercise9/exercise9-5.py
682
4.375
4
"""This script checks if the word contains all available letters.""" def uses_all(word, required): """Checks if a word contains all available characters. :param word: string :param required: required characters :return: boolean value """ for letter in required: if letter not in word: return False return True def count_all(): """Counts how many words contain available characters.""" count = 0 with open('words.txt', 'r') as f: for line in f: word = line.strip() if uses_all(word, 'aeiou'): count += 1 print(count) if __name__ == '__main__': count_all()
true
03e799fcef0e0425b47c77c714be23fe0e0b755c
ksentrax/think-py-2e--my-solutions
/exercise6/exercise6-3.py
1,050
4.3125
4
"""This script checks if the string is a palindrome.""" def first(word): """Returns the first character from the string. :param word: input string value :return: first string element """ return word[0] def last(word): """Returns the last character from the string. :param word: input string value :return: last string element """ return word[-1] def middle(word): """Returns all character from the string except the first and last. :param word: input string value :return: middle element of string """ return word[1:-1] def is_palindrome(word): """Return True if argument is a palindrome. :param word: input string value :return: boolean value """ if len(word) <= 1: return True elif first(word) == last(word): if len(middle(word)) <= 1: return True elif len(middle(word)) > 1: return is_palindrome(middle(word)) else: return False if __name__ == '__main__': print(is_palindrome('noon'))
true
ab82ba87820d8e172fced7d4bcd3a11f876fc5b3
ksentrax/think-py-2e--my-solutions
/exercise9/exercise9-3.py
859
4.34375
4
"""This script checks if a word contains forbidden letters and counts those words.""" def avoids(word, forbidden): """Checks if a word contains a string of forbidden letters. :param word: string :param forbidden: string of forbidden letters :return: boolean value """ for letter in word: if letter in forbidden: return False return True def avoids_forbidden(): """Prompts the user to enter a string of forbidden letters and prints the number of words that do not contain any of them.""" user_input = input("Enter a string of forbidden letters:") count = 0 with open('words.txt', 'r') as f: for line in f: word = line.strip() if avoids(word, user_input): count += 1 print(count) if __name__ == '__main__': avoids_forbidden()
true