blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f70f72b4d449726be0bb53878d32116d999756f5 | dlingerfelt/DSC-510-Fall2019 | /Steen_DSC510/Assignment 2.1 - Jonathan Steen.py | 1,105 | 4.28125 | 4 | # File: Assignment 2.1 - Jonathan Steen.py
# Name: Jonathan Steen
# Date: 12/2/2019
# Course: DSC510 - Introduction to Programing
# Desc: Program calculates cost of fiber optic installation.
# Usage: The program gets company name,
# number of feet of fiber optic cable, calculate
# installation cost and prints a receipt.
print('Welcome to the fiber optic installation cost calculator.')
companyName = input('Please input company name.\n')
fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n')
fiberOpticCost = .87 #define the varible to hold the cost per ft of fiber optic.
totalCost = float(fiberOpticLength) * float(fiberOpticCost) #convert user input to float and calculate price.
print('\n')
print('Receipt')
print(companyName)
print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '$' + str(fiberOpticCost) + ' Per Foot') #convert float varible to string
totalCost = totalCost - totalCost % 0.01 #format output to two decimal points without rounding up or down to get accurate amount.
print('Total: ' + '$' + str(totalCost))
| true |
2155f32ff8af7f310124f09964e576fe5b464398 | dlingerfelt/DSC-510-Fall2019 | /DSC510- Week 5 Nguyen.py | 2,139 | 4.3125 | 4 | '''
File: DSC510-Week 5 Nguyen.py
Name: Chau Nguyen
Date: 1/12/2020
Course: DSC_510 Intro to Programming
Desc: This program helps implement variety of loops and functions.
The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user.
'''
def performCalculation(user_operation):
# Using list will allow multiple inputs
user_input = list(map(int, input("Enter multiple values: (no comma, just space) ").split()))
if user_operation =="*":
result = user_input[0] * user_input[1]
elif user_operation =="%":
try:
result = user_input[0] / user_input[1]
except:
print("Error: Cannot Divide %s/%s" %(user_input[0], user_input[1]))
return
elif user_operation =="-":
result = user_input[0] - user_input[1]
elif user_operation =="+":
result = user_input[0] + user_input[1]
else :
return float(result,2)
print("Your calcualtion result is",result)
def calculateAverage():
user_input2 = int(input('How many numbers they wish to input? '))
total_sum = 0
# Define store_input as list
store_input = []
for n in range(user_input2):
x = (int(input("Enter your value ")))
# Store user input into a list
store_input.append(x)
total_sum = sum(store_input)
average = total_sum / user_input2
print("The average is ", average)
def main():
# Welcome statement
print("Welcome. What program would you like to run today?")
user_operation =''
# Asking user to pick the program they want to run
while user_operation != 'exist':
user_operation = input("pick one of the choices: -,*,+,%,average, or exist ")
if user_operation == 'exist':
break
elif (user_operation == '-') or (user_operation == '+') or (user_operation == '*') or (user_operation == '%'):
performCalculation(user_operation)
elif (user_operation == 'average'):
calculateAverage()
else:
print("invalid choice try again")
if __name__ == '__main__':
main()
| true |
7bd2456b0c77f97e11f16454bfa9890c28d93f35 | mun5424/ProgrammingInterviewQuestions | /MergeTwoSortedLinkedLists.py | 1,468 | 4.15625 | 4 | # given two sorted linked lists, merge them into a new sorted linkedlist
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# set iterators
dummy = ListNode(0)
current = dummy
#traverse linked list, looking for lower value of each
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
#traverse rest of the linkedlist
if l1:
current.next = l1
else:
current.next = l2
return dummy.next
def printList(self, list1: ListNode):
# print a linked list
dummy = list1
res = ""
while dummy:
if dummy.next:
res += str(dummy.val) + ", "
else:
res += str(dummy.val)
dummy = dummy.next
print(res)
# sample test
node1 = ListNode(1)
node5 = ListNode(5)
node8 = ListNode(8)
node1.next = node5
node5.next = node8
node4 = ListNode(4)
node7 = ListNode(7)
node9 = ListNode(9)
node4.next = node7
node7.next = node9
s = Solution()
list1 = node1
s.printList(list1)
list2 = node4
s.printList(list2)
result = s.mergeTwoLists(list1, list2)
s.printList(result)
| true |
b9d16e4a06e0485a6e4e5c26bf4673d063c1eb7e | JaydeepKachare/Python-Classwork | /Session3/Arithematic6.py | 429 | 4.125 | 4 | # addition of two number
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2) # reusing same function (function call)
print("Addition : ",ans)
| true |
7ccff781110f6a1cdefcda48c00fca3c9be5e0b6 | AbrahamCain/Python | /PasswordMaker.py | 1,501 | 4.375 | 4 | #Password Fancifier by Cyber_Surfer
#This program takes a cool word or phrase you like and turns it into a decent password
#you can comment out or delete the following 3 lines if using an OS other than Windows
import os
import sys
os.system("color e0") #It basically alters the colors of the terminal
#Enter a password and store it in the variable "word"
word = input("Give me a word/phrase to turn into a password of at least 10 characters please:\n\n--->")
word = word.lower()
#check the length of the password/phrase
count = len(word)
if count >= 10:
for i in word:
if "e" in word:
word = word.replace("e", "3") #replace e's with 3's
if "a" in word:
word = word.replace("a", "@") #replace a's with @'s
if "s" in word:
word = word.replace("s", "$") #replace s's with $'s
word = word.title() #make the first letter of words uppercase
#make 3 other options for passwords if the environment doesn't allow spaces, underscores, or dashes
underscore = word.replace(" ", "_")
tac = word.replace(" ", "-")
nospace = word.replace(" ", "")
#print results
print("Here are four different options:")
print("1.",word)
print("2.",underscore)
print("3.",tac)
print("4.",nospace)
#Let user know the password is too short
else:
print("That password is too short. Try something over 10 characters next time.")
#End/Exit the program
input("Press ENTER To Exit")
exit(0)
| true |
0f679c78696c3d221458ece5c214502f58449c9d | GuillermoDeLaCruz/python--version3 | /name.py | 726 | 4.4375 | 4 |
#
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
# Combining or Concatenating Strings
# Python uses the plus symbol (+) to combine strings
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
#1
favorite_language = 'python '
print(favorite_language)
favorite_language.rstrip()
print(favorite_language)
#2 rstrip() removes whitespaces from the right
# lstrip() from left
# strip() from both
favorite_language = favorite_language.rstrip()
print(favorite_language)
| true |
ad8ad997ed8f9103cff43928d968f78201856399 | kevyo23/python-props | /what-a-birth.py | 1,489 | 4.5 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# what-a-birth.py - simple birthday monitor, check and add birthdays
# Kevin Yu on 28/12/2016
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
all_months = 'January February March April May June July August September October November December'
while True:
print('Enter a name: (blank to quit)')
name = raw_input()
if name == '':
break
if not name.isalpha():
print ('Invalid name entered - must contain letters only, eg Daniel')
continue
name = name.title()
if name in birthdays:
print(name + ' has a birthday on ' + birthdays[name])
else:
print('No birthday record found for ' + name)
print('What month is ' + name + '\'s birthday?')
while True:
print('Enter a month:')
month = raw_input()
if not name.isalpha() or month.title() not in all_months:
print('Invalid month entered - must contain letters only, eg January')
continue
break
month = month.title()
month = month[:3]
while True:
print('Enter a date:')
date = raw_input()
if not date.isdigit() or int(date) < 1 or int(date) > 31:
print('Invalid date entered - must contain numbers only, eg 21')
continue
break
birthdays[name] = month + ' ' + date
print ('Birthday database updated.')
| true |
f98aeb7d429aae2a54eaaa52530889c6129ddc57 | Vikas-KM/python-programming | /repr_vs_str.py | 741 | 4.375 | 4 | # __str__ vs __repr__
class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
# print and it returns always string
# for easy to read representation
def __str__(self):
return '__str__ : a {self.color} car with {self.mileage} mileage'.format(self=self)
# typing mycar in console calls this
# unambiguous
# for internal use, for developers
def __repr__(self):
return '__repr__ :a {self.color} car with {self.mileage} mileage'.format(self=self)
my_car = Car('red', 123)
# see which methods they are calling
# comment __STR__ method see what is the output again
print(my_car)
print(str(my_car))
print('{}'.format(my_car))
print(repr(my_car))
| true |
cbb68b5a739a298268d2f150aa25841ff4156ffe | sp2013/prproject | /Assgn/Linear_Regression2.py | 1,597 | 4.1875 | 4 | '''
Linear_Regression2.py
Implements Gradient Descent Algorithm
'''
import numpy as np
import random
import matplotlib.pyplot as plt
def linear_regression2():
'''
1. Read training data in to input, output array.
2. Initialize theta0 - y intercept, theta1 - slope of line.
3. Repeat following steps until convergence:
a. Compute theta0.
b. Compute theta1.
c. Compute cost.
d. Check convergence by finding the difference between previous and current cost.
4. Plot data with line using theta0, theta1.
'''
x = np.array([10, 9, 2, 15, 10, 16, 11, 16])
y = np.array([95, 80, 10, 50, 45, 98, 38, 93])
m = x.size
theta0 = random.random()
theta1 = random.random()
delta = 1000000;
error = 0.05
learningrate = 0.001
prevJtheta = 1000
Jtheta = 1000
while (delta > error):
# compute theta0
hx = theta0 + theta1*x
s1 = (hx - y).sum() / m
temp0 = theta0 - learningrate * s1
# compute theta1
s2 = ((hx - y) * x).sum() / m
temp1 = theta1 - learningrate * s2
theta0 = temp0
theta1 = temp1
#compute cost
hx = theta0 + theta1 * x
tempx = (hx - y) * (hx - y)
Jtheta = tempx.sum() / (2 * m)
delta = abs(prevJtheta - Jtheta)
prevJtheta = Jtheta
plt.xlabel('X')
plt.ylabel('Y')
axis = plt.axis([0, 20, 0, 100])
plt.grid(True)
plt.plot(x, y, 'k.')
plt.plot(x, theta1*x + theta0, '-')
plt.show()
return theta0, theta1
| true |
5c33baae0e50f099028f50a221f18e0d1437f30a | babzman/Babangida_Abdullahi_day30 | /Babangida_Abdullahi_day30.py | 1,429 | 4.28125 | 4 | def nester(n):
"""Given a string of digits S, This function inserts a minimum number of opening and closing parentheses into it such that the resulting
string is balanced and each digit d is inside exactly d pairs of matching parentheses.Let the nesting of two parentheses within a string be
the substring that occurs strictly between them. An opening parenthesis and a closing parenthesis that is further to its right
are said to match if their nesting is empty, or if every parenthesis in their nesting matches with another parenthesis in their nesting.
The nesting depth of a position p is the number of pairs of matching parentheses m such that p is included in the nesting of m.
"""
if type(n) is not str:
return "Parameter must be in string"
for t in n:
if t not in "0123456789":
return "Parameters must be numbers and greater than zero"
if len(n)==1:
return "("*int(n)+n+")"*int(n)
no=list(n)
u=no
no[0]="("*int(no[0])+no[0]
no[-1]=no[-1]+")"*int(no[-1])
num=[int(i) for i in list(n)]
diff=[int(num[i])-int(num[i+1]) for i in range(len(no)-1)]
for d in range(len(diff)):
if diff[d]>0:
u[d]=u[d]+")"*diff[d]
if diff[d]<0:
u[d]=u[d]+"("*abs(diff[d])
return "".join(u)
#test cases
print(nester("-111000"))
print(nester("4512"))
print(nester("000"))
print(nester("302"))
| true |
74789b8d7f88978a688db1b902cdb8954f315a22 | AlvinJS/Python-practice | /Group6_grades.py | 747 | 4.15625 | 4 | # Function to hold grade corresponding to score
def determinegrade(score):
if 80 <= score <= 100:
return 'A'
elif 65 <= score <= 79:
return 'B'
elif 64 <= score <= 64:
return 'C'
elif 50 <= score <= 54:
return 'D'
else:
return 'F'
count = 0
# Use range(10) because function should repeat 10 times
for name in range(10):
# Ask user to input name which is stored in name as a string
name = str(input('Please enter your name: '))
# Ask user to input score which is stored in grade as an integer
grade = int(input('What is your score? '))
# count shows you which iteration you are on
count = count + 1
print(count,'Hello',name,'your grade is:',determinegrade(grade))
| true |
fab1979adbfa20245e24943f73ba15566cd06f69 | magotheinnocent/Simple_Chatty_Bot | /Simple Chatty Bot/task/bot/bot.py | 1,188 | 4.25 | 4 | print("Hello! My name is Aid.")
print("I was created in 2020.")
print("Please, remind me your name.")
name = str(input())
print(f"What a great name you have, {name}!")
print("Let me guess your age.")
print("Enter remainders of dividing your age by 3, 5 and 7")
remainder1 = int(input())
remainder2 = int(input())
remainder3 = int(input())
age = (remainder1 * 70
+ remainder2 * 21
+ remainder3 * 15) % 105
print(f"Your age is {age}; that's a good time to start programming!")
print("Now I will prove to you that I can count to any number you want")
number=int(input())
i = 0
while i <= number:
print(f"{i}!")
i += 1
print("Let's test your programming knowledge.")
print("Why do we use methods?")
answer_1 = list("1. To repeat a statement multiple times.")
answer_2 = list("2. To decompose a program into several small subroutines.")
answer_3 = list("3. To determine the execution time of a program.")
answer_4 = list("4. To interrupt the execution of a program.")
answer = input()
while answer != "2":
print('Please, try again.')
answer = input()
if answer == "2":
print("Completed, have a nice day!")
print("Congratulations, have a nice day!")
| true |
fd73641925aa29814156330883df9d132dbcb802 | goodwjsphone/WilliamG-Yr12 | /ACS Prog Tasks/04-Comparision of two.py | 296 | 4.21875 | 4 | #write a program which takes two numbers and output them with the greatest first.
num1 = int(input("Input first number "))
num2 = int(input("Input second number "))
if num1 > num2:
print (num1)
else:
print(num2)
## ACS - You need a comment to show where the end of the if statement is.
| true |
a606701ff19aeb87aa7747cd39d40feb826ccb29 | PhyzXeno/python_pro | /transfer_to_x.py | 991 | 4.25 | 4 | # this piece of code will convert strings like "8D4C2404" into "\x8D\x4C\x24\x04"
# which will then be disassembled by capstone and print the machine code
import sys
from capstone import *
# print("the hex string is " + sys.argv[1])
the_str = sys.argv[1]
def x_encode(str):
the_str_len = len(str)
count = 0
the_x_str = r"\x" # \x is not some kind of encodeing. It is an escape character, the fllowing two characters will be interpreted as hex digit
# in order not to escape here, we need raw string to stop character escaping
while 1:
the_x_str = the_x_str + sys.argv[1][count:count+2] + r"\x"
count += 2
if count == the_str_len:
return(the_x_str[:-2].decode("string_escape")) # this will convert raw string into normal string
def x_disassem(str):
CODE = str
# CODE = "\x89\xe5"
# print(type(CODE))
md = Cs(CS_ARCH_X86, CS_MODE_64)
for i in md.disasm(CODE, 0x1000):
print "0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str)
x_disassem(x_encode(the_str))
| true |
de62d877172215f9cbb0b30b24e8009b3485bf47 | cpkoywk/IST664_Natural_Language_Processing | /Lab 1/assignment1.py | 1,148 | 4.21875 | 4 | '''
Steps:
get the text with nltk.corpus.gutenberg.raw()
get the tokens with nltk.word_tokenize()
get the words by using w.lower() to lowercase the tokens
make the frequency distribution with FreqDist
get the 30 top frequency words with most_common(30) and print the word, frequency pairs
'''
#Import required modules
import nltk
from nltk import FreqDist
from nltk.corpus import brown
#check what file they've got in gutenberg
nltk.corpus.gutenberg.fileids()
#I will pick 'shakespeare-hamlet.txt'
file0 = nltk.corpus.gutenberg.fileids()[-3]
#file0 = 'shakespeare-hamlet.txt'
#1. get the text with nltk.corpus.gutenberg.raw()
hamlettext=nltk.corpus.gutenberg.raw(file0)
#2. Get the tokens with nltk.word_tokenize()
hamlettokens = nltk.word_tokenize(hamlettext)
#3. Get the words by using w.lower() to lowercase the tokens
hamletwords = [w.lower() for w in emmatokens]
#4. make the frequency distribution with FreqDist
fdist = FreqDist(hamletwords)
fdistkeys=list(fdist.keys())
#5. get the 30 top frequency words with most_common(30) and print the word, frequency pairs
top30keys=fdist.most_common(30)
for pair in top30keys:
print (pair)
| true |
eb9d5ad1a3bb38c87c64f435c2eabd429405ddc3 | niall-oc/things | /codility/odd_occurrences_in_array.py | 2,360 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/
A non-empty array A consisting of N integers is given. The array contains an odd
number of elements, and each element of the array can be paired with another
element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.
Write a function:
def solution(A)
that, given an array A consisting of N integers fulfilling the above conditions,
returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
N is an odd integer within the range [1..1,000,000];
each element of array A is an integer within the range [1..1,000,000,000];
all but one of the values in A occur an even number of times.
# 100% solution https://app.codility.com/demo/results/trainingCB48ED-3XU/
"""
import time
def solution(A):
"""
Bitwise or between 2 numbers where N==N produces a 0.
Therefore even pairing of numbers will produce zero.
The remainder of the bitwise or operation will be equal to the one odd occurance
in the array.
"""
result=0
for item in A:
result ^= item
return result
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(7, ([1,1,2,2,7],)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!')
| true |
db239ae5d7cc670f71e8af8d99bc441f4af2503a | niall-oc/things | /puzzles/movies/movies.py | 2,571 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Given the following list in a string seperated by \n characters.
Jaws (1975)
Starwars 1977
2001 A Space Odyssey ( 1968 )
Back to the future 1985.
Raiders of the lost ark 1981 .
jurassic park 1993
The Matrix 1999
A fist full of Dollars
10,000 BC (2008)
1941 (1979)
24 Hour Party People (2002)
300 (2007)
2010
Produce the following output.
2000s : 3
1970s : 3
1980s : 2
1990s : 2
1960s : 1
"""
import re
year_pattern = re.compile("[0-9]{4}") # or [0-9]{4}
def find_year(title):
"""
Returns a 4 digit block nearest the right of the string title.
OR
Returns None.
EG.
Starwars (1977) # year is 1997
2001 A space odyssey 1968 # year is 1968
2010 # NO year
1985. # NO year
75 # NO year
usage:
>>> find_year("starwars (1977)")
1977
:param str title: A string containing a movie title and year of relaease.
:return str: Year of release
"""
# find all patterns that match the year pattern
matches = year_pattern.findall(title)
# if any matches
if matches:
# record for convienence
year = matches[-1]
too_short = len(title) < 8
# If the year is the title then return None
if year == title:
return None
# If we have enough room for 1 block of 4 digits and its at the start
elif too_short and title.startswith(year):
return None
else:
return year
def rank_decades(movies):
"""
Returns a dictionary of decades -> number of movies released.
usage:
>>> rank_decades(['starwars 1977'])
{'1970s': 1}
:param list movies: A collection of title strings
:return dict: decades and number of releases.
"""
results = {}
for movie in movies:
year = find_year(movie)
# If we found a release year then count it
if year:
# A way to map year to decade
decade = "{0}0s".format(year[:3])
else:
decade = "None"
results[decade] = results.setdefault(decade, 0) + 1
return results
if __name__ == "__main__":
f = open('movie_releases.txt')
movie_data = f.read()
all_movies = movie_data.split('\n')
rank = rank_decades(all_movies)
for decade, count in sorted(rank.items(), key=lambda s: s[1], reverse=True):
print "%s : %s" % (decade, count,)
| true |
e6ea4c49d3012708cededb29a1f79f575561c82f | niall-oc/things | /codility/frog_jmp.py | 2,058 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Author: Niall O'Connor
# https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
A small frog wants to get to the other side of the road. The frog is currently
located at position X and wants to get to a position greater than or equal to Y.
The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its
target.
Write a function:
def solution(X, Y, D):
that, given three integers X, Y and D, returns the minimal number of jumps from
position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
# 100% solution https://app.codility.com/demo/results/trainingWK4W5Q-7EF/
"""
import time
def solution(X, Y, D):
"""
Simply divide the jumps into the distance.
Distance being y-X and ensuring a finaly jump over the line!
"""
distance = (Y-X)
hops = distance // D
if distance%D: # landing even is not over the line!
hops += 1
return hops
if __name__ == '__main__':
tests = (
# Test cases are in pairs of (expected, (args,))
(3, (10, 85, 30,)),
)
for expected, args in tests:
# record performance of solution
tic = time.perf_counter()
res = solution(*args)
toc = time.perf_counter()
print(f'ARGS produced {res} in {toc - tic:0.8f} seconds')
if args[0] is None:
continue # This is just a speed test
try:
assert(expected == res)
except AssertionError as e:
print(f'ERROR {args} produced {res} when {expected} was expected!')
| true |
fdec6fee3a57a11783c40eafcb9125b11e174f51 | Anshu-Singh1998/python-tutorial | /fourty.py | 289 | 4.28125 | 4 | # let us c
# Write a function to calculate the factorial value of any integer enyered
# through the keyboard.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
n = int(input("Input a number to compute the factorial : "))
print(factorial(n))
| true |
5ca65e5362eca7bf9cfeda1021564e6c20ccb4a5 | Anshu-Singh1998/python-tutorial | /eight.py | 228 | 4.25 | 4 | # let us c
# input a integer through keyboard and find out whether it is even or odd.
a = int(input("Enter a number to find out even or odd:"))
if a % 2 == 0:
print("the number is even")
else:
print("the number is odd")
| true |
4516d98fd3db1d9c9049bb6cb3d1fe18e9e7914b | Anshu-Singh1998/python-tutorial | /nineteen.py | 268 | 4.15625 | 4 | # From internet
# Write a program to remove an element from an existing array.
from array import *
num = list("i", [4, 7, 2, 0, 8, 6])
print("This is the list before it was removed:"+str(num))
print("Lets remove it")
num.remove(2)
print("Removing performed:"+str(num)) | true |
a17e198eeaac4a06b472845f6dffdd2bcf1f74c3 | damsonli/mitx6.00.1x | /Mid_Term/problem7.py | 2,190 | 4.4375 | 4 | '''
Write a function called score that meets the specifications below.
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet (a=1 ... z=26)
times its distance from start of word.
Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2.
2) The score for a word is the result of applying f to the
scores of the word's two highest scoring letters.
The first parameter to f is the highest letter score,
and the second parameter is the second highest letter score.
Ex. If f returns the sum of its arguments, then the
score for 'adD' is 12
"""
#YOUR CODE HERE
Paste your entire function, including the definition, in the box below. Do not leave any print statements.
'''
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet (a=1 ... z=26)
times its distance from start of word.
Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2.
2) The score for a word is the result of applying f to the
scores of the word's two highest scoring letters.
The first parameter to f is the highest letter score,
and the second parameter is the second highest letter score.
Ex. If f returns the sum of its arguments, then the
score for 'adD' is 12
"""
#YOUR CODE HERE
i = 0
scores = []
word = word.lower()
for letter in word:
score = (ord(letter) - ord('a') + 1) * i
scores.append(score)
i += 1
scores = sorted(scores, reverse=True)
return f(scores[0], scores[1])
def f(num1, num2):
print(num1)
print(num2)
return num1 + num2
print(score('adDe', f)) | true |
622b10cab635fa09528ffdeab353bfd42e69bdc7 | damsonli/mitx6.00.1x | /Final Exam/problem7.py | 2,105 | 4.46875 | 4 | """
Implement the class myDict with the methods below, which will represent a dictionary without using
a dictionary object. The methods you implement below should have the same behavior as a dict object,
including raising appropriate exceptions. Your code does not have to be efficient. Any code that
uses a Python dictionary object will receive 0.
For example:
With a dict: | With a myDict:
-------------------------------------------------------------------------------
d = {} md = myDict() # initialize a new object using
your choice of implementation
d[1] = 2 md.assign(1,2) # use assign method to add a key,value pair
print(d[1]) print(md.getval(1)) # use getval method to get value stored for key 1
del(d[1]) md.delete(1) # use delete method to remove
key,value pair associated with key 1
"""
class myDict(object):
""" Implements a dictionary without using a dictionary """
def __init__(self):
""" initialization of your representation """
self.keys = []
self.values = []
def assign(self, k, v):
""" k (the key) and v (the value), immutable objects """
if k not in self.keys:
self.keys.append(k)
self.values.append(v)
else:
index = self.keys.index(k)
self.values[index] = v
def getval(self, k):
""" k, immutable object """
if k not in self.keys:
raise KeyError(k)
else:
index = self.keys.index(k)
return self.values[index]
def delete(self, k):
""" k, immutable object """
if k not in self.keys:
raise KeyError(k)
else:
index = self.keys.index(k)
self.keys.pop(index)
self.values.pop(index)
md = myDict()
print(md.keys)
print(md.values)
md.assign(1,2)
print(md.keys)
print(md.values)
md.assign('a', 'c')
print(md.keys)
print(md.values)
md.assign(1,3)
print(md.keys)
print(md.values)
print(md.getval(1))
#print(md.getval('d'))
md.delete(1)
print(md.keys)
print(md.values)
md.delete('d') | true |
de17bb8bd8f94f087845cd59e2ad83f7b43f8ebd | Nicolanz/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 269 | 4.21875 | 4 | #!/usr/bin/env python3
"""Module to return str repr of floats"""
def to_str(n: float) -> str:
"""Function to get the string representation of floats
Args:
n (float): [float number]
Returns:
str: [str repr of n]
"""
return str(n)
| true |
94c63cf09da1e944b67ca243ee40f67ad3550cf5 | Nicolanz/holbertonschool-web_back_end | /0x00-python_variable_annotations/9-element_length.py | 435 | 4.28125 | 4 | #!/usr/bin/env python3
"""Module with correct annotation"""
from typing import Iterable, Sequence, List, Tuple
def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]:
"""Calculates the length of the tuples inside a list
Args:
lst (Sequence[Iterable]): [List]
Returns:
List[Tuple[Sequence, int]]: [New list with the length of the tupes]
"""
return [(i, len(i)) for i in lst]
| true |
aedfe44fe94a31da053f830a56ad5842c77b4610 | jesseklein406/data-structures | /simple_graph.py | 2,747 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A data structure for a simple graph using the model from Martin BroadHurst
http://www.martinbroadhurst.com/graph-data-structures.html
"""
class Node(object):
"""A Node class for use in a simple graph"""
def __init__(self, name, value):
"""Make a new node object"""
self.name = name
self.value = value
class G(tuple):
"""A data structure for a simple graph"""
def __init__(self):
"""Make a new simple graph object"""
self.nodes_ = set()
self.edges_ = set()
def __repr__(self):
return (self.nodes_, self.edges_)
def nodes(self):
"""return a list of all nodes in the graph"""
return list(self.nodes_)
def edges(self):
"""return a list of all edges in the graph"""
return list(self.edges_)
def add_node(self, n):
"""adds a new node 'n' to the graph"""
self.nodes_.add(n)
def add_edge(self, n1, n2):
"""adds a new edge to the graph connecting 'n1' and 'n2', if either n1
or n2 are not already present in the graph, they should be added.
"""
if n1 not in self.nodes_:
self.nodes_.add(n1)
if n2 not in self.nodes_:
self.nodes_.add(n2)
self.edges_.add((n1, n2))
def del_node(self, n):
"""deletes the node 'n' from the graph, raises an error if no such node exists
"""
self.nodes_.remove(n)
for edge in self.edges_.copy():
if n in edge:
self.edges_.remove(edge)
def del_edge(self, n1, n2):
"""deletes the edge connecting 'n1' and 'n2' from the graph, raises an
error if no such edge exists
"""
self.edges_.remove((n1, n2))
def has_node(self, n):
"""True if node 'n' is contained in the graph, False if not.
"""
return n in self.nodes_
def neighbors(self, n):
"""returns the list of all nodes connected to 'n' by edges, raises an
error if n is not in g
"""
if n not in self.nodes_:
raise ValueError("Node not in graph")
neighbors = set()
for edge in self.edges_:
if edge[0] is n:
neighbors.add(edge[1])
return list(neighbors)
def adjacent(self, n1, n2):
"""returns True if there is an edge connecting n1 and n2, False if not,
raises an error if either of the supplied nodes are not in g
"""
if n1 not in self.nodes_ or n2 not in self.nodes_:
raise ValueError("Both nodes not in graph")
for edge in self.edges_:
if n1 in edge and n2 in edge:
return True
return False
| true |
dfc818c931c516d40f82d5d2b16c18bd2b2ff20d | vibhor3081/GL_OD_Tracker | /lib.py | 2,986 | 4.1875 | 4 | import pandas as pd
def queryTable(conn, tablename, colname, value, *colnames):
"""
This function queries a table using `colname = value` as a filter.
All columns in colnames are returned. If no colnames are specified, `select *` is performed
:param conn: the connection with the database to be used to execute/fetch the query
:param tablename: the tablename to query
:param colname: the column to filter by
:param value: the value to filter by
:param colnames: the columns to fetch in the result
"""
if not colnames: colnames = "*"
else: colnames = ', '.join(colnames)
df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname}='{value}'", conn)
return df
def queryTableNew(conn, tablename, colname1, value1, colname2, value2, *colnames):
"""
This function queries a table using `colname = value` as a filter.
All columns in colnames are returned. If no colnames are specified, `select *` is performed
:param conn: the connection with the database to be used to execute/fetch the query
:param tablename: the tablename to query
:param colname: the column to filter by
:param value: the value to filter by
:param colnames: the columns to fetch in the result
"""
if not colnames: colnames = "*"
else: colnames = ', '.join(colnames)
df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname1}='{value1}' AND {colname2}= '{value2}'", conn)
return df
def currencyFormatter(n):
"""
Format a number as it if were currency. Force two decimal places of precision
:param n: a number to format
"""
s = format(round(n, 2), ',') # formatted with ','s as the 100s separator
if '.' not in s: s += '.'
tail = len(s.rsplit('.',1)[-1])
s += '0'*(2-tail) # rpad decimal precision to 2 places
return s
def cumsumByGroup(df):
"""
Given a dataframe, group the dateaframe by AccounNumber. Sort each group by date, multiply the Amount by -1 for CR/DR and perform a cumsum
:param df: a pandas dataframe containing transaction information across multiple accounts for one customer
"""
df.sort_values(by=['AccountNumber', 'Date'], inplace=True, ignore_index=True) # we can sort by date here, just the one time, rather than having to sort each group individually
# get a signed amount by CR/DR
df['NetAmount'] = df.Amount
df.loc[df.CRDR=='DR', 'NetAmount'] = df[df.CRDR=='DR']['NetAmount']*-1
df['AvailableBalance'] = None # new column for the cumsum
for accountNum in df.AccountNumber.unique(): # cumsum for each account number
df.loc[df.AccountNumber==accountNum, 'AvailableBalance'] = df[df.AccountNumber==accountNum].NetAmount.cumsum()
df.sort_values(by=['Date'], inplace=True, ignore_index=True) # sort again by date, so that all transactions are stratified by date
df.fillna(value='', inplace=True) # so that None's don't show up in the st.write(df)
return df
| true |
e617e0788ff6129a6717d7cc26bb2a9fe2e7f12b | yasmineElnadi/python-introductory-course | /Assignment 2/2.9.py | 330 | 4.1875 | 4 | #wind speed
ta=float(input("Enter the Temperature in Fahrenheit between -58 and 41:"))
v=eval(input("Enter wind speed in miles per hour:"))
if v < 2:
print("wind speed should be above or equal 2 mph")
else:
print("the wind chill index is ", format(35.74 + (0.6215*ta) - (35.75* v**0.16) + (0.4275 * ta * v**0.16), ".5f"))
| true |
1b6d2d0843efad0980c4fa09aa7388c3b1eb609c | birkirkarl/assignment5 | /Forritun/Æfingardæmi/Hlutapróf 1/practice2.py | 241 | 4.28125 | 4 | #. Create a program that takes two integers as input and prints their sum.
inte1= int(input('Input the first integer:'))
inte2= int(input('Input the second integer:'))
summan= int(inte1+inte2)
print('The sum of two integers is:',+summan)
| true |
18ad8bcf6e920438f101c955b30c4e4d11f72e4b | birkirkarl/assignment5 | /Forritun/Assignment 10 - lists/PascalTriangle.py | 422 | 4.15625 | 4 | def make_new_row(row):
new_row = []
for i in range(0,len(row)+1):
if i == 0 or i == len(row):
new_row.append(1)
else:
new_row.append(row[i]+row[i-1])
return new_row
# Main program starts here - DO NOT CHANGE
height = int(input("Height of Pascal's triangle (n>=1): "))
new_row = []
for i in range(height):
new_row = make_new_row(new_row)
print(new_row) | true |
b74ac298e5cba51c032cee6114decf658a67f494 | dhurataK/python | /score_and_grades.py | 804 | 4.1875 | 4 | def getGrade():
print "Scores and Grades"
for i in range(0,9):
ip = input()
if(ip < 60):
print "You failed the exam. Your score is: "+str(ip)+" Good luck next time!"
elif (ip >= 60 and ip <= 69):
print "Score: "+str(ip)+"; Your grade is D"
elif (ip >= 70 and ip <= 79):
print "Score: "+str(ip)+"; Your grade is C"
elif (ip >= 80 and ip <= 89):
print "Score: "+str(ip)+"; Your grade is B"
elif (ip >= 90 and ip <= 100):
print "Score: "+str(ip)+"; Your grade is A"
elif (ip > 100):
print "Invalid score! "+str(ip)
print "End of the program. Bye! "
getGrade()
# Looks great, but what happens if I supply a grade below 60 or over 100? Just something to think about.
| true |
495dffd2bb07f45cc5bb355a1a00d113c2cd6288 | cadyherron/mitcourse | /ps1/ps1a.py | 981 | 4.46875 | 4 | # Problem #1, "Paying the Minimum" calculator
balance = float(raw_input("Enter the outstanding balance on your credit card:"))
interest_rate = float(raw_input("Enter the annual credit card interest rate as a decimal:"))
min_payment_rate = float(raw_input("Enter the minimum monthly payment rate as a decimal:"))
monthly_interest_rate = interest_rate / 12
number_of_months = 1
total_amount_paid = 0
while number_of_months <= 12:
min_payment = round(min_payment_rate * balance, 2)
total_amount_paid += min_payment
interest_paid = round(interest_rate / 12 * balance, 2)
principle_paid = min_payment - interest_paid
balance -= principle_paid
print "Month: ", number_of_months
print "Minimum monthly payment: ", min_payment
print "Principle paid: ", principle_paid
print "Remaining balance: ", balance
number_of_months += 1
print "RESULT"
print "Total amount paid: ", total_amount_paid
print "Remaining balance: ", balance
| true |
f3fb695d70656cd48495be8fc89af09dd3cee40a | learning-triad/hackerrank-challenges | /gary/python/2_if_else/if_else.py | 838 | 4.40625 | 4 | #!/bin/python3
#
# https://www.hackerrank.com/challenges/py-if-else/problem
# Given a positive integer n where 1 <= n <= 100
# If n is even and in the inclusive range of 6 to 20, print "Weird"
# If n is even and greater than 20, print "Not Weird"
def check_weirdness(n):
"""
if n is less than 1 or greater than 100, return "Not Applicable"
if n is odd, return "Weird"
if n is even and in the inclusive range of 6 to 20, return "Weird"
if n is even and in the inclusive range of 2 to 5, return "Not Weird"
if n is even and greater than 20, return "Not Weird"
"""
if n < 1 or n > 100:
return "Not Applicable"
return "Not Weird" if n % 2 == 0 and (2 <= n <= 5 or n > 20) else "Weird"
if __name__ == '__main__':
n = int(input().strip())
result = check_weirdness(n)
print(result)
| true |
1083052e37b5556980972557425aeac95fa7931b | arensdj/math-series | /series_module.py | 2,753 | 4.46875 | 4 | # This function produces the fibonacci Series which is a numeric series starting
# with the integers 0 and 1. In this series, the next integer is determined by
# summing the previous two.
# The resulting series looks like 0, 1, 1, 2, 3, 5, 8, 13, ...
def fibonacci(n):
"""
Summary of fibonacci function: computes the fibonacci series which is a
numeric series starting with integers 0 and 1. The next integer in series
is determined by summing the previous two and looks like
0, 1, 1, 2, 3, 5, 8, 13, ...
Parameters:
n (int): positive integer n
Returns:
int: Returns the nth value of the fibonacci numbers
"""
array = []
index = 1
array.append(index)
array.append(index)
total = 0
for i in range(index, n):
total = array[i - 1] + array[i]
array.append(total)
return array[i]
# This function produces the Lucas Numbers. This is a related series of integers
# that start with the values 2 and 1.
# This resulting series looks like 2, 1, 3, 4, 7, 11, 18, 29, ...
def lucas(n):
"""
Summary of lucas function: computes the lucas series which is a related series
of integers that start with the values 2 and 1 and looks like
2, 1, 3, 4, 7, 11, 18, 29, ...
Parameters:
n (int): positive integer n
Returns:
int: Returns the nth value of the lucas numbers
"""
array = []
index = 1
array.append(index+1)
array.append(index)
total = 0
for i in range(index, n):
total = array[i -1] + array[i]
array.append(total)
return array[i]
# This function produces numbers from the fibonacci series if there are no
# optional parameters. Invoking this function with the optional arguments 2 and 1
# will produce values from the lucas numbers.
def sum_series(n, arg1=0, arg2=1):
"""
Summary of sum_series function: computes a series of numbers based on the
arguments. One required argument will produce fibonacci numbers. One argument and optional arguments 2 and 1 produces the lucas series.
Parameters:
n (int): positive integer n
arg1 (int): (optional) positive integer arg1
arg2 (int): (optional) positive integer arg2
Returns:
int: Returns the nth value of either the fibonacci numbers or the lucas numbers
"""
array = []
total = 0
index = 1
# if optional arguments are not included in function call, produce
# fibonacci numbers
if ( (arg1 == 0) and (arg2 == 1) ):
array.append(index)
array.append(index)
else:
# optional numbers were included in function call. Produce lucas numbers
array.append(index+1)
array.append(index)
for i in range(index, n):
total = array[i - 1] + array[i]
array.append(total)
return array[i]
| true |
ce9d1cd697671c12003a39b17ee7a9bfebf0103d | dlaststark/machine-learning-projects | /Programming Language Detection/Experiment-2/Dataset/Train/Python/letter-frequency-3.py | 890 | 4.125 | 4 | import string
if hasattr(string, 'ascii_lowercase'):
letters = string.ascii_lowercase # Python 2.2 and later
else:
letters = string.lowercase # Earlier versions
offset = ord('a')
def countletters(file_handle):
"""Traverse a file and compute the number of occurences of each letter
return results as a simple 26 element list of integers."""
results = [0] * len(letters)
for line in file_handle:
for char in line:
char = char.lower()
if char in letters:
results[ord(char) - offset] += 1
# Ordinal minus ordinal of 'a' of any lowercase ASCII letter -> 0..25
return results
if __name__ == "__main__":
sourcedata = open(sys.argv[1])
lettercounts = countletters(sourcedata)
for i in xrange(len(lettercounts)):
print "%s=%d" % (chr(i + ord('a')), lettercounts[i]),
| true |
7424e3d1c91b4052176e86aeedc9261a86490a14 | kiukin/codewars-katas | /7_kyu/Descending_order.py | 546 | 4.125 | 4 | # Kata: Descending Order
# https://www.codewars.com/kata/5467e4d82edf8bbf40000155/train/python
# Your task is to make a function that can take any non-negative integer as a argument and
# return it with its digits in descending order. Essentially, rearrange the digits to
# create the highest possible number.
# Examples:
# Input: 21445 Output: 54421
# Input: 145263 Output: 654321
# Input: 123456789 Output: 987654321
def descending_order(num):
sorted_num = sorted([d for d in str(num)],reverse=True)
return int("".join(sorted_num)) | true |
36a0cb1db271953430c191c321286014bc97ed6d | Asabeneh/Fundamentals-of-python-august-2021 | /week-2/conditionals.py | 997 | 4.40625 | 4 | is_raining = False
if is_raining:
print('I have to have my umbrella with me')
else:
print('Go out freely')
a = -5
if a > 0:
print('The value is positive')
elif a == 0:
print('The value is zero')
elif a < 0:
print('This is a negative number')
else:
print('It is something else')
# weather = input('What is the weather like today? ').lower()
# if weather == 'rainy':
# print('Go out with an umbrella')
# elif weather == 'cloudy':
# print('There is a possibility of rain.')
# elif weather == 'sunny':
# print('Go out freely and enjoy the sunny day.')
# elif weather == 'snowy':
# print('It may be slippery.')
# else:
# print('No one knows about today weather')
a = 3
value = 'Positive' if a > 0 else 'Negative'
print(value)
if a > 0:
if a % 2 == 0:
print('It is a positive even number')
else:
print('It is a positive odd number')
elif a == 0:
print('The number is zero')
else:
print('The number is negaive')
| true |
d6e5435f634beb7a11f6095bb3f697fbeb426fb8 | hossein-askari83/python-course | /28 = bult in functions.py | 898 | 4.25 | 4 |
number = [0, 9, 6, 5, 4, 3, -7, 1, 2.6]
print("-----------") # all , any
print(any(number)) # if just one of values was true it show : true (1 and other numbers is true)
print(all(number)) # if just one of values was false it show : false (0 is false)
print("-----------") # min , max
print(max(number)) # show maximum of numbers
print(min(number)) # show minimum of numbers
print("-----------") # sorted , reversed
print(sorted(number)) # sort numbers from smallest to biggest
print(list(reversed(number))) # show reversed list
print("-----------") # len , abs
print(len(number)) # show number of value in list
print(abs(number[6])) # abs = absolute : show "قدر مطلق"
print("-----------") # sum , round
print(sum(number)) # show sum of list values
# note : sum (varible , some sumber) if write a number after varible it show sum of "numbers + number"
print(round(number[8])) | true |
0e4a586b1bfb3a97d3311b61d8653e0041c42eb0 | sinceresiva/DSBC-Python4and5 | /areaOfCone.py | 499 | 4.3125 | 4 | '''
Write a python program which creates a class named Cone and write a
function calculate_area which calculates the area of the Cone.
'''
import math
class ConeArea:
def __init__(self):
pass
def getArea(self, r, h):
#SA=πr(r+sqrt(h**2+r**2))
return math.pi*r*(r+math.sqrt(h**2+r**2))
coneArea=ConeArea()
radius=input("Input the radius (numeric):")
height=input("Input the height (numeric):")
print("Area is {}".format(coneArea.getArea(float(radius),float(height)))) | true |
928d5d403a69cd99e6c9ae579a6fc34b87965c1c | kostyafarber/info1110-scripts | /scripts/rain.py | 468 | 4.125 | 4 | rain = input("Is it currently raining? ")
if rain == "Yes":
print("You should take the bus.")
elif rain == "No":
travel = int(input("How far in km do you need to travel? "))
if travel > 10:
print("You should take the bus.")
elif travel in range(2, 11):
print("You should ride your bike.")
elif travel < 2:
print("You should walk.")
# if you use the range function with a if statement you use in not the equality operator
| true |
a2d0a7288f4fc9ce22f9f1447e1e70046b80b30b | tschutter/skilz | /2011-01-14/count_bits_a.py | 733 | 4.125 | 4 | #!/usr/bin/python
#
# Given an integer number (say, a 32 bit integer number), write code
# to count the number of bits set (1s) that comprise the number. For
# instance: 87338 (decimal) = 10101010100101010 (binary) in which
# there are 8 bits set. No twists this time and as before, there is
# no language restriction.
#
import sys
def main():
number = int(sys.argv[1])
if number < 0:
number = -number
#import gmpy
#print gmpy.digits(number, 2)
nsetbits = 0
while number != 0:
if number % 2 == 1:
nsetbits += 1
number = number // 2 # // is integer division
print "Number of bits set = %i" % nsetbits
return 0
if __name__ == '__main__':
sys.exit(main())
| true |
1d48da6a7114922b7e861afa93ddc03984815b0c | iZwag/IN1000 | /oblig3/matplan.py | 477 | 4.21875 | 4 | # Food plan for three residents
matplan = { "Kari Nordmann": ["brod", "egg", "polser"],
"Magda Syversen": ["frokostblanding", "nudler", "burger"],
"Marco Polo": ["oatmeal", "bacon", "taco"]}
# Requests a name to check food plan for
person = input("Inquire the food plan for a resident, by typing their name: ")
# Prints feedback for the inquiry
if person in matplan:
print(matplan[person])
else:
print("Sorry, that person doesn't seem to be a resident here.")
| true |
914134c3475f4618fa39fbbde917a4ada837968f | iZwag/IN1000 | /oblig5/regnefunksjoner.py | 1,933 | 4.125 | 4 | # 1.1
# Function that takes two parameters and returns the sum
def addisjon(number1, number2):
return number1 + number2
# 1.2
# Function that subtracts the second number from the first one
def subtraksjon(number1, number2):
return number1 - number2
# 1.2
# Function that divides the first argument by the second
# Also added an assertion to test for 0 in denominator
def divisjon(number1, number2):
assert(number2 != 0),"Division by 0 is illegal"
return number1/number2
# 1.3
# Converts inches to centimeter and tests for an input <= 0
def tommerTilCm(antallTommer):
assert(antallTommer > 0), "Inches must be greater than 0"
return antallTommer * 2.54
# 1.4
# User input is run through the above functions and tested
def skrivBeregninger():
print("Utregninger:")
number1 = float(input("Skriv inn tall 1: "))
number2 = float(input("Skriv inn tall 2: "))
print("")
print("Resultat av summering: %.1f" % addisjon(number1, number2))
print("Resultat av subtraksjon: %.1f" % subtraksjon(number1, number2))
print("Resultat av divisjon: %.1f" % divisjon(number1, number2))
print("")
print("Konvertering fra tommer til cm:")
number3 = float(input("Skriv inn et tall: "))
print("Resultat: %.2f" % tommerTilCm(number3))
# 1.1
# Prints the results of addition
print(addisjon(1,3))
# 1.2
# Testing all the other functions with assert
assert(subtraksjon(5,7) == -2),"Subtraction didn't work!"
assert(subtraksjon(1,-8) == 9),"Subtraction didn't work!"
assert(subtraksjon(-5,-5) == 0), "Subtraction didn't work!"
assert(divisjon(10,2) == 5),"Division didn't work!"
assert(divisjon(-2,2) == -1),"Division didn't work!"
assert(divisjon(-8,4) == -2),"Division didn't work!"
# 1.3
# Tests the inches to cm function
assert(tommerTilCm(3) > 0),"Converting from inches didn't work!"
# 1.4
# Runs the user test without arguments
skrivBeregninger()
| true |
67b284c3f8dcaed9bdde75429d81c7c96f31847c | keithkay/python | /python_crash_course/functions.py | 2,432 | 4.78125 | 5 | # Python Crash Course
#
# Chapter 8 Functions
# functions are defined using 'def'
def greeting(name):
"""Display a simple greeting""" # this is an example of a docstring
print("Hello, " + name.title() + "!")
user_name = input("What's your name?: ")
greeting(user_name)
# in addition to the normal positional arguements for a function, you can
# pass 'keyword arguements' to a function, and provide a default for an
# arguement, essentially making it optional (you can also just make it
# optional without a default by using =''
def describe_pet(pet_name, animal_type='cat'):
"""Display information about a pet"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
# now when calling 'describe_pet' we either ensure they are in the correct
# order, or we explictly assign them, illustrated here:
describe_pet('harry', 'hamster')
describe_pet(animal_type='dog', pet_name='willie')
describe_pet('lois')
# functions can also return a value, using, you guessed it 'return'
def format_name(fname, lname, mname=''):
"""Return a full name, neatly formatted."""
if mname:
full_name = fname + ' ' + mname + ' ' + lname
else:
full_name = fname + ' ' + lname
return full_name.title()
my_name = format_name('keith', 'kAy')
print(my_name)
print(format_name('J', 'Seymor', 'Thomas'))
# functions can be set up to receive and arbitrary number of arguements
# using '*' tells Python to create a tuple in which to store all the
# arguements received
def make_pizza(*toppings):
"""Print a list of the toppings requested"""
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# you can also use '**' to pass a dictionary of unknown structure, but
# the dictionary must be passed as keyword-value pairs
def build_profile(fname, lname, **user_info):
"""
Build a dictionary containing everyting we know about a user.
"""
profile = {}
profile['first_name'] = fname
profile['last_name'] = lname
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print("")
print(user_profile) | true |
03ec200798e7dfd44352b6997e3b6f2804648732 | keithkay/python | /python_crash_course/classes.py | 776 | 4.5 | 4 | # Python Crash Course
#
# Chapter 9 OOP
# In order to work with an object in Python, we first need to
# define a class for that object
class Dog():
"""A simple class example"""
def __init__(self, name, age):
"""Initializes name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command"""
print(self.name.title() + " rolled over!")
my_dog = Dog('rosey',11)
print("My dog's name is " + my_dog.name.title() + ".")
print(my_dog.name.title() + " is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over() | true |
d146d5541c713488ed3e3cc0497baea68cf368ff | tcsfremont/curriculum | /python/pygame/breaking_blocks/02_move_ball.py | 1,464 | 4.15625 | 4 | """ Base window for breakout game using pygame."""
import pygame
WHITE = (255, 255, 255)
BALL_RADIUS = 8
BALL_DIAMETER = BALL_RADIUS * 2
# Add velocity component as a list with X and Y values
ball_velocity = [5, -5]
def move_ball(ball):
"""Change the location of the ball using velocity and direction."""
ball.left = ball.left + ball_velocity[0]
ball.top = ball.top + ball_velocity[1]
return ball
def game():
"""Main function for the game."""
WIDTH = 800
HEIGHT = 600
# Define the ball as a square box the size of the ball
# We can use this to check collision later
ball = pygame.Rect(300, HEIGHT - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER)
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Breaking Blocks")
clock = pygame.time.Clock()
# Game Loop
while True:
# Set max frames per second
clock.tick(30
# Fill the screen on every update
screen.fill(BLACK)
# Event Handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
# Move ball
ball = move_ball(ball)
# Draw ball
pygame.draw.circle(screen, WHITE, (ball.left + BALL_RADIUS, ball.top + BALL_RADIUS), BALL_RADIUS)
# Paint and refresh the screen
pygame.display.flip()
if __name__ == "__main__":
game() | true |
56cb3dc1b9ef863246aa518d8a83b90b3f0c2d9d | trcooke/57-exercises-python | /src/exercises/Ex07_area_of_a_rectangular_room/rectangular_room.py | 830 | 4.125 | 4 | class RectangularRoom:
SQUARE_FEET_TO_SQUARE_METER_CONVERSION = 0.09290304
lengthFeet = 0.0
widthFeet = 0.0
def __init__(self, length, width):
self.lengthFeet = length
self.widthFeet = width
def areaFeet(self):
return self.lengthFeet * self.widthFeet
def areaMeters(self):
return round(self.areaFeet() * self.SQUARE_FEET_TO_SQUARE_METER_CONVERSION, 3)
if __name__ == "__main__":
length = input("What is the length of the room in feet? ")
width = input("What is the width of the room in feet? ")
print("You entered dimensions of " + length + " feet by " + width + " feet.")
print("The area is")
room = RectangularRoom(float(length), float(width))
print(str(room.areaFeet()) + " square feet")
print(str(room.areaMeters()) + " square meters.")
| true |
9ba7fb40eacf3ebca5c5fb9a5ac9e823f1ef9df0 | mccabedarren/python321 | /p12.p3.py | 1,098 | 4.46875 | 4 | #Define function "sqroot" (Function to find the square root of input float)
#"Sqroot" calculates the square root using a while loop
#"Sqroot" gives the number of guesses taken to calculate square root
#The program takes input of a float
#if positive the program calls the function "sqroot"
#if negative the program prints the error message: "Error: Number must be greater than 0"
def sqroot(number):
epsilon = 0.01
step = epsilon**2
numguesses=0
root = 0.0
while abs(number-root **2) >=epsilon and root <=number:
root += step
numguesses +=1
if numguesses % 100000 == 0:
print('Still running. Number of guesses:',numguesses)
print ('Number of guesses:',numguesses)
if abs (number-root**2) < epsilon:
return ('The approximate square root of',number,'is',root)
else:
return('Failed to find the square root of',number)
number = float(input('Enter the number for which you wish to calculate the square root:'))
if number > 0:
print (sqroot(number))
else:
print("Error: Number must be greater than 0")
| true |
dc5b545562df84e36ce8696cdaa33e0239a37001 | mccabedarren/python321 | /p13.p2.py | 431 | 4.46875 | 4 | #Program to print out the largest of two user-entered numbers
#Uses function "max" in a print statement
def max(a,b):
if a>b:
return a
else:
return b
#prompt the user for two floating-point numbers:
number_1 = float(input("Enter a number: "))
number_2 = float(input("Enter another number: "))
print ("The largest of", number_1,"and", number_2, "is", max(number_1, number_2))
print("Finished!")
| true |
e0fc45ba2b2da28b629f3c6bf7ce6c85d4334ca4 | elizabethadventurer/Treasure-Seeker | /Mini Project 4 part 1.py | 1,575 | 4.28125 | 4 | # Treasure-Seeker
#Introduction
name = input("Before we get started, what's your name?")
print("Are you ready for an adventure", name, "?")
print("Let's jump right in then, shall we?")
answer = input("Where do you thnk we should start? The old bookstore, the deserted pool, or the abandoned farm?")
if answer == "the deserted pool" or "deserted pool" or "Pool" or "The deserted pool" or "pool" or "the pool" or "Deserted pool" or "deserted pool" or "the pool":
print("Oooh, a spooky pool? Sure, why not? Lets see if there's even any water left...maybe a drowned spirit?!")
if answer == "the old bookstore" or "the bookstore" or "bookstore" or "The old bookstore" or "Bookstore":
print("The bookstore huh? Sounds like the lesser of three evils.")
if answer == "the abandoned farm" or "the farm" or "The farm" or "Farm" or "The abandoned farm" or "farm":
print("Hmm...sounds dangerous..but since you picked it...I guess I must join you. Whatever happens....happens.")
name2 = input("Honestly...there seems to be more to this than meets the eye. Do you trust me ?")
if name2 == "Yes" or name2 =="yes":
print("Thanks for the confidence boost!")
answer2 = input("We should move forward...right? *Answer in yes/no")
if answer2 == "Yes" or answer2 == "yes":
print("Okay...)
if answer2 == "No" or answer2 == "no":
print("Whew, bye bye.")
exit(3)
if name == "No" or name == "no":
print("Ouch, okay. Good luck getting through this without any hints...in fact I suggest you restart the game...cuz you ain’t going nowhere no more.")
exit()
| true |
6e6545bf2e9b4a7ff360d8151e6418168f777ff8 | sagarujjwal/DataStructures | /Stack/StackBalancedParens.py | 986 | 4.15625 | 4 | # W.A.P to find the given parenthesis in string format is balanced or not.
# balanced: {([])}, [()]
# non balanced: {{, (()
from stack import Stack
def is_match(p1, p2):
if p1 == '[' and p2 == ']':
return True
elif p1 == '{' and p2 == '}':
return True
elif p1 == '(' and p2 == ')':
return True
else:
return False
def is_paren_balanced(paren_string):
s=Stack()
is_balanced=True
index=0
while index < len(paren_string) and is_balanced:
paren=paren_string[index]
if paren in '[{(':
s.push(paren)
else:
if s.is_empty():
is_balanced = False
else:
top=s.pop()
if not is_match(top,paren):
is_balanced = False
index+=1
if s.is_empty() and is_balanced:
return True
else:
return False
#print(is_paren_balanced('([{(){}()}])'))
print(is_paren_balanced('[{(){}{}]'))
| true |
380769147add0ecf5e071fa3eb5859ee2eded6da | alexmeigz/code-excerpts | /trie.py | 1,185 | 4.40625 | 4 | # Trie Class Definition
# '*' indicates end of string
class Trie:
def __init__(self):
self.root = dict()
def insert(self, s: str):
traverse = self.root
for char in s:
if not traverse.get(char):
traverse[char] = dict()
traverse = traverse.get(char)
traverse['*'] = '*'
def find(self, s: str) -> bool:
traverse = self.root
for char in s:
if not traverse.get(char):
return False
traverse = traverse.get(char)
return traverse.get('*', '') == '*'
def delete(self, s: str) -> bool:
traverse = self.root
for char in s:
if not traverse.get(char):
return False
traverse = traverse.get(char)
if not traverse.get('*'):
return False
traverse.pop("*")
return True
'''
# Sample Usage
if __name__ == "__main__":
t = Trie()
t.insert("hello")
print(t.find("he"))
t.insert("he")
print(t.find("he"))
t.delete("he")
print(t.find("he"))
print(t.root)
''' | true |
03995a46974520e6d587e3c09a24fa1c98a6423f | brownboycodes/problem_solving | /code_signal/shape_area.py | 443 | 4.1875 | 4 | """
Below we will define an n-interesting polygon.
Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1.
An n-interesting polygon is obtained by taking the n - 1-interesting polygon
and appending 1-interesting polygons to its rim, side by side.
You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.
"""
def shapeArea(n):
return n**2+(n-1)**2
| true |
298ce4a268c6242ee4b18db1b5029995ebaa183f | brownboycodes/problem_solving | /code_signal/adjacent_elements_product.py | 362 | 4.125 | 4 | """
Given an array of integers,
find the pair of adjacent elements that has the largest product
and return that product.
"""
def adjacentElementsProduct(inputArray):
product=0
for i in range(0,len(inputArray)-1):
if inputArray[i]*inputArray[i+1]>product or product==0:
product=inputArray[i]*inputArray[i+1]
return product
| true |
98edf9ce118f9641f55d08c6527da8d01f03b49a | kirubeltadesse/Python | /examq/q3.py | 604 | 4.28125 | 4 | # Kirubel Tadesse
# Dr.Gordon Skelton
# J00720834
# Applied Programming
# Jackson State University
# Computer Engineering Dept.
#create a program that uses a function to determine the larger of two numbers and return the larger to the main body of the program and then print it. You have to enter the numbers from the keyboard so you have to use input.
#defining the function
def printLarg():
x = input("Enter your first number: ")
y = input("Enter your second number: ")
holder=[x,y]
larg = max(holder)
print("the larger number is : ")
print(larg)
return larg
#calling the function
printLarg()
| true |
9b773282655c5e3a6a35f9b59f22ddb221386870 | AyvePHIL/MLlearn | /Sorting_alogrithms.py | 2,275 | 4.21875 | 4 | # This is the bubbleSort algorithm where we sort array elements from smallest to largest
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed (more efficient).
# Last i elements are already in place
for j in range(0, n - i - 1):
# traverse the array from 0 to n-i-1. Swap if the element found is greater than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
# Another bubble sort algorithm but returns the no. of times elements were swapped from small to large
def minimumSwaps(arr):
swaps = 0
temp = {}
for i, val in enumerate(arr):
temp[val] = i
for i in range(len(arr)):
# because they are consecutive, I can see if the number is where it belongs
if arr[i] != i + 1:
swaps += 1
t = arr[i] # Variable holder
arr[i] = i + 1
arr[temp[i + 1]] = t
# Switch also the tmp array, no need to change i+1 as it's already in the right position
temp[t] = temp[i + 1]
return swaps
def minimumSwappnumber(arr):
noofswaps = 0
for i in range(len(arr)):
while arr[i] != i + 1:
temp = arr[i]
arr[i] = arr[arr[i] - 1]
arr[temp - 1] = temp
noofswaps += 1
print noofswaps
# A QuickSort algorithm where we pivot about a specified int in a array by partitioning the array into two parts
def quick_sort(sequence):
if len(sequence)<=1:
return(sequence)
else:
pivot = sequence.pop()
items_bigger = []
items_smaller = []
for item in sequence:
if item > pivot:
items_bigger.append(item)
else:
items_smaller.append(item)
return quick_sort(items_smaller) + [pivot] + quick_sort(items_bigger)
# This is the testing phase, where the above algorithms are tested and tried by FIRE🔥🔥🔥
testing_array = [3, 56, 0, 45, 2324, 2, 12, 123, 434, 670, 4549, 3, 4.5, 6]
print(bubbleSort(testing_array))
print(quick_sort(testing_array))
print(minimumSwappnumber(testing_array)) | true |
2486925e16396536f048f25889dc6d3f7675549a | NathanielS/Week-Three-Assignment | /PigLatin.py | 500 | 4.125 | 4 | # Nathaniel Smith
# PigLatin
# Week Three Assignment
# This program will take input from the usar, translate it to PigLatin,
# and print the translated word.
def main ():
# This section of code ask for input from the usar and defines vowels
word = input("Please enter an English word: ")
vowels = "AEIOUaeiou"
# This section of code translates the usars input into PigLatin
if word[0] in vowels:
print(word + "yay")
else:
print(word[1:] + word[0] + "ay")
main () | true |
4d872b88871da0fd909f4cb71954a3f0f8d0f43f | RocketDonkey/project_euler | /python/problems/euler_001.py | 470 | 4.125 | 4 | """Project Euler - Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def Euler001():
num = 1000
r = range(3, num)
for index, i in enumerate(xrange(3, num)):
if sum(bool(j) for j in (i%3, i%5)) > 1:
r[index] = 0
return sum(r)
def main():
print Euler001()
if __name__ == '__main__':
main()
| true |
54406e46376433c727027b350e1b7b6a6f818181 | kamil-fijalski/python-reborn | /@Main.py | 2,365 | 4.15625 | 4 | # Let's begin this madness
print("Hello Python!")
int1 = 10 + 10j
int2 = 20 + 5j
int3 = int1 * int2
print(int3)
print(5 / 3) # floating
print(5 // 3) # integer
str1 = "Apple"
print(str1[0])
print(str(len(str1)))
print(str1.replace("p", "x") + " " + str1.upper() + " " + str1.lower() + " " + str1.swapcase())
# method "find" works like "instr" in SQL
# tuples are immutable and they can be nesting
tuple1 = ("A", "B", 1, 2, 3.14, 2.73)
print(type(tuple1))
print(tuple1[2])
tupleStr = tuple1[0:2]
print(tupleStr)
tupleNest = (("Jazz", "Rock"), "Dance", ("Metal", "Folk"))
print(tupleNest[0][1])
# list are mutable -> square brackets / list can nested other lists and tuples
list1 = [5, 1, 3, 10, 8]
print(sorted(list1))
list1.extend([7, 12]) # extend adds two elements -> APPEND adds one element (list with elements 7, 12)
print(list1)
list1[0] = 100 # are mutable
print(list1)
del(list1[2])
print(list1)
str2 = "Quick brown fox jumps over the lazy dog"
listSplit = str2.split()
print(listSplit)
listSplit2 = listSplit[:] # clone existing list
# sets / collection -> unique element => curly brackets
set1 = set(list1)
print(set1)
set1.add(256)
set1.add(512)
print(set1)
set1.remove(100)
print(set1)
check = 512 in set1 # checking if element exists in given set
print(check)
set88 = {2, 4, 5, 7, 9}
set99 = {1, 3, 5, 8, 9}
print(set88 & set99) # intersect of the two sets / or "intersection" method
print(set88.union(set99))
print(set88.difference(set99))
# dictionaries -> key: value
# keys are immutable and unique, values can be mutable and duplicates
dict1 = {1: "one", 2: "two", 3: "three"}
print(dict1)
print(dict1[3])
dict1[1000] = "thousand" # adding new element
print(dict1)
del(dict1[2]) # delete element
print(dict1)
print(2 in dict1) # checking if element exists in dict
print(dict1.keys())
print(dict1.values())
age = 25
if age < 25:
print("less")
elif age > 25:
print("more")
else:
print("equal")
squares = {"red", "blue", "yellow", "black", "purple"}
for i in squares:
print(i)
str88 = ""
for r in range(10, 15):
str88 = str88 + str(r) + " "
print(str88)
str99 = ""
while age < 30:
str99 = str99 + "bu" + " "
age += 1
print(str99 + "BUM!")
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
nn = input("Give me a word... ")
print(factorial(len(nn)))
| true |
7b2d9aa4ece7d8a777def586cb3af02685eac071 | omer-goder/python-skillshare-beginner | /conditions/not_in_keyword.py | 347 | 4.1875 | 4 | ### 17/04/2020
### Author: Omer Goder
### Checking if a value is not in a list
# Admin users
admin_users = ['tony','frank']
# Ask for username
username = input("Please enter you username?")
# Check if user is an admin user
if username not in admin_users:
print("You do not have access.")
else:
print("Access granted.")
| true |
f457e6763c190e10b297912019aa76ad7dc899a4 | omer-goder/python-skillshare-beginner | /dictionary/adding_user_input_to_a_dictionary.py | 997 | 4.375 | 4 | ### 04/05/2020
### Author: Omer Goder
### Adding user input to a dictionary
# Creat an empty dictionary
rental_properties = {}
# Set a flag to indicate we are taking apllications
rental_open = True
while rental_open: # while True
# prompt users for name and address.
username = input("\nWhat is your name?")
rental_property = input("What is the address of the property you would like to rent?")
# Store the responses in a dictionary
rental_properties[username] = rental_property
# Ask if the user knows anyone else who would like to rent their property
repeat = input("\nDo you know anyone how might like to rent out their propery?\t(Y/N)").lower()
if repeat == 'y':
continue # just to check code upgrading option
else:
rental_open = False
# Adding propery is complete
print('\n---Property to rent---')
for username, rental_property in rental_properties.items():
print(username.title() + " have a property at " + rental_property.title() + " to rent.")
| true |
fd1ccd8e94a9a2f7d68ce5caade21b4727a5356e | omer-goder/python-skillshare-beginner | /conditions/or_keyword.py | 418 | 4.21875 | 4 | ### 17/04/2020
### Author: Omer Goder
### Using the OR keyword to check values in a list
# Names registered
registered_names = ['tony','frank','mary','peter']
username = input("Please enter username you would like to use.\n\n").lower()
#Check to see if username is already taken
if username in registered_names:
print("Sorry, username is already taken.")
else:
print("This username is available")
| true |
34c12dde56d3cb3176565750b4292d6a062105df | omer-goder/python-skillshare-beginner | /list/a_list_of_numbers.py | 552 | 4.25 | 4 | ### 15/04/2020
### Author: Omer Goder
### Creating a list of numbers
# Convert numbers into a list
numbers = list(range(1,6))
print(numbers)
print('\n')
# print("List of even number in the range of 0 to 100:")
even_numbers = list(range(0,102, 2))
print(even_numbers)
print('\n')
print("List of square values of 1 to 10:")
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
print('\n')
digits = [1,2,3,4,5]
print(min(digits))
print(max(digits))
print(sum(digits))
print('\n')
| true |
97360bd4a55477713e3868b9c9af811143151aca | omer-goder/python-skillshare-beginner | /class/class_as_attribute(2).py | 1,127 | 4.34375 | 4 | ### 11/05/2020
### Author: Omer Goder
### Using a class as an attribute to another class
class Tablet():
"""This will be the class that uses the attribute."""
def __init__(self, thickness, color, battery):
"""Initialize a parameter as a class"""
self.thickness = thickness
self.color = color
self.battery = battery
self.screen = Screen()
class Screen():
"""This will be the attribute for the other class."""
def __init__(self, glass_grade = 'gorilla glass', color = 'BW', screen_size = '8"'):
"""Initalize the attributes of the Attrib class."""
self.glass = glass_grade
self.color = color
self.screen_size = screen_size
def screen_type(self):
"""Print the attributes"""
print("Glass: " + self.glass + "\nSize: " + self.screen_size + ".")
def screen_color(self):
"""Print the arguments."""
print("This is a " + self.color + " screen.\n")
my_tablet = Tablet('5 mm', 'green', '4800 mAh')
my_tablet.screen.screen_type()
my_tablet.screen.screen_color()
my_screen = Screen('Gorilla 8', 'color', '10"')
my_tablet.screen = my_screen
my_tablet.screen.screen_type()
my_tablet.screen.screen_color() | true |
f385856290585e7e625d82c6f1d0b6f5aa171f71 | akram2015/Python | /HW4/SECURITY SCANNER.py | 631 | 4.4375 | 4 | # this program Prompt user for a file name, and read the file, then find and report if file contains a string with a string ("password=") in it.
# file name = read_it.txt
found = True
userinput = input ("Enter the file name: ")
string = input ("Enter the string: ")
myfile = open (userinput) # open the file that might contain a string
for line in myfile:
if string in line:
print ("The line which contain the string", string, "is: ", line) # print the line that contain the string
found = False
myfile.close()
if found:
print ("The string", string, "does not exist in", userinput, "file!")
| true |
8e2989008f52b56dee43360378533c5b4a757d90 | josego85/livescore-cli | /lib/tt.py | 2,078 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import re
'''
module to convert the given time in UTC to local device time
_convert() method takes a single time in string and returns the local time
convert() takes a list of time in string format and returns in local time
NOTE: any string not in the format "digits:digits" will be returned as is
USAGE:
>>>convert(['19:45','18:15','5:45','512','FT'])
['01:00','00:00','11:30','512','FT']
isgreat(time1,time2) takes two time strings such as "4:30" and "12"15"
and returns if the first time is greater than the second.
if time1>time2: return 1
if time2>time1: return -1
if time1==time2: return 0
NOTE: the function stalls if not in the above format
USAGE:
>>>isgreat("3:00","4:15")
-1
'''
if time.daylight:
offsetHour = time.altzone / 3600.0
else:
offsetHour = time.timezone / 3600.0
hour = int(-offsetHour)
minute = int(-offsetHour * 60 % 60)
def _convert(time):
if bool(re.match(r'[0-9]{1,2}:[0-9]{1,2}', time)):
time = list(map(int, time.split(':')))
time[1] += minute
time[0] += hour
if time[1] > 59:
time[1] -= 60
time[0] += 1
elif time[1] < 0:
time[1] += 60
time[0] -= 1
if time[0] < 0:
time[0] += 24
elif time[0] > 23:
time[0] -= 24
time = _fix(str(time[0])) + ":" + _fix(str(time[1]))
return time
def _fix(y):
if len(y) == 1:
y = '0' + y
return y
def convert(times):
times = list(map(_convert, times))
return times
def is_great(time1, time2):
t1 = list(map(int, time1.split(':')))
t2 = list(map(int, time2.split(':')))
if t1[0] > t2[0]:
return 1
elif t2[0] > t1[0]:
return -1
else:
if t1[1] > t2[1]:
return 1
elif t2[1] > t1[1]:
return -1
else:
return 0
def datetime_now():
return time.strftime("%c")
| true |
0c900e9b4ad2f2b3e904ee61661cda39ed458646 | shivraj-thecoder/python_programming | /Swapping/using_tuple.py | 271 | 4.34375 | 4 | def swap_tuple(value_one,value_two):
value_one,value_two=value_two,value_one
return value_one,value_two
X=input("enter value of X :")
Y=input("enter value of Y :")
X, Y=swap_tuple(X,Y)
print('value of X after swapping:', X)
print('value of Y after swapping:', Y) | true |
1c77967940f1f8b17e50f4f2632fb34a13b3daf0 | sweetysweat/EPAM_HW | /homework1/task2.py | 692 | 4.15625 | 4 | """
Given a cell with "it's a fib sequence" from slideshow,
please write function "check_fib", which accepts a Sequence of integers, and
returns if the given sequence is a Fibonacci sequence
We guarantee, that the given sequence contain >= 0 integers inside.
"""
from typing import Sequence
def check_fibonacci(data: Sequence[int]) -> bool:
seq_len = len(data)
fib1 = 0
fib2 = 1
if seq_len == 0 or seq_len == 1:
return False
if data[0] == 0 and data[1] == 1:
for i in range(2, seq_len):
fib1, fib2 = fib2, fib1 + fib2
if not fib2 == data[i]:
return False
return True
else:
return False
| true |
d10cd2ab04df7e4720f72bf2f5057768e8bfad3f | sweetysweat/EPAM_HW | /homework8/task_1.py | 1,745 | 4.21875 | 4 | """
We have a file that works as key-value storage,
each line is represented as key and value separated by = symbol, example:
name=kek last_name=top song_name=shadilay power=9001
Values can be strings or integer numbers.
If a value can be treated both as a number and a string, it is treated as number.
Write a wrapper class for this key value storage that works like this:
storage = KeyValueStorage('path_to_file.txt') that has its keys and values accessible as collection
items and as attributes.
Example: storage['name'] # will be string 'kek' storage.song_name # will be 'shadilay'
storage.power # will be integer 9001
In case of attribute clash existing built-in attributes take precedence. In case when value cannot be assigned
to an attribute (for example when there's a line 1=something) ValueError should be raised.
File size is expected to be small, you are permitted to read it entirely into memory.
"""
import re
from typing import Union
class KeyValueStorage:
def __init__(self, path: str):
self.storage = dict()
self.create_class_attributes(path)
def create_class_attributes(self, path: str):
with open(path, 'r') as f:
for line in f:
key, value = line.strip().split('=')
if not re.search(r'^[a-zA-z_][\w]*$', key, re.ASCII):
raise ValueError("The key can only contain ASCII symbols and can't starts with numbers!")
value = int(value) if value.isdigit() else value
self.storage[key] = value
def __getattr__(self, attr_name: str) -> Union[str, int]:
return self.storage[attr_name]
def __getitem__(self, attr_name: str) -> Union[str, int]:
return self.storage[attr_name]
| true |
50e50015e425e4ba5a924775ded68b79cba31edc | sawall/advent2017 | /advent_6.py | 2,729 | 4.21875 | 4 | #!/usr/bin/env python3
# memory allocation
#
#### part one
#
# The debugger would like to know how many redistributions can be done before a blocks-in-banks
# configuration is produced that has been seen before.
#
# For example, imagine a scenario with only four memory banks:
#
# The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen
# for redistribution.
# Starting with the next bank (the fourth bank) and then continuing to the first bank, the second
# bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second
# banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4
# 1 2.
# Next, the second bank is chosen because it contains the most blocks (four). Because there are four
# memory banks, each gets one block. The result is: 3 1 2 3.
# Now, there is a tie between the first and fourth memory banks, both of which have three blocks.
# The first bank wins the tie, and its three blocks are distributed evenly over the other three
# banks, leaving it with none: 0 2 3 4.
# The fourth bank is chosen, and its four blocks are distributed such that each of the four banks
# receives one: 1 3 4 1.
# The third bank is chosen, and the same thing happens: 2 4 1 2.
# At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite
# loop is detected after the fifth block redistribution cycle, and so the answer in this example is
# 5.
#
# Given the initial block counts in your puzzle input, how many redistribution cycles must be
# completed before a configuration is produced that has been seen before?
def day6():
inp = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5'
memory = [int(i) for i in inp.strip().split()]
past_states = []
num_banks = len(memory)
cycles = 0
while (hash(tuple(memory)) not in past_states):
past_states.append(hash(tuple(memory)))
realloc_blocks = max(memory)
realloc_cursor = memory.index(max(memory))
memory[realloc_cursor] = 0
while realloc_blocks > 0:
realloc_cursor += 1
memory[(realloc_cursor) % num_banks] += 1
realloc_blocks -= 1
cycles += 1
print('-= advent of code DAY SIX =-')
print(' part one: total cycles until loop detected = ' + str(cycles))
#### part two
#
# Out of curiosity, the debugger would also like to know the size of the loop: starting from a state
# that has already been seen, how many block redistribution cycles must be performed before that
# same state is seen again?
loop_start = past_states.index(hash(tuple(memory)))
print(' part two: loop size = ' + str(cycles - loop_start))
day6()
| true |
910db0a0156d0f3c37e210ec1931fd404f1357e9 | aymhh/School | /Holiday-Homework/inspector.py | 1,095 | 4.125 | 4 | import time
print("Hello there!")
print("What's your name?")
name = input()
print("Hello there, " + name)
time.sleep(2)
print("You have arrived at a horror mansion!\nIt's a large and spooky house with strange noises coming from inside")
time.sleep(2)
print("You hop out of the car and walk closer...")
time.sleep(2)
print("You tread carefully onto the rotten woodpath porch.")
time.sleep(2)
print("You trip over a loose plank of wood and fall over")
time.sleep(2)
print("Your knee hurts. But you notice something under the porch...")
time.sleep(2)
print("It's a box...")
time.sleep(2)
print("Inside it was a blooded hand!")
time.sleep(2)
print("You wonder wether to go inside or leave...")
question = input("What is your next move?\n - Type in `inside` to go inside the house\n - Type in `leave` to leave away!\n")
if question == "inside":
print("you pick yourself up and head inside the house and only to be greated with a mysterious character, the door slams behind you and you are trapped!")
if question == "leave":
print("you rush back into your car and drift away, very far!")
| true |
24d025d8a89380a8779fbfdf145083a9db64fc07 | shahad-mahmud/learning_python | /day_16/unknow_num_arg.py | 324 | 4.15625 | 4 | def sum(*nums: int) -> int:
_sum = 0
for num in nums:
_sum += num
return _sum
res = sum(1, 2, 3, 5)
print(res)
# Write a program to-
# 1. Declear a funtion which can take arbitary numbers of input
# 2. The input will be name of one or persons
# 3. In the function print a message to greet every one
| true |
382a8a2f5c64f0d3cd4c1c647b97e19e2c137fda | shahad-mahmud/learning_python | /day_3/if.py | 417 | 4.1875 | 4 | # conditional statement
# if conditon:
# logical operator
# intendation
friend_salary = float(input('Enter your salary:'))
my_salary = 1200
if friend_salary > my_salary:
print('Friend\'s salary is higher')
print('Code finish')
# write a program to-
# a. Take a number as input
# b. Identify if a number is positive
# sample input 1: 10
# sample output 1: positive
# sample inout 2: -10
# sample output:
| true |
ec55765f79ce87e5ce0f108f873792fecf5731f6 | shahad-mahmud/learning_python | /day_7/python_function.py | 347 | 4.3125 | 4 | # def function_name(arguments):
# function body
def hello(name):
print('Hello', name)
# call the funciton
n = 'Kaka'
hello(n)
# Write a program to-
# a. define a function named 'greetings'
# b. The function print 'Hello <your name>'
# c. Call the function to get the message
# d. Modify your function and add a argument to take your name | true |
b0824befae2b1d672ac6ec693f97e7c801366c0c | srinivasdasu24/regular_expressions | /diff_patterns_match.py | 1,534 | 4.53125 | 5 | """
Regular expression basics, regex groups and pipe character usage in regex
"""
import re
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
phoneNum_regex = re.compile(
r'\d\d\d-\d\d\d-\d\d\d\d') # re.compile to create regex object \d is - digit numeric character
mob_num = phoneNum_regex.search(message)
# print(phoneNum_regex.findall(message)) # findall returns a list of all occurences of the pattern
print(mob_num.group) # regex object has group method which tells the matching pattern
# pattern with different groups - groups are created in regex strings using parentheses
phoneNum_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') # this pattern will have twwo groups
mob_num = phoneNum_regex.search(message)
mob_num.group() # gives entire match
mob_num.group(1) # gives first 3 digits 1 is first set of parentheses , 2 is second and so on
mob_num.group(2) # gives remaining pattern
# o/p is : '415-555-1011'
# :'415'
# : '555-1011'
# pattern with matching braces( () )
phoneNum_regex = re.compile(r'\(\d\d\d\) \d\d\d-\d\d\d\d')
mo = phoneNum_regex.search('My number is (415) 555-4243')
mo.group()
# o/p is : '(415) 555-4243
# matching multiple patterns
bat_regx = re.compile(r'Bat(man|mobile|copter|bat)') # pipe | symbol used to match more than one pattern
mo = bat_regx.search('I like Batman movie')
mo.group() # o/p is 'Batman'
# if search method doesn't find pattern it returns None
mo = bat_regx.search('Batmotorcycle lost a wheel')
mo == None # prints True
| true |
3865e404fdf198c9b8a6cb674783aa58af2c8539 | rehul29/QuestionOfTheDay | /Question8.py | 561 | 4.125 | 4 | # minimum number of steps to move in a 2D grid.
class Grid:
def __init__(self, arr):
self.arr = arr
def find_minimum_steps(self):
res = 0
for i in range(0, len(self.arr)-1):
res = res + self.min_of_two(self.arr[i], self.arr[i+1])
print("Min Steps: {}".format(res))
def min_of_two(self, first, second):
x1, y1 = first
x2, y2 = second
return max(abs(x2-x1), abs(y2-y1))
if __name__ == "__main__":
arr = [(0,0),(1,1),(1,2)]
sol = Grid(arr)
sol.find_minimum_steps()
| true |
1e30e88c79c0941f93ce4239a74eb38d4dcd02f5 | dtekluva/first_repo | /datastructures/ato_text.py | 1,616 | 4.125 | 4 | # sentence = input("Please enter your sentence \nWith dashes denoting blank points :\n ")
# replacements = input("Please enter your replacements in order\nseperated by commas :\n ")
# ## SPLIT SENTENCE INTO WORDS
# sentence_words = sentence.split(" ")
# print(sentence_words)
# ## GET CORRESPONDING REPLACEMENTS
# replacement_words = replacements.split(',')
# replacement_index = 0
# # search and replace dashes with replacement words
# for i in range(len(sentence_words)):
# ## FIND DASHES IN WORDS OF GIVEN SENTENCE
# if sentence_words[i].find("_") != -1:
# ## REPLACE DASHES WITH CORRESPONDING REPLACEMENT WORDS.
# sentence_words[i] = sentence_words[i].replace("_", replacement_words[replacement_index])
# replacement_index+=1
# full_sentence = " ".join(sentence_words)
# print(full_sentence)
# prices = [200, 300, 400, 213, 32 ]
# marked = 1.5
# for i in range(len(prices)):
# prices[i] = prices[i]*marked
# print(prices)
x = 20
# def do_somthing():
# global x
# x = 30
# print(x)
# return 23
# do_somthing()
# print(x)
# def numbers(one, two, three):
# print("One : ",one, "Two : ", two, "Three : ", three)
# numbers(2,3,1)
# numbers(two = 2, three = 3, one = 1)
def greet(name, gender):
if gender == "male":
print(f"Hello Mr {name}..!")
else:
print(f"Hello Mrs {name}..!")
greet("Bolu", "female")
people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)]
# for person in people:
# greet(person[0], person[1])
for name, gender in people:
greet(name, gender) | true |
b9a6f5dfa9f184d24f941addd3aa219dcc16a1bd | harrylb/anagram | /anagram_runner.py | 2,436 | 4.3125 | 4 | #!/usr/bin/env python3
"""
anagram_runner.py
This program uses a module "anagram.py" with a boolean function
areAnagrams(word1, word2)
and times how long it takes that function to correctly identify
two words as anagrams.
A series of tests with increasingly long anagrams are performed,
with the word length and time to identify output to a file in the
same directory, anagram_results.csv, for easy import into a spreadsheet
or graphing program.
@author Richard White
@version 2017-02-20
"""
import random
import time
import anagram
def create_anagrams(word_length):
"""
Creates a random collection of lowercase English letters, a-z, of a
specified word_length, as well as a randomized rearranging of those
same letters. The strings word1 and word2 are anagrams of each other,
and returned by this function.
"""
baseword = []
for i in range(word_length):
baseword.append(chr(int(random.random()*26) + 97)) # random letter
word1 = ''.join(baseword) # Convert list to string
# Now go through baseword and pop off random letters to create word2.
word2 = ""
while len(baseword) > 0:
word2 += baseword.pop(int(random.random() * len(baseword)))
return word1, word2
def main():
"""
This main program includes some timed pauses and timed countdowns to
give the user some sense of the time it takes to sort the words.
"""
MAX_WORD_LENGTH = 10000
print("ANAGRAM RUNNER")
results = []
for word_length in range(int(MAX_WORD_LENGTH/10), MAX_WORD_LENGTH, int(MAX_WORD_LENGTH/10)):
word1,word2 = create_anagrams(word_length)
print("Comparing",word1,"and",word2)
print("Starting test")
start = time.time()
result = anagram.areAnagrams(word1,word2)
stop = time.time()
print("Stopping test")
if result:
print("The two words are anagrams")
else:
print("The two words are not anagrams")
print("Time elapsed: {0:.4f} seconds".format(stop - start))
results.append((word_length, stop-start))
outfile = open("anagram_results.csv","w")
outfile.write("Anagram length in letters,time to verify(seconds)\n")
for result in results:
outfile.write(str(result[0]) + "," + str(result[1]) + "\n")
outfile.close()
print("anagram_results.csv successfully written")
if __name__ == "__main__":
main()
| true |
7008f73c39d0cffbb93e317e2e4371b16e4a1152 | ozgecangumusbas/I2DL-exercises | /exercise_01/exercise_code/networks/dummy.py | 2,265 | 4.21875 | 4 | """Network base class"""
import os
import pickle
from abc import ABC, abstractmethod
"""In Pytorch you would usually define the `forward` function which performs all the interesting computations"""
class Network(ABC):
"""
Abstract Dataset Base Class
All subclasses must define forward() method
"""
def __init__(self, model_name='dummy_network'):
"""
:param model_name: A descriptive name of the model
"""
self.model_name = model_name
@abstractmethod
def forward(self, X):
"""perform the forward pass through a network"""
def __repr__(self):
return "This is the base class for all networks we will use"
@abstractmethod
def save_model(self, data=None):
""" each model should know what are the relevant things it needs for saving itself."""
class Dummy(Network):
"""
Dummy machine
"""
def __init__(self, model_name="dummy_machine"):
"""
:param model_name: A descriptive name of the model
"""
super().__init__()
self.model_name = model_name
def forward(self, x):
"""
:param x: The input to the network
:return: set x to any integer larger than 59 to get passed
"""
########################################################################
# TODO #
# Implement the dummy machine function. #
# #
########################################################################
pass
########################################################################
# END OF YOUR CODE #
########################################################################
return x
def __repr__(self):
return "A dummy machine"
def save_model(self, data=None):
directory = 'models'
model = {self.model_name: self}
if not os.path.exists(directory):
os.makedirs(directory)
pickle.dump(model, open(directory + '/' + self.model_name + '.p', 'wb'))
| true |
a477f9345fcd496943a6543eba007b5a883bc1d0 | Ayaz-75/Prime-checker-program | /pime_checker.py | 267 | 4.125 | 4 | # welcome to the prime number checker
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
return "not prime"
else:
return "prime"
num = int(input("Enter number: "))
print(prime_checker(number=num))
| true |
52230fa21f292174d6bca6c86ebcc35cc860cb69 | kisyular/StringDecompression | /proj04.py | 2,900 | 4.625 | 5 | #############################################
#Algorithm
#initiate the variable "decompressed_string" to an empty string
#initiate a while True Loop
#prompt the user to enter a string tocompress
#Quit the program if the user enters an empty string
#Initiate a while loop if user enters string
#find the first bracket and convert it into an integer
#find the other bracket ")"
#find the comma index and convert it to an integer
#find the first number within the parenthesis and convert it to integer
#find the index of the second number within the comma and the last parenthesis
#get the string within the first index and the second index numbers
#find the decompressed string. Given by the string entered plus string within
#update the new string entered to a newer one
#replace the backslash with a new line during printing
#print the decompressed string
Backslash = "\\"
#initiate the variable "decompressed_string" to an empty string
decompressed_string =""
print()
#initiate a while True Loop
while True:
#prompt the user to enter a string tocompress
string_entered=input ("\nEnter a string to decompress (example 'to be or not to(13,3)' \
will be decompressed to 'TO BE OR NOT TO BE' see more examples in the pdf attached \
or press 'enter' to quit: ")
#Quit the program if the user enters an empty string
if string_entered=="" :
print("There is nothing to decompress. The Program has halted")
break
#Initiate a while loop if user enters string
while string_entered.find("(") != -1:
#find the first bracket and convert it into an integer
bracket_1st=int(string_entered.find("("))
#find the other bracket nd convert to an integer ")"
sec_bracket=int(string_entered.find(")"))
#find the comma index and convert it to an integer
comma=int(string_entered.find(",", bracket_1st, sec_bracket))
# find the first number within the parenthesis and convert it to integer
index_1st = int(string_entered[bracket_1st+1: comma])
# find the index of the second number within the comma and the last parenthesis
sec_indx=int(string_entered[comma+1 : sec_bracket])
#get the string within the first index and the second index numbers
string_within=string_entered[bracket_1st - index_1st \
: bracket_1st - index_1st + sec_indx]
#find the decompressed string. Given by the string entered plus string within
decompressed_string=(string_entered [ : bracket_1st] + string_within)
#update the new string entered to a newer one
string_entered=decompressed_string + string_entered[sec_bracket+1: ]
#replace the backslash with a new line during printing
decompressed_string=string_entered.replace(Backslash, "\n")
#print the decompressed string
print("\nYour decompressed string is:" "\n")
print(decompressed_string)
| true |
e3e8af1efd0adbca06cba83b769bc93d10c13d69 | jalalk97/math | /vec.py | 1,262 | 4.125 | 4 | from copy import deepcopy
from fractions import Fraction
from utils import to_fraction
class Vector(list):
def __init__(self, arg=None):
"""
Creates a new Vector from the argument
Usage:
>> Vector(), Vector(None) Vector([]) creates empty vector
>> Vector([5, 6, 6.7, Fraction(5, 6)]) creates vector with elements as list
"""
if arg is None:
super().__init__()
elif isinstance(arg, list):
super().__init__(to_fraction(arg))
elif isinstance(arg, Vector):
self = deepcopy(arg)
else:
raise TypeError('Invalid argument type:', arg)
def __getitem__(self, arg):
"""
Uses the basic list indexing
Usage:
>> v[0] returns the firt element
>> v[-1] returns the last element
>> v[:] shallow copy of vector elements
>> v[4:8] returns a sclice of the vectors element from 4 to 8
"""
return super().__getitem__(arg)
def __setitem__(self, arg, value):
"""
Uses the basic list indexing to set values
Usage:
>>
>>
>>
>>
"""
value = to_fraction(value)
super().__setitem__(arg, value)
| true |
a84f6776548484ef96ab81e0107bdd36385e416e | DasVisual/projects | /temperatureCheck/tempCheck2.py | 338 | 4.125 | 4 | #! python 3
# another version of temperature checker, hopefully no none result
print('What is the current temperature of the chicken?')
def checkTemp(Temp):
if Temp > 260:
return 'It is probably cooked'
elif Temp < 260:
return 'More heat more time'
Temp = int(input())
Result = checkTemp(Temp)
print(Result)
| true |
cd3b288dc03da30a69439727191cb18e429d943a | olympiawoj/Algorithms | /stock_prices/stock_prices.py | 1,934 | 4.3125 | 4 | #!/usr/bin/python
"""
1) Understand -
Functions
- find_max_profit should receive a list of stock prices as an input, return the max profit that can be made from a single buy and sell. You must buy first before selling, no shorting
- prices is an array of integers which represent stock prices and we need to find the max, the min, and subtract
- TO solve this, we need to find out the max profit and minimum
[1, 3, 2]
Max profit = 2
3-2 = 1
[4, 8, 1]
I have to buy 4
Sell 8
Max profit = 4
So we start with the maxProfit = arr[1] - arr[0]
We need to track the min price arr[0]
TO DO
- Iterate through array prices
- For each current_price, if that price - min price > maxProfit, then define a new max
- For each current price, if that cur price is less than the min price, define a new min
- Update variables if we find a higher max profit and/or a new min price
"""
import argparse
def find_max_profit(prices):
# Tracks min price and current max profit
minPrice = prices[0]
maxProfit = prices[1] - minPrice
# could also do
# for currentPrice in prices[1:]
for i in range(1, len(prices)):
print('loop', prices[i])
print('i', i)
maxProfit = max(prices[i] - minPrice, maxProfit)
minPrice = min(prices[i], minPrice)
print('min', minPrice)
print('maxProfit', maxProfit)
return maxProfit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(
description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(
profit=find_max_profit(args.integers), prices=args.integers))
# print(find_max_profit([1050, 270, 1540, 3800, 2]))
| true |
17209e6ac514e763706e801ef0fb80a88ffb56b7 | Swaraajain/learnPython | /learn.python.loops/stringQuestions.py | 457 | 4.1875 | 4 | # we have string - result must be the first and the last 2 character of the string
name = "My Name is Sahil Nagpal and I love Programming"
first2index = name[:2]
last2index = name[len(name)-2:len(name)]
print(first2index + last2index)
#print(last2index)
#string.replace(old, new, count)
print(name.replace('e','r',2))
# question - find the longest word and print the word and length of the z
# question - remove the nth index element from the string
| true |
fbc2b174ff0abcb78531105634d19c6ec9022184 | 40309/Files | /R&R/Task 5.py | 557 | 4.28125 | 4 | checker = False
while checker == False:
try:
user_input = int(input("Please enter a number between 1-100: "))
except ValueError:
print("The value entered was not a number")
if user_input < 1:
print("The number you entered is too low, Try again")
elif user_input > 100:
print("The number you entered is too high, Try again")
else:
print()
print("The Number you entered is good")
print(user_input)
checker = True
print()
print()
print("End of Program")
| true |
707681af05d6cb4521bf4f729290e96e6c347287 | Dirac26/ProjectEuler | /problem004/main.py | 877 | 4.28125 | 4 | def is_palindromic(num):
"""Return true if the number is palindromic and false otehrwise"""
return str(num) == str(num)[::-1]
def dividable_with_indigits(num, digits):
"""Returns true if num is a product of two integers within the digits range"""
within = range(10 ** digits - 1)
for n in within[1:]:
if num % n == 0:
if num / n <= 10 ** digits - 1:
return True
return False
def largest_mult(digits):
"""Returns the largest palindromic number that is the product of two numbers with certain digits number"""
num = (10 ** digits - 1) ** 2
found = False
while not found:
if is_palindromic(num):
if dividable_with_indigits(num, digits):
return num
num -= 1
def main():
"""main funtion"""
print(largest_mult(3))
if __name__ == "__main__":
main() | true |
774edd572b1497b9a8bc9e1c0f6107147626f276 | max-moazzam/pythonCoderbyte | /FirstFactorial.py | 541 | 4.1875 | 4 | #Function takes in a number as a parameter and returns the factorial of that number
def FirstFactorial(num):
#Converts parameter into an integer
num = int(num)
#Creates a factorial variable that will be returned
factorial = 1
#While loop will keep multipying a number to the number 1 less than it until 1 is reached
while num > 1:
factorial = factorial * num
num = num - 1
return factorial
#May need to change to raw_input to just input depending on which version of Python used
print(FirstFactorial(raw_input()))
| true |
d9fbdc7310218e85b562a1beca25abe48e72ee8b | lcantillo00/python-exercises | /randy_guessnum.py | 305 | 4.15625 | 4 | from random import randint
num = randint(1, 6)
print ("Guess a number between 1 and 6")
answer = int(raw_input())
if answer==num:
print ("you guess the number")
elif num<answer:
print ("your number is less than the random #")
elif num>answer:
print("your number is bigger than the random #")
| true |
7b692f7ea4d8718261e528d07222061dc3e35de8 | michelmora/python3Tutorial | /BegginersVenv/dateAndTime.py | 757 | 4.375 | 4 | # Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch
# time. To get the date or time in Python we need to use the standard time module.
import time
ticks = time.time()
print("Ticks since epoch:", ticks)
# To get the current time on the machine, you can use the function localtime:
timenow = time.localtime(time.time())
print("Current time :", timenow)
# You can access each of the elements of the array:
timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])
# and use a combination for your own formatting. One alternative is to use the asctime function:
timenow = time.asctime(time.localtime(time.time()))
print(timenow)
| true |
4dd9a591648531943ccd60b984e1d3f0b72a800c | michelmora/python3Tutorial | /BegginersVenv/switch(HowToSimulate).py | 2,519 | 4.21875 | 4 | # An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
# OPTION No.1
def dog_sound():
return 'hau hau'
def cat_sound():
return 'Me au'
def horse_sound():
return 'R R R R'
def cow_sound():
return 'M U U U'
def no_sound():
return "Total silence"
switch = {
'dog': dog_sound,
'cat': cat_sound,
'horse': horse_sound,
'cow': cow_sound,
}
# value = input("Enter the animal: ")
# if value in switch:
# sound = switch[value]()
# else:
# sound = no_sound()
# # default
#
# print(sound)
# OPTION No.2
# define the function blocks
def zero():
print("You typed zero.\n")
def sqr():
print("n is a perfect square\n")
def even():
print("n is an even number\n")
def prime():
print("n is a prime number\n")
# map the inputs to the function blocks
options = {0: zero,
1: sqr,
4: sqr,
9: sqr,
2: even,
3: prime,
5: prime,
7: prime,
}
# options[10]()
# OPTION NO. 3
# A very elegant way
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
print(numbers_to_strings(2))
# OPTION NO. 4
# Dictionary Mapping for Functions
def zero():
return "zero"
def one():
return "one"
def numbers_to_functions_to_strings(argument):
switcher = {
0: zero,
1: one,
2: lambda: "two",
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "nothing")
# Execute the function
return func()
print(numbers_to_functions_to_strings(3))
# OPTION NO. 5
# Dispatch Methods for Classes
# If we don't know what method to call on a class, we can use a dispatch method to determine it at runtime.
class Switcher(object):
def numbers_to_methods_to_strings(self, argument):
"""Dispatch method"""
# prefix the method_name with 'number_' because method names
# cannot begin with an integer.
method_name = 'number_' + str(argument)
# Get the method from 'self'. Default to a lambda.
method = getattr(self, method_name, lambda: "nothing")
# Call the method as we return it
return method()
def number_2(self):
return "two"
def number_0(self):
return "zero"
def number_1(self):
return "one"
tes = Switcher()
print(tes.numbers_to_methods_to_strings(4))
| true |
8dee8c987a27474de2b12a4a783dddc7aa142260 | darrengidado/portfolio | /Project 3 - Wrangle and Analyze Data/Update_Zipcode.py | 1,333 | 4.21875 | 4 | '''
This code will update non 5-digit zipcode.
If it is 8/9-digit, only the first 5 digits are kept.
If it has the state name in front, only the 5 digits are kept.
If it is something else, will not change anything as it might result in error when validating the csv file.
'''
def update_zipcode(zipcode):
"""Clean postcode to a uniform format of 5 digit; Return updated postcode"""
if re.findall(r'^\d{5}$', zipcode): # 5 digits 02118
valid_zipcode = zipcode
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{3}$', zipcode): # 8 digits 02118-029
valid_zipcode = re.findall(r'(^\d{5})-\d{3}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'(^\d{5})-\d{4}$', zipcode): # 9 digits 02118-0239
valid_zipcode = re.findall(r'(^\d{5})-\d{4}$', zipcode)[0]
return valid_zipcode
elif re.findall(r'CA\s*\d{5}', zipcode): # with state code CA 02118
valid_zipcode =re.findall(r'\d{5}', zipcode)[0]
return valid_zipcode
else: #return default zipcode to avoid overwriting
return zipcode
def test_zip():
for zips, ways in zip_print.iteritems():
for name in ways:
better_name = update_zipcode(name)
print name, "=>", better_name
if __name__ == '__main__':
test_zip()
| true |
3177bc787712977e88acaa93324b7b43c25016f9 | sudharsan004/fun-python | /FizzBuzz/play-with-python.py | 377 | 4.1875 | 4 | #Enter a number to find if the number is fizz,buzz or normal number
n=int(input("Enter a number-I"))
def fizzbuzz(n):
if (n%3==0 and n%5==0):
print(str(n)+"=Fizz Buzz")
elif (n%3==0):
print(str(n)+"=Fizz")
elif (n%5==0):
print(str(n)+"=Buzz")
else:
print(str(n)+"=Not Fizz or Buzz")
fizzbuzz(n)
#define a function
| true |
da04ab784745cdce5c77c0b6159e17d802011129 | sclayton1006/devasc-folder | /python/def.py | 561 | 4.40625 | 4 | # Python3.8
# The whole point of this exercise is to demnstrate the capabilities of
# a function. The code is simple to make the point of the lesson simpler
# to understand.
# Simon Clayton - 13th November 2020
def subnet_binary(s):
""" Takes a slash notation subnet and calculates the
number of host addresses """
if s[0] == "/":
a = int(s.strip("/"))
else:
a = int(s)
addresses = (2**(32-a))
return addresses
s = input("Enter your slash notation. Use a number or a slash (/27 or 27): ")
x = subnet_binary(s)
print(x)
| true |
bbfa62e0a73aa476ff8c7a2abd98c021c956d20e | Zeonho/LeetCode_Python | /archives/535_Encode_and_Decode_TinyURL.py | 1,708 | 4.125 | 4 | """
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your
encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny
URL and the tiny URL can be decoded to the original URL.
"""
class hashMap:
def __init__(self):
self.mapping = [[]]*25
def put(self, key, val):
hash_key = hash(val) % len(self.mapping)
bucket = self.mapping[hash_key]
key_exists = False
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket.append((hash_key, val))
else:
self.mapping[hash_key] = [(hash_key,val)]
return key
def get(self, key):
hash_key = hash(key) % len(self.mapping)
bucket = self.mapping[hash_key]
for i, kv in enumerate(bucket):
k,v = kv
return v
raise KeyError
class Codec:
def __init__(self):
self.urlShortener = hashMap()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
return self.urlShortener.put(hash(longUrl), longUrl)
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.urlShortener.get(shortUrl)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url)) | true |
ad6c9704c7f09a5fa1d1faab38eb5d43967026a4 | fagan2888/leetcode-6 | /solutions/374-guess-number-higher-or-lower/guess-number-higher-or-lower.py | 1,199 | 4.4375 | 4 | # -*- coding:utf-8 -*-
# We are playing the Guess Game. The game is as follows:
#
# I pick a number from 1 to n. You have to guess which number I picked.
#
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
#
# You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
#
#
# -1 : My number is lower
# 1 : My number is higher
# 0 : Congrats! You got it!
#
#
# Example :
#
#
#
# Input: n = 10, pick = 6
# Output: 6
#
#
#
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
low=1
high=n
num=(low+high)/2
while guess(num)!=0:
if guess(num)<0:
high=num
num=(low+high)/2
else:
low=num
num=(low+high)/2
if guess(num)!=0:
if num==low:
num=high
elif num==high:
num=low
return num
| true |
6a097f9f7027419ba0649e5017bc2e17e7f822d3 | fagan2888/leetcode-6 | /solutions/557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py | 773 | 4.1875 | 4 | # -*- coding:utf-8 -*-
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving 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.
#
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl=[]
for word in s.split(' '):
wordl=[]
for i in xrange(len(word)-1,-1,-1):
wordl.append(word[i])
sl.append(''.join(wordl))
rs=' '.join(sl)
return rs
| true |
6f4b3f90db0be1ccc197aacca9b625642c498aee | Raziel10/AlgorithmsAndMore | /Probability/PowerSet.py | 267 | 4.34375 | 4 | #Python program to find powerset
from itertools import combinations
def print_powerset(string):
for i in range(0,len(string)+1):
for element in combinations(string,i):
print(''.join(element))
string=['a','b','c']
print_powerset(string) | true |
da7bd9d5abbdd838c1110515dde30c459ed8390c | Smita1990Jadhav/GitBranchPracticeRepo | /condition&loops/factorial.py | 278 | 4.25 | 4 | num=int(input("Enter Number: "))
factorial=1
if num<1:
print("Factorial is not available for negative number:")
elif num==0:
print("factorial of 1 is zero: ")
else:
for i in range(1,num+1):
factorial=factorial*i
print("factorial of",num,"is",factorial) | true |
a3e1eadfdf24f44dc353726180eee97269844c45 | jjspetz/digitalcrafts | /py-exercises3/hello2.py | 517 | 4.34375 | 4 | #!/usr/bin/env python3
# This is a simple function that says hello using a command-line argument
import argparse
# formats the arguments for argparse
parser = argparse.ArgumentParser()
# requires at least one string as name
parser.add_argument('username', metavar='name', type=str, nargs='*',
help="Enter a name so the computer can say hello")
def hello(name):
print("Hello, {}!".format(name))
if __name__ == "__main__":
args = parser.parse_args()
hello(' '.join(args.username))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.