blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d6d13883deaedf3f3db0d95dda7a77fda53d5712 | CRaNkXD/PyMoneyOrga | /PyMoneyOrga/PyMoneyOrga/domain/account.py | 2,184 | 4.3125 | 4 | from dataclasses import dataclass
import datetime
@dataclass
class Transaction(object):
"""
Data class for transactions made from and to an account. Used in Account class.
"""
amount: int
new_balance: int
description: str
time_stamp: datetime.datetime
account_id: int = None # foreign key to Account
class Account(object):
"""
Class for defining an account.
"""
def __init__(self, acc_name, balance, currency, transactions=None):
if transactions is None:
transactions = []
self._acc_name = acc_name
self._balance = balance
self._currency = currency
self._transactions = transactions # list of Transaction objects
def __str__(self):
return f"Account Name: {self._acc_name}; Money in Account: {self._balance}"
def __repr__(self):
return f"Account Name: {self._acc_name}; Money in Account: {self._balance}"
def add_income(self, amount, description):
"""
Adds an income to the account which is than saved in the transactions list.
"""
self._balance += amount
self.transactions.append(
Transaction(
amount=amount,
new_balance=self._balance,
description=description,
time_stamp=datetime.datetime.now(),
)
)
def add_expense(self, amount, description):
"""
Adds an expense to the account which is than saved in the transactions list.
"""
self._balance -= amount
self.transactions.append(
Transaction(
amount=-amount,
new_balance=self._balance,
description=description,
time_stamp=datetime.datetime.now(),
)
)
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, balance):
self._balance = balance
@property
def acc_name(self):
return self._acc_name
@property
def currency(self):
return self._currency
@property
def transactions(self):
return self._transactions
| true |
47c8166a0ae2e8c9ef5d2b38fefe83d2983e18d4 | as0113-dev/Python-Data-Structure | /mergeSort.py | 1,078 | 4.1875 | 4 | def mergeSort(array):
#base case
if len(array) <= 1:
return array
#midpoint of "array"
mid = len(array)//2
#split array in half
leftSplit = array[:mid]
rightSplit = array[mid:]
#recursively call the splitting of array
leftSplit = mergeSort(leftSplit)
rightSplit = mergeSort(rightSplit)
#final step call the merge "helper" function that builds the array and sort them
return merge(leftSplit, rightSplit)
def merge(leftArr, rightArr):
#the array that we return in the end after filling it up
result = []
l_Index, r_Index = 0, 0
while l_Index < len(leftArr) and r_Index < len(rightArr):
if leftArr[l_Index] < rightArr[r_Index]:
result.append(leftArr[l_Index])
l_Index += 1
else:
result.append(rightArr[r_Index])
r_Index += 1
if l_Index == len(leftArr):
result += rightArr[r_Index:]
else:
result += leftArr[l_Index:]
return result
list1 = [22,15,10,18,100]
fixed_list1 = mergeSort(list1)
print(fixed_list1) | true |
2b93732d35dbee22032b49dc9968e6f07ad8ee89 | stavernatalia95/Lesson-5.2-Assignment | /Exercise #1.py | 781 | 4.34375 | 4 | # Assume you have the list xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
# Write a loop that prints each of the numbers on a new line
for i in xs:
print(i)
# Write a loop that prints each number and its square on a new line.
for i in xs:
print(i,i**2)
# Write a loop that adds all the numbers from the list into a variable called total.
# You should set the total variable to have the value 0 before you start adding them up,
# and print the value in total after the loop has completed.
total=0
for i in xs:
total+=i
print("Total:", total)
# Print the product of all the numbers in the list. (product means all multiplied together)
product=1
for i in xs:
product*=i
print("Product:", product) | true |
c2beb9e3beeb12a3e91f5189ea70fde4e4a07c87 | SHETU-GUHA/1st | /1st chapter.py | 1,128 | 4.375 | 4 | print('Hellow World!')
print ('What is your name?')
myName = input()
print ('it is good to meet you ' + myName)
print('The length of our name is :')
print (len(myName))
print ('what is your age?')
myAge = input ()
print ('You will be ' + str (int(myAge)+1) + 'in a year.')
#1. operator (*, -, / , +) values ('hello', -88.8, 5)
# variable (spam), string ('spam')
# int,floating point ,string
# after running the code bacon value is 21
# 'spam' + 'spamspam' = spamspamspam
'spam' * 3 =
spam
spam
spam
#Why is eggs a valid variable name while 100 is invalid?
Because variable names cannot begin with a number.
# What three functions can be used to get the integer, floating-point number, or string version of a value?
str()
int()
float()
#Why does this expression cause an error? How can you fix it?
'I have eaten ' + 99 + ' burritos.'
This expression causes an error because here'I have eaten' and 'burritos' are strings, while 99 is treated as integer. In order to fix the error and print 'I have eaten 99 burritos.', 99 needs '' around it to treat it as a string.
| true |
f204312c8a2bd68d75b89db21b8334c3d7d9191d | Anurag-12/learning-python | /Coroutines_Example/main.py | 2,464 | 4.3125 | 4 | '''
Both generator and coroutine operate over the data; the main differences are:
Generators produce data
Coroutines consume data
Coroutines are mostly used in cases of time-consuming programs, such as tasks related to machine learning or deep learning algorithms or in cases
where the program has to read a file containing a large number of data. In such situations, we do not want the program to read the file or data,
again and again, so we use coroutines to make the program more efficient and faster. Coroutines run endlessly in a program because they use a while
loop with a true or 1 condition so it may run until infinite time. Even after yielding the value to the caller, it still awaits further instruction
or calls. We have to stop the execution of coroutine by calling coroutine.close() function.
Syntax:
def myfunc():
while True:
value = (yield)
Execution is the same as of a generator. When you call a coroutine, nothing happens. They only run in response to the next() and send() methods.
Coroutine requires the use of the next statement first so it may start its execution. Without a next() it will not start executing. We can search
a coroutine by sending it the keywords as input using object name along with send(). The keywords to be searched are send inside the parenthesis.
send() — used to send data to coroutine
close() — to close the coroutine
'''
def searcher():
import time
# Some 4 seconds time consuming task
book = "This is a book on anurag and code with anurag and good"
time.sleep(4)
while True:
text = (yield) # whatever name is being passed to search
if text in book:
print("Your text is in the book")
else:
print("Text is not in the book")
search = searcher()
print("search started")
next(search)
print("Next method run")
search.send("anurag")
search.close()
#search.send("anurag") # this will throw error since the coroutine is closed
###############################################################
def names():
import time
names = "anurag harry haris carry amit ajey bhuvan shubham rahul aftab hrithik vivek ujjawal mohit rohit"
time.sleep(2)
while True:
text = (yield)
if text in names:
print("Your name is in the list.")
else:
print("Your name is not in the list.")
name = names()
next(name)
name.send(input("Type your Name: "))
| true |
d181bf517a3d745068e1e2de3af4d91abaf18b6b | Anurag-12/learning-python | /seek-tell-file/main.py | 861 | 4.4375 | 4 | #This code will change the current file position to 5, and print the rest of the line.
# Note: not all file objects are seekable.
f = open("myfile.txt", "r")
f.seek(5)
print( f.readline() )
f.close()
f = open("myfile.txt")
f.seek(11)
print(f.tell())
print(f.readline())
# print(f.tell())
print(f.readline())
# print(f.tell())
f.close()
###################################################
# With open(“file1txt”) as f, open(“file2.txt”) as g
'''advantages of With block:
Multiple files can be opened.
The files that are opened together can have different modes
Automatically closes file
Saves processing power by opening and closing file only when running code inside the block
'''
with open("harry.txt") as f:
a = f.readlines()
print(a)
# f = open("harry.txt", "rt")
# f.close()
| true |
5111dee03f6cdcc8dc76ffe3409b809fefaf4ffd | vijaypalmanit/daily_coding_problem | /daily_coding_problem_2.py | 649 | 4.125 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
# Follow-up: what if you can't use division?
def product(n):
arr=[]
for i in range(len(n)):
product=1
for j in range(len(n)):
if i != j:
product=product*n[j]
arr.append(product)
return arr
n=[6, 15, 10, 7]
print(product(n))
| true |
c4051d5b29c21c23b545cee418d14da0e11b29a0 | shaunakchitare/PythonLearnings | /function_programs.py | 2,152 | 4.40625 | 4 | #-------------------------------------------------------------------------------
#Exercise 1 - Creat a function that accepts 3 ardument and return their sum
print('\nExercise 1')
def add_numbers(x,y,z):
total = x + y + z
return total
total = add_numbers(5,1,9)
print(total)
#-------------------------------------------------------------------------------
#Exercise 2 - Create a
print('\nExercise 2')
def add_numbers_2(list_nums):
total = 0
for num in list_nums:
total = total + num
return total
total = add_numbers_2([4,3,7,5,8])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 3')
def add_numbers_3(list_nums_1,list_nums_2):
list_nums = list_nums_1 + list_nums_2
return add_numbers_2(list_nums)
total = add_numbers_3([4,3,7,5,8],[5,7,6,1,4])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 4')
def add_numbers_4(list_nums_1,list_nums_2,list_nums_3):
list_nums = list_nums_1 + list_nums_2 + list_nums_3
return add_numbers_2(list_nums)
total = add_numbers_4([4,3,7,5,8],[5,7,6,1,4],[9,5,7,0,2])
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 5')
def add_numbers_5(my_dict):
v1 = my_dict['a']
v2 = my_dict['b']
v3 = my_dict['c']
L1 = [v1,v2,v3]
r = sum(L1)
return r
total = add_numbers_5({'a':1,'b':2,'c':3})
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 6')
def add_numbers_6(my_dict):
values = my_dict.values()
r = sum(values)
return r
total = add_numbers_6({'a':1,'b':2,'c':3, 'd':4})
print(total)
#-------------------------------------------------------------------------------
print('\nExercise 7')
def add_numbers_7(kanha):
shaunak = kanha['s']
jas = kanha['j']
kedar = kanha['k']
shrijit = kanha['sh']
anvi = kanha['a']
Sjksha = [shaunak,jas,kedar,shrijit,anvi]
v = sum(Sjksha)
return v
total = add_numbers_7({'s':9,'j':10,'k':8,'sh':7,'a':6})
print(total)
| true |
1cd0a2fc2283355d1398aafb3fea2e57a50b5312 | kovokilla/python | /namedTuple.py | 684 | 4.375 | 4 | # Import the 'namedtuple' function from the 'collections' module
from collections import namedtuple
# Set the tuple
#tuple je v podstate object
individual = namedtuple("Nazov_identifikacia", "name age height")
user = individual(name="Homer", age=37, height=178)
user2 = individual(name="Peter", age=33, height=175)
# Print the tuple
print(user)
print(user2)
people = (user, user2)
# Print each item in the tuple
#looping through tuple of tuples
#v pythone loopujes inak, ked das for item in (collection of items), tak “item” bude uz ten tuple,
# takze ak chces jeho .name tak das item.name a nie collection[item].
for i in people:
print(i.name)
print(i.age)
print(i.height) | true |
0161d8a35ce81625815121d56e93b56162a62b95 | sabirul-islam/Python-Practice | /ANISUL ISLAM/list.py | 1,125 | 4.34375 | 4 | subjects = ['javascript', 'python', 'php', 'java', 'flutter', 'kotlin']
print(subjects)
print(subjects[1])
print(subjects[2:]) # print from 2 number index
print(subjects[-1])
print('python' in subjects) # check is this subject in here?(case sensitive)
print('golang' not in subjects) # it returns true
print(subjects + ['xamarin', 45]) # add new list
print(subjects * 3) # showing this list 3 times
print(len(subjects)) # showing length and count from 1
subjects.append('c++') # insrt a item
print(subjects)
subjects.insert(2, 'c') # insert a new item in a specific location
print(subjects)
subjects.remove('kotlin') # remove a item
print(subjects)
subjects.sort() # sort the list alphabeticaly
print(subjects)
subjects.reverse()
print(subjects)
subjects.pop() # remove the last item
print(subjects)
subjects.clear() # clear all the item
print(subjects)
subjectsCopy = subjects.copy() # copy old list in a new list
print(subjectsCopy)
subjectsIndex = subjects.index('java') # showing index of an item
print(subjectsIndex)
subjectsCount = subjects.count('kotlin') # an item how many times have in the list
print(subjectsCount) | true |
a2ebbe7a95c56145f67b5e46208e3bbced0c44d2 | Bokomoko/classes-and-operations-in-data-model-python | /main.py | 744 | 4.375 | 4 | class Polynomial:
# method to initialize the object with some values
def __init__(self, *coefs):
self.coefs = coefs
# function to represent the object (print)
# similar to __str__ but for debuging purposes
# it will be used if no __str__ method
def __repr__(self):
return 'Polynomial(*{!r})'.format(self.coefs)
# method to add two objects of this class
def __add__(self,other):
return Polynomial(*(x+y for x,y in zip(self.coefs,other.coefs)))
# method to evaluate the Polynomial
# can be used to implement a funcion based on the class
def __call__(self, number):
v = 0
for expo in self.coefs:
v+= number**expo
return v
p1 = Polynomial( 1, 2, 3)
p2 = Polynomial(3, 4, 3)
print(p1+p2) | true |
3ca81cce7fcf16010bd88b5fc94d932dd5834db0 | rodrigodata/learning | /pyhton/arithmetic_operations/arithmetic_operations.py | 434 | 4.1875 | 4 | # add
print(10 + 3) # 13
# subtract
print(10 - 4) # 6
#float
print(2.22 * 3) # 6.66
# multiplication
print(2 * 8) # 16
# division
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3 => Returns an integer from division
# modules
print(10 % 3) # 1 Returns the remaining
# exponation
print(10 ** 3) # 1000
####
#increment
### bad
x = 10
x = x + 3
print(x) # 13
### good
y = 10
y += 3
print(y) # 13
z = 20
z -= 10
print(z) # 10 | true |
3c9c29480c72a6e8082cd18297d94773ab531e4f | gedo147/Python | /ConvertClassToDictionary/BinaryTree.py | 719 | 4.1875 | 4 |
class BinaryTree:
def __init__(self,value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
tree = BinaryTree(10,left=BinaryTree(7,left=3, right=8), right=BinaryTree(15,left=11,right=17))
print(tree.__dict__)
print("So as we can see only the outer binaryTree class got converted into dictionary, it doesn't go into heirarchy")
print("So can we do something here")
res = tree.__dict__
for key, value in res.items():
if hasattr(value, '__dict__'): # This basically checks if object is something on which __dict__ can be called, for ex for value = 10, __dict__ can't be called.
res[key] = value.__dict__
print(res)
| true |
70ded69c41a75a06894364a029d28f77f54cad9c | ariannasg/python3-training | /standard_library/json_ops.py | 1,356 | 4.1875 | 4 | #!usr/bin/env python3
# working with JSON data
import json
import urllib.request
# use urllib to retrieve some sample JSON data
req = urllib.request.urlopen("http://httpbin.org/json")
data = req.read().decode('utf-8')
print(data)
# use the JSON module to parse the returned data
obj = json.loads(data)
# when the data is parsed, we can access it like any other object
print(obj["slideshow"]["author"])
for slide in obj["slideshow"]["slides"]:
print(slide["title"])
# python objects can also be written out as JSON
objdata = {
"name": "Joe Marini",
"author": True,
"titles": [
"Learning Python", "Advanced Python",
"Python Standard Library Essential Training"
]
}
# writing the above object as json to a file
with open("jsonoutput.json", "w") as fp:
json.dump(objdata, fp, indent=4)
# CONSOLE OUTPUT:
# {
# "slideshow": {
# "author": "Yours Truly",
# "date": "date of publication",
# "slides": [
# {
# "title": "Wake up to WonderWidgets!",
# "type": "all"
# },
# {
# "items": [
# "Why <em>WonderWidgets</em> are great",
# "Who <em>buys</em> WonderWidgets"
# ],
# "title": "Overview",
# "type": "all"
# }
# ],
# "title": "Sample Slide Show"
# }
# }
#
# Yours Truly
# Wake up to WonderWidgets!
# Overview
| true |
9835578b347135a0a3be9da82c7f1538b64843d1 | ariannasg/python3-training | /advanced/lambdas.py | 1,336 | 4.8125 | 5 | #!usr/bin/env python3
# lambdas are simple and small anonymous functions that are used in situations
# where defining a whole separate function would unnecessarily increase the
# complexity of the code and reduce readability.
# Lambdas can be used as in-place functions when using built-ins conversion
# functions like filter, map, etc
def celsius_to_fahrenheit(temp):
return (temp * 9 / 5) + 32
def fahrenheit_to_celsius(temp):
return (temp - 32) * 5 / 9
def main():
celsius_temps = (0, 12, 34, 100)
fahrenheit_temps = (32, 65, 100, 212)
# Use regular functions to convert temps
print(list(map(fahrenheit_to_celsius, fahrenheit_temps)))
print(list(map(celsius_to_fahrenheit, celsius_temps)))
# Use lambdas to accomplish the same thing
# reducing the complexity of the code
print(list(map(lambda temp: (temp - 32) * 5 / 9, fahrenheit_temps)))
print(list(map(lambda temp: (temp * 9 / 5) + 32, celsius_temps)))
# using lambda as the filter function
odd_f_temps = list(filter(lambda temp: (temp % 2) != 0, fahrenheit_temps))
print(odd_f_temps)
if __name__ == "__main__":
main()
# CONSOLE OUTPUT:
# [0.0, 18.333333333333332, 37.77777777777778, 100.0]
# [32.0, 53.6, 93.2, 212.0]
# [0.0, 18.333333333333332, 37.77777777777778, 100.0]
# [32.0, 53.6, 93.2, 212.0]
# [65]
| true |
45287696df3e49cbf7899d074edcdc0ae31e35a4 | ariannasg/python3-training | /standard_library/random_sequence.py | 1,788 | 4.8125 | 5 | #!usr/bin/env python3
import random
import string
# A common use case for random number generation is to use the generated
# random number along with a sequence of other values.
# So for example, you might want to select a random element from a list or
# a set of other elements.
# Use the choice function to randomly select from a sequence
moves = ["rock", "paper", "scissors"]
print(random.choice(moves))
# Use the choices function (introduced in python 3.6) to create a list of
# random elements
roulette_wheel = ["black", "red", "green"]
weights = [18, 18, 2]
# we define we want a list of 10 elements, otherwise is 1 by default
# there are only 2 green spaces on a roulette wheel, the green color shouldn't
# have the same chance to appear as black and red. we use weights for this.
# the weights arg tells the function how to distribute the results.
print(random.choices(roulette_wheel, weights, k=10))
# The sample function randomly selects elements from a population
# without replacement (the chosen items are not replaced)
# and without duplicates.
# here we print 6 random uppercase letters without duplicates
chosen = random.sample(string.ascii_uppercase, 6)
print(chosen)
# The shuffle function shuffles a sequence in place
players = ["Bill", "Jane", "Joe", "Sally", "Mike", "Lindsay"]
random.shuffle(players)
print(players)
# to shuffle an immutable sequence/collection, use the sample function first
result = random.sample(string.ascii_uppercase, k=len(string.ascii_uppercase))
random.shuffle(result)
print(''.join(result))
# CONSOLE OUTPUT (it will vary!):
# paper
# ['black', 'red', 'black', 'black', 'black', 'black', 'red', 'black', 'red', 'red']
# ['P', 'D', 'W', 'K', 'U', 'V']
# ['Lindsay', 'Mike', 'Bill', 'Sally', 'Joe', 'Jane']
# IRKXAVZNPHUCBLSEOJGQYWTFDM
| true |
4e1dec27165ae11de26af08675f180aaaba8f2d9 | ariannasg/python3-training | /standard_library/urls_parsing.py | 1,349 | 4.15625 | 4 | #!usr/bin/env python3
# Using the URL parsing functions to deconstruct and parse URLs
import urllib.parse
sample_url = "https://example.com:8080/test.html?val1=1&val2=Hello+World"
# parse a URL with urlparse()
result = urllib.parse.urlparse(sample_url)
print(result)
print('scheme:', result.scheme)
print('hostname:', result.hostname)
print('path:', result.path)
print('port:', result.port)
print('url:', result.geturl())
# in order to use special chars (space,ñ) un a url we need to convert them
# quote() replaces special characters for use in URLs
sample_string = "Hello El Niño"
print(urllib.parse.quote(sample_string))
print(urllib.parse.quote_plus(sample_string))
# how to convert dict of values into parameter strings for using in a URL as
# part of the query string
# Use urlencode() to convert maps to parameter strings
query_data = {
'Name': "John Doe",
"City": "Anytown USA",
"Age": 37
}
result = urllib.parse.urlencode(query_data)
print(result)
# CONSOLE OUTPUT:
# ParseResult(scheme='https', netloc='example.com:8080', path='/test.html', params='', query='val1=1&val2=Hello+World', fragment='')
# scheme: https
# hostname: example.com
# path: /test.html
# port: 8080
# url: https://example.com:8080/test.html?val1=1&val2=Hello+World
# Hello%20El%20Ni%C3%B1o
# Hello+El+Ni%C3%B1o
# Name=John+Doe&City=Anytown+USA&Age=37
| true |
bec0dc0a1418dc6eaddb447325395115ed8dddb4 | ariannasg/python3-training | /standard_library/string_search.py | 897 | 4.46875 | 4 | #!usr/bin/env python3
# Use standard library functions to search strings for content
sample_str = "The quick brown fox jumps over the lazy dog"
# startsWith and endsWith functions
print(sample_str.startswith("The"))
print(sample_str.startswith("the"))
print(sample_str.endswith("dog"))
# the find function starts searching from the left/start side of the str)
# and rfind function starts searching from the right hand-side of the str
# they both return the index at which the substring was found
print(sample_str.find("the"))
print(sample_str.rfind("the"))
# for knowing if a substr is contained in the str
print("the" in sample_str)
# using replace
new_str = sample_str.replace("lazy", "tired")
print(new_str)
# counting instances of substrings
print(sample_str.count("over"))
# CONSOLE OUTPUT:
# True
# False
# True
# 31
# 31
# True
# The quick brown fox jumps over the tired dog
# 1
| true |
e5acc44ad8a023261a1818cce025e33ea782e299 | vijonly/100_Days_of_Code | /Day2/tip_calculator.py | 357 | 4.1875 | 4 | # Tip Calculator project
print("Welcome to the tip calculator.")
bill = float(input("What was the total bill? $"))
partition = int(input("How many people to split the bill? "))
tip_percentage = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
print(f"Each person should pay: ${(bill / partition) * (tip_percentage + 100) / 100}")
| true |
b3c75e95a54ef8a1ddaf19b83b4595a94df35cd7 | vijonly/100_Days_of_Code | /Day15/coffee_machine.py | 2,702 | 4.25 | 4 | # Coffee Machine Program
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100
}
profit = 0
def generate_report():
'''Prints the report showing current resource values'''
for resource, value in resources.items():
print(f"{resource}: {value}")
print(f"Money: {profit}")
def check_resource(coffee):
'''
Check if there are enough resources to make user's desired coffee.
'''
for ingredient, quantity in MENU[coffee]['ingredients'].items():
if resources[ingredient] < quantity:
print(f"Sorry there is not enough {ingredient}")
return False
return True
def process_coin():
print("Please insert coins.")
quarters = int(input("How many quarters?: "))
dimes = int(input("How many dimes?: "))
nickles = int(input("How many nickles?: "))
pennies = int(input("How many pennies?: "))
money = round((quarters * 0.25) + (dimes * 0.10) + (dimes * 0.05) + (pennies * 0.01), 2)
return money
def complete_transaction(money, coffee_cost):
'''Return Boolean value by validating the payment'''
if money >= coffee_cost:
change = round(money - coffee_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += coffee_cost
return True
else:
print("Sorry that's not enough money. Money refunded!")
return False
def make_coffee(coffee_name, ingredients):
'''Deduct the required ingredients from the resources.'''
for ingredient in ingredients:
resources[ingredient] -= ingredients[ingredient]
print(f"Here is your {coffee_name} ☕. Enjoy!")
def start():
serving = True
while serving:
choice = input("\nWhat would you like? (espresso/latte/cappuccino): ").lower()
if choice == 'off':
print("Maintainence Mode!")
serving = False
elif choice == 'report':
generate_report()
elif choice in MENU.keys():
coffee = MENU[choice]
if check_resource(choice):
money = process_coin()
if complete_transaction(money, coffee['cost']):
make_coffee(choice, coffee['ingredients'])
start() | true |
5db1788519d32d194b83d998344193c9cc8044d9 | vijonly/100_Days_of_Code | /Day8/area_calc.py | 654 | 4.3125 | 4 | # Area Calc
"""
You are painting a wall.
The instructions on the paint can says that 1 can of paint can cover 5 square meters of wall.
Given a random height and width of wall,
calculate how many cans of paint you'll need to buy.
Formula to caclculate number of cans:
(wall_height x wall_width) / coverage per can
"""
import math
def paint_calc(height, width, coverage):
number_of_cans = math.ceil((height * width) / coverage)
print(f"You'll need {number_of_cans} cans of paint.")
wall_height = int(input("Enter Height of wall: "))
wall_width = int(input("Enter Width of wall: "))
coverage = 5
paint_calc(wall_height, wall_width, coverage) | true |
591489c8f26efdd66c23665fce80a3d5ea3096dd | malmhaug/Py_AbsBegin | /Ch4E2_egasseM/main.py | 353 | 4.34375 | 4 | # Project Name: Ch4E2_egasseM
# Name: Jim-Kristian Malmhaug
# Date: 11 Des 2015
# Description: This program take an input message from the user and prints it backwards
message = str(input("Hey! Please enter a message: "))
print("\nThe message is backwards:\n")
for letter_nr in range(len(message), 0, -1):
print(message[letter_nr-1])
input("\nPress Enter...") | true |
ab6a519ff67fba192d60c3fc45b4833034676a9a | malmhaug/Py_AbsBegin | /Ch3E4_GuessMyNumber_V1.02/main.py | 2,503 | 4.21875 | 4 | # Project Name: Ch3E4_GuessMyNumber_V1.02
# Name: Jim-Kristian Malmhaug
# Date: 25 Oct 2015
# Description: This program is a modified version of the
# Guess My Number program from the book, with computer versus player
# Guess My Number - Computer guesser
#
# The user picks a random number between 1 and 100
# The computer tries to guess it.
# Tries = 10
# ---------------------------------------------------------------------------------
# PSEUDO CODE
# ---------------------------------------------------------------------------------
# 1. Welcome user and tell him/her what to do
# 2. Store user input in the_number
# 3. Set guess to 0
# 4. Set tries to 1
# 5. set low_guess to 1
# 6. Set high_guess to 100
# 7. Import random library
# 8. While the computer has not guessed the number and tries are below 10
# 8.1 Computer guess a number between low_guess value and high_guess value
# 8.2 Print the guess
# 8.3 If the guess is higher than the the_number
# 8.3.1 Print lower text and inform of tries left
# 8.3.2 Set high_guess to last guessed number minus one
# 8.4 Else
# 8.4.1 Print higher text and inform of tries left
# 8.4.2 Set low_guess to las guessed number plus one
# 8.5 Increment tries
# 9. If tries is above or equal to 10
# 9.1 Print failure text
# 10. If tries is below 10
# 10.1 Print winner text and winner number
# 10.2 Print tries
# 11. Print exit text, and ask for user enter input
# ---------------------------------------------------------------------------------
print("\tWelcome to 'Guess My Number'!")
print("\nThinking of a number between 1 and 100.")
print("The computer will try to guess your number in 10 tries.")
# set the initial values
the_number = int(input("Enter the number here: "))
guess = 0
tries = 1
low_guess = 1
high_guess = 100
import random
# guessing loop
while (guess != the_number) and (tries < 10):
guess = random.randint(low_guess, high_guess)
print(guess)
if guess > the_number:
print("Lower... Computer has " + str(10 - tries) + " left!")
high_guess = guess - 1
else:
print("Higher... Computer has " + str(10 - tries) + " left!")
low_guess = guess + 1
tries += 1
if tries >= 10:
print("\nThe computer failed insanely!")
else:
print("\nThe computer guessed it! The number was", the_number)
print("And it only took", tries, "tries!\n")
input("\n\nPress the enter key to exit.") | true |
cefb4ec8bf58af1859c49337d9cd7ca70df5ef77 | pohrebniak/Python-base-Online-March | /pogrebnyak_yuriy/03/Task_3_2_Custom map.py | 1,779 | 4.34375 | 4 | '''
Implement custom_map function, which will behave like the original Python map() function.
Add docstring.
'''
def custom_map(func, *args):
"""
Custom_map function, which will behave like the original Python map() function.
:param arg1: func, function name to which custom_map passes each element of given iterable
:param arg2: *args, A sequence, collection or an iterator object
:type arg1: type - string
:type arg2: type - list
:return: Returns a list of the results after applying the given function
to each item of a given iterable
:rtype: return type - list
Small comment: the differance between map() and custom_map(), output example:
>>> map(print, [1, 2, 3])
<map object at 0x034D7B20>
>>> list(map(print, [1, 2, 3]))
1
2
3
[None, None, None]
>>> custom_map(print, [1, 2, 3])
1
2
3
[None, None, None]
Custom_map() don`t return object (link to memory value) but return list of the results.
And I don`t know how to make it exactly the same function as map().
Possibly It`s needed to use python mathods.
"""
def inner_func(in_args):
"""
Function for solve: custom_map(lambda x,y: x*y, [1,2],[3,4])
"""
print('in_args: ', in_args)
print(len(in_args))
x = func(tuple(in_args))
return x
if len(args) == 1:
return [func(i) for arg in args for i in arg]
else:
return inner_func(args)
l = [['sat', 'bat', 'cat', 'mat'], ['sat', 'bat', 'cat', 'mat']]
test = list(map(list, l))
print('Original map() result:', test)
test = list(custom_map(list, l))
print('Custom function custom_map() result:', test)
| true |
4674b82a4afad64d74fe1973eb1c83566b3c6aab | pohrebniak/Python-base-Online-March | /kirill_kravchenko/02/task_2.3.py | 1,580 | 4.25 | 4 | # Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.
#
# Examples:
#
# list: [1, 2, 3, 1, 3, 2, 1]
# output: 1
str = [1, 2, 3, 1, 3, 2, 1]
# ======
# 1 variant
# ======
equiv = 0
for i in str:
for j in str:
if i == j:
equiv += 1
if equiv > 0 and equiv % 2:
print(f'This is number "{i}" occurs "{equiv}" times in array')
break
equiv = 0
if equiv % 2 == 0:
print(f'There is no number that occurs odd times in array')
# ======
# 2 variant, not optimal, not normal, but all numbers
# ======
str_odd = []
length = 0
for i in str:
str_odd.append([i for j in str if i == j])
for j in str_odd:
length = len(j)
if length > 0 and length % 2:
print(f'This is number "{j[0]}" occurs "{length}" times in array')
break
if length % 2 == 0:
print(f'There is no number that occurs odd times in array')
# ======
# 3 variant
# ======
new_array = []
new_index_array = []
if_print = True
for i in str:
flag = True
for j in range(len(new_array)):
if new_array[j] == i:
new_index_array[j] += 1
flag = False
if flag:
new_array.append(i)
new_index_array.append(1)
for j in range(len(new_index_array)):
if new_index_array[j] % 2:
if_print = False
print(f'This is number "{new_array[j]}" occurs "{new_index_array[j]}" times in array')
break
if if_print:
print(f'There is no number that occurs odd times in array')
| true |
d03e936eb276d78f90572ad39a31e14ff76a32e5 | MuskanKhandelwal/Coding-problem-prep | /Operator overloading.py | 456 | 4.125 | 4 | class Student:
def __init__(self,x,y):
self.x=x
self.y=y
def __add__(self, other):
ans1=self.x+other.x
ans2=self.y+other.y
return ans1,ans2
S1=Student(10,20)
S2=Student(5,6)
S3=S1+S2 #This will give error as we are trying to add 2 objects, so we will override add method to add objects(operator overloading)
print(S3)
#After operator overloading giving addition answer
#S3=Student.__add__(S1,S2) | true |
4c92cfc6d9f3709ab208e4fec1d2bc1970cccea2 | agladman/python-exercises | /small-exercises/readtime.py | 1,087 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Calculates reading time based on average pace of 130 words per minute.
"""
import sys, time
def mpace(p):
if type(p) == int and p > 0:
return p
else:
match p:
case "slow":
return 100
case "average":
return 130
case "fast":
return 160
case _:
raise ValueError
def main():
words = None
pace = 130
# capture words and pace from sys args if passed
if len(sys.argv) == 2:
words = int(sys.argv[1])
elif len(sys.argv) > 2:
words = int(sys.argv[1])
p = sys.argv[2]
if p.isnumeric():
p = int(p)
pace = mpace(p)
# get words from user if still needed, pace stays as default
if words is None:
words = int(input("Enter wordcount: "))
# perform the calculation
sec = words/pace * 60
ty_res = time.gmtime(sec)
res = time.strftime("%Hh:%Mm:%Ss", ty_res)
print(f"Reading time: {res}")
if __name__ == '__main__':
main()
| true |
25dce67e505a17f3c7b71eb4a397539c956fa72d | agladman/python-exercises | /small-exercises/alphabetbob.py | 406 | 4.34375 | 4 | #!/usr/bin/env Python3
"""
Write a program that asks the user for their name, and then prints out
their name with the first letter replaced by each letter of the alphabet
in turn, e.g. for 'Bob' it prints 'Aob', 'Bob', 'Cob', 'Dob' etc.
"""
alpha = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split()
name = input('Please enter your name: ')
for letter in alpha:
print(letter + name[1:])
| true |
827baf8718a70c90c62f702f817824a47d6ac068 | dtom90/Algorithms | /Arrays/nearly-sorted-algorithm.py | 1,490 | 4.125 | 4 | """
Nearly Sorted Algorithm
https://practice.geeksforgeeks.org/problems/nearly-sorted-algorithm/0
Given an array of n elements, where each element is at most k away from its target position.
The task is to print array in sorted form.
Input:
First line consists of T test cases.
First line of every test case consists of two integers N and K,
denoting number of elements in array and at most k positions away from its target position respectively.
Second line of every test case consists of elements of array.
Output:
Single line output to print the sorted array.
Constraints:
1<=T<=100
1<=N<=100
1<=K<=N
Example:
Input:
2
3 3
2 1 3
6 3
2 6 3 12 56 8
Output:
1 2 3
2 3 6 8 12 56
"""
def parse_input(func):
t = int(input()) # "How many use cases? "
# print('{} test cases'.format(t))
for i in range(t):
# print('use case {}'.format(i + 1))
n, k = list(map(lambda x: int(x), input().split())) # "Size of array? "
# print('n = {}'.format(n))
# print('k = {}'.format(k))
seq = list(map(lambda x: int(x), input().split())) # "Sequence? "
# print(seq)
print(func(n, k, seq))
def fast_sort(n, k, seq):
swapped = True
while swapped:
swapped = False
for i in range(n-1):
if seq[i+1] < seq[i]:
tmp = seq[i]
seq[i] = seq[i+1]
seq[i+1] = tmp
swapped = True
return ' '.join(str(n) for n in seq)
parse_input(fast_sort)
| true |
0a67103e7ad9ba72106c840ed1dfcd7e07c2869c | dtom90/Algorithms | /Encoding/url-shortener.py | 2,067 | 4.5 | 4 | """
https://practice.geeksforgeeks.org/problems/design-a-tiny-url-or-url-shortener/0
Design a system that takes big URLs like “http://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/”
and converts them into a short 6 character URL.
It is given that URLs are stored in database and every URL has an associated integer id.
So your program should take an integer id and generate a 6 character long URL.
A URL character can be one of the following
A lower case alphabet [‘a’ to ‘z’], total 26 characters
An upper case alphabet [‘A’ to ‘Z’], total 26 characters
A digit [‘0′ to ‘9’], total 10 characters
There are total 26 + 26 + 10 = 62 possible characters.
So the task is to convert an integer (database id) to a base 62 number where digits of 62 base are
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Input:
The first line of input contains an integer T denoting the number of test cases.
The second line consists of a long integer.
Output:
For each testcase, in a new line, print the shortened string in the first line
and convert the shortened string back to ID (to make sure that your conversion works fine)
and print that in the second line.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 232-1
Example:
Input:
1
12345
Output:
dnh
12345
"""
def parse_input(func):
t = int(input()) # "How many use cases? "
# print('{} test cases'.format(t))
for i in range(t):
id = int(input())
func(id)
def generate_tiny_url(id):
encoding = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
short_arr = []
while id > 62:
i = id % 62
# print(i)
short_arr.append(encoding[i])
id = int(id / 62)
# print(id)
short_arr.append(encoding[id])
# short_arr.reverse()
str = ''.join(short_arr[::-1])
print(str)
num = 0
mult = 1
for char in short_arr:
n = encoding.index(char)
# print(n, mult)
num += n * mult
mult *= 62
print(num)
parse_input(generate_tiny_url)
| true |
834de094ea09b3e3a66ea6b7222a8ad905f9d790 | nurawat/learning_python | /list_range_introduction.py | 641 | 4.15625 | 4 | ##
# Basic Learner type
#
##
# ip_address = input("Please Enter IP address : ")
# print(ip_address.count("."))
ip_address = ["127.0.0.1", "192.168.0.1", "192.168.1.1"]
for single_IP in ip_address:
print("IP given is {}".format(single_IP))
### List
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7]
numbers = even + odd
l_numbers = numbers
numbers.sort(reverse = True)
print(numbers is even)
if sorted(l_numbers) == numbers:
print("YES")
else:
print("NO")
print(list("Hi, This is arun"))
dummy = "this is a test"
print(dummy.split())
###### range
print("#######################")
print(list(range(0,10,1)))
print(list(range(0,10,2)))
| true |
34b4df534b19bc416dffdb4f35a63681d9c6fa16 | anant-creator/Other_sources | /Area_perimeter_of_Triangle.py | 404 | 4.125 | 4 | ''' Area and perimeter of a right angle triangle '''
base = int(input("Enter the base of triangle:- "))
height = int(input("Enter the height of triangle:- "))
print("If you want to know the area then use '0' as hypotenuse")
hypotenuse = int(input("Enter the hypotenuse:- "))
area = base * height / 2
perimeter = base + height + hypotenuse
if hypotenuse == 0:
print(area)
else:
print(perimeter)
| true |
66a5d533a37ba0df7d85bba6df765a903e5679d3 | KakE-TURTL3/PythonPractice | /Login System/loginSystem.py | 1,509 | 4.15625 | 4 | import time
#Introduces user to program they are using
print("Welcome to *insert name here*")
#Asks the user to either register or log in
opt = int(input ("To continue you must login or register. Please pick an option.\n1)Log In\n2)Register\n"))
#Defines login function
def login():
accountName = input("Please enter your account name: ")
password = input("Please enter your password: ")
f = open("accounts.txt", "r")
real = f.read()
accountDetails = accountName + ", " + password + "\n"
if accountDetails == real:
print("You have successfully logged in to the account: " + accountName + "\n")
time.sleep(2)
else:
print("Login failed. You entered the wrong username or password. Please try again.\n")
login()
f.close()
#Define register function
def register():
registerAccountName = input("Please input a suitable username: ")
registerPassword = input("Please enter a suitable password: ")
confirmPassword = input("Please confirm your password: ")
if registerPassword == confirmPassword:
f = open("accounts.txt", "w")
f.write(registerAccountName + ", " + registerPassword + "\n")
f.close()
print("Now you must log in")
login()
else:
print("The first password you entered didnt match the confirm password. Please try again.\n")
register()
if opt == 1:
login()
elif opt == 2:
register()
else:
quit
| true |
704eeb3197f4bfd65121dcb7bed54dc5113014b5 | simrit1/scrabble-word-score-calculator | /scrabble_word_score.py | 1,837 | 4.25 | 4 | '''
Habitica Challenge October 2019
Challenge Description
In the game Scrabble each letter has a value. One completed word gives you a score.
Write a program that takes a word as an imput and outputs the calculated scrabble score.
Values and Letters:
1 - A, E, I, O, U, L, N, R, S, T
2 - D, G
3 - B, C, M, P
4 - F, H, V, W, Y
5 - K
8 - J, X
10 - Q, Z
Example:
The word "cabbage" gives you a score of 14 (c-3, a-1, b-3, b-3, a-1, g-2, e-1)
Extensions:
You can play a double or triple letter
You can play a double or triple word
'''
import os
let_val = {
'A':1, 'E':1, 'I':1, 'O':1, 'U':1, 'L':1, 'N':1, 'R':1, 'S':1, 'T':1,
'D':2, 'G':2,
'B':3, 'C':3, 'M':3, 'P':3,
'F':4, 'H':4, 'V':4, 'W':4, 'Y':4,
'K':5,
'J':8, 'X':8,
'Q':10, 'Z':10
}
def select_action():
print('Please Select Action:')
op = -1
while not(op == '1' or op == '0'):
print(' 1 - Check word')
print(' 0 - Exit')
op = input('Option: ')
return op
def check_valid_word(word):
with open('sowpods.txt') as f:
if word in f.read():
return True
return False
def enter_word():
word = input('Please enter word: ').upper().strip()
while not check_valid_word(word):
word = input('Invalid Scrabble word. Please Try again: ').upper().strip()
score = 0
for let in word:
score += let_val[let]
print('Valid Scrabble word! The score for {} is: {}\n'.format(word, score))
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
print('Welcome to scrabble word value calculator!')
opt = select_action()
while opt != '0':
enter_word()
opt = select_action()
print('Thanks for playing!')
main() | true |
08f9a8c7e174acc88b18811e4b2b6ee2b6bc0c4f | Liquid-sun/MIT-6.00.1x | /week-4/fruits.py | 1,665 | 4.21875 | 4 |
"""
Code Grader: Python Loves Fruits
(10 points possible)
Python is an MIT student who loves fruits. He carries different types of fruits (represented by capital letters)
daily from his house to the MIT campus to eat on the way. But the way he eats fruits is unique.
After each fruit he eats (except the last one which he eats just on reaching the campus), he takes a 30 second
break in which he buys 1 fruit of each type other than the one he just had.
Cobra, his close friend, one day decided to keep a check on Python. He followed him on his way to MIT campus
and noted down the type of fruit he ate in the form of a string pattern (Eg.: 'AABBBBCA').
Can you help Cobra determine the maximum quantity out of the different types of fruits
that is present with Python when he has reached the campus?
Write a function nfruits that takes two arguments:
A non-empty dictionary containing type of fruit and its quantity initially with Python when he leaves home (length < 10)
A string pattern of the fruits eaten by Python on his journey as observed by Cobra.
This function should return the maximum quantity out of the different types of fruits that is available with
Python when he has reached the campus.
For example, if the initial quantities are {'A': 1, 'B': 2, 'C': 3} and the string pattern is 'AC' then
'A' is consumed, updated values are {'A': 0, 'B': 2, 'C': 3}
Python buys 'B' and 'C', updated values are {'A': 0, 'B': 3, 'C': 4}
'C' is consumed, updated values are {'A': 0, 'B': 3, 'C': 3}
Now Python has reached the campus. So the function will return 3 that is maximum of the quantities of the three fruits.
"""
| true |
d43a9d3ba885470d292cb3d377913f7257862571 | Liquid-sun/MIT-6.00.1x | /week-1-2/payments3.py | 731 | 4.125 | 4 | #!/usr/bin/env python
balance = 320000
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
min_pay = balance / 12
max_pay = (balance * (1 + monthlyInterestRate)**12) / 12.0
ans = (min_pay + max_pay) / 2
while(balance <= 0):
print('pay: ', ans)
for month in range(1, 13):
balance -= ans
interest = (annualInterestRate / 12.0) * balance
balance += interest
print("Remaining balance at the end of the year: {}".format(round(balance, 2)))
print("Min payment: {}".format(ans))
if balance > 0:
min_pay = ans
else:
max_pay = ans
print("--------------------------------------------")
#print("Lowest Payment: {}".format(round(ans, 2)))
| true |
2dfc365283d74732559002389ca6b526ec4d0891 | Liquid-sun/MIT-6.00.1x | /quiz/flatten.py | 616 | 4.46875 | 4 | #!/usr/bin/env python
"""
Problem 6
(15 points possible)
Write a function to flatten a list. The list contains other lists, strings, or ints.
For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5]
"""
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
flt = lambda *n: (e for a in n for e in (flt(*a) if isinstance(a, list) else (a,)))
return list(flt(aList))
if __name__=="__main__":
test_list = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
flat = flatten(test_list)
print flat
| true |
96f5e490d0d0e216bc13b8ac4b6fced2a3888e86 | Liquid-sun/MIT-6.00.1x | /week-6/queue.py | 1,694 | 4.46875 | 4 | #!/usr/bin/env python
"""
For this exercise, you will be coding your very first class, a Queue class.
Queues are a fundamental computer science data structure. A queue is basically
like a line at Disneyland - you can add elements to a queue, and they maintain
a specific order.
When you want to get something off the end of a queue, you get the item that
has been in there the longest (this is known as 'first-in-first-out', or FIFO).
You can read up on queues at Wikipedia if you'd like to learn more.
In your Queue class, you will need three methods:
__init__:
initialize your Queue (think: how will you store the queue's elements?
You'll need to initialize an appropriate object attribute in this method)
insert:
inserts one element in your Queue
remove:
removes (or 'pops') one element from your Queue and returns it.
If the queue is empty, raises a ValueError.
"""
class Queue(object):
def __init__(self):
self.qu = []
def __len__(self):
return len(self.qu)
def __repr__(self):
q = ','.join([str(i) for i in self.qu])
return "Queue({})".format(q)
def __str__(self):
q = ','.join([str(i) for i in self.qu])
return "[{}]".format(q)
def insert(self, item):
self.qu.append(item)
def remove(self):
if not self.qu:
raise ValueError("Queue is empty")
else:
fst = self.qu[0]
self.qu = self.qu[1:]
return fst
if __name__=="__main__":
q = Queue()
for i in range(10):
q.insert(i)
print repr(q)
for i in range(20):
elem = q.remove()
print("Removing: {}".format(elem))
print repr(q)
| true |
d34b5d4f791efb03822cd6841ba5f7636cf635f1 | prajaktasangore/coding-challenge-2015 | /PythogorousTriplets.py | 787 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Prajakta Sangore
# Date: 30th September 2015
# Problem: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import time
import decimal
start_time = time.time()
def pythagorous():
for a in xrange (1,1000):
for b in xrange(2,1000):
c = 1000 - (a+b)
if((a**2) + (b**2) == (c**2)):
if(a + b + c == 1000):
print "a = %d b =%d c = %d" %(a,b,c)
print "The sum is = %d" %(a+b+c)
print "The product is = %d" %(a*b*c)
return 1
pythagorous()
print "total time taken = %s seconds" %round((time.time() - start_time),2)
| true |
c8a6d7caef5c558d448908ba2f764f4adbfab1d8 | chunkify/Course_Materials | /CMPT 830_Bioinformatics_and_Computational_Biology/Assignment_1/Solution/Exercise 2.py | 2,098 | 4.21875 | 4 | #!/usr/bin/env python3
# This script will open the file "Glycoprotein.fasta" and read each line of the
# file within a for-loop. That means that each iteration through the for-loop
# will be performed with a new (the next) line of the input file. The
# number of characters in each line is printed.
# Open the file
#file = open("Glycoprotein.fasta")
flag = 0
total_sequence = 0
amino_acid = "";
amino_acid_count = 0
print("Enter the name of a FASTA file: ")
file_name = input()
file_name_list = file_name.split(".")
length_list = len(file_name_list)
if length_list == 2 and file_name_list[1] != "fasta":
print("enter a valid FASTA file name with extension fasta ")
elif length_list == 1:
fasta_file_name = file_name + ".fasta" # make the file name with extension "fasta"
file = open(fasta_file_name, "r")
flag = 1
else:
file = open(file_name,"r")
flag = 1
f= open("out.txt","w+")
# The next operation will repeatedly read the next line of the file and place
# it in the string "line". The loop will then be performed for each
# value of "line". Note that the terminating newline character
# (of the line that was read) will be included in the value of "line"
if flag:
for line in file:
#Print out the length of the line
if line[0] == ">":
header = line
if amino_acid_count != 0:
print("the first ten characters are: ",amino_acid[0:10]," and the total amino acid count is: ",amino_acid_count)
amino_acid_count = 0
amino_acid = ""
print("the header is: ", line.rstrip())
total_sequence += 1
#f.write(line)
else:
line = line.rstrip()
amino_acid += line
amino_acid_count += len(line)
#line = line.rstrip()
#print( "the line contains ", len(line), " characters")
#print("the string: ", line)
# Close the opened file. This step is actually optional if it occurs
# at the end of the script.
#file.close()
if header[0] == ">":
print("the first ten characters are: ", amino_acid[0:10], " and the total amino acid count is: ", amino_acid_count)
print("total sequence is: ", total_sequence)
| true |
d3db0e57da66e3105e022c17ee7567a2358b9541 | chriscross00/cci | /data_structures/linked_lists.py | 2,176 | 4.15625 | 4 | # https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/
# READ THIS https://www.greenteapress.com/thinkpython/thinkCSpy/html/chap17
# .html
# creating the class Node
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def set_data(self, val):
self.data = val
def get_next(self):
return self.next
def set_next(self, val):
self.next = val
# Class linked list
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def get_size(self):
return self.size
def is_empty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
self.size += 1
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.get_data() == item:
found = True
else:
current = current.get_next()
return found
def remove(self, item):
# Setting up our pointers
current = self.head
previous = None
found = False
# The search function
while not found:
if current.get_data() == item:
found = True
self.size -= 1
else:
previous = current
current = current.get_next()
# Once item is found break to this if-else statement which 'leap
# frogs' the item node, connecting the previous node to the node
# after current.
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
def print_list(self):
current = self.head
while current is not None:
print(current.get_data())
current = current.get_next()
mylist = LinkedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
mylist.print_list()
| true |
13300283d829e0a97591566f852896cbf30e2a00 | BlackTimber-Labs/DemoPullRequest | /Python/tripur1.py | 303 | 4.15625 | 4 | # to find sum
# of elements in given array
def _sum(arr):
sum=0
for i in arr:
sum = sum + i
return(sum)
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr)
# display sum
print ('Sum of the array is ', ans)
| true |
ae33b423103085042b0b0084035f20108689778e | fizzahwaseem/Assignments | /31_gcd.py | 394 | 4.21875 | 4 | #Python program to compute the greatest common divisor (GCD) of two positive integers.
print('To find GCD enter ')
num1 = int(input('number 1 : '))
num2 = int(input('number 2 : '))
if num1 > num2:
greater = num1
else:
greater = num2
for i in range(1, greater+1):
if((num1 % i == 0) and (num2 % i == 0)):
gcd = i
print('The gcd of' , num1 , 'and' , num2 , 'is' , gcd) | true |
bd671af590ae1ec9251afc96487aa2e1f95db6cb | fizzahwaseem/Assignments | /20_time_to_seconds.py | 224 | 4.28125 | 4 | #Python program to convert all units of time into seconds.
hour = int(input("Enter time in hours: "))
minute = int(input("Enter time in minutes: "))
t = (hour * 60 * 60) + (minute * 60)
print("Total time in seconds is: ", t) | true |
26a3b257f2a1797e32773e653195450f68e83729 | AnneOkk/Alien_Game | /bullet.py | 1,561 | 4.125 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to manage bullets fired from the ship"""
def __init__(self, ai_game):
"""Create a bullet object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.bullet_color
# Create a bullet rect at (0,0) and then set the correct position.
self.rect = pygame.Rect(0,0, self.settings.bullet_width,
self.settings.bullet_height) # requires the x- and y-coordinates of the top-left
# corner rect, and the width and height of the rect
self.rect.midtop = ai_game.ship.rect.midtop # set the bullet's midtop attribute to match the ship's midtop
# attribute --> makes it look like the bullet emerges from the top of the ship (like it is fired)
# Store the bullet's position as a decimal value.
self.y = float(self.rect.y) #store decimal values for the bullet's y coordinate, so we can make fine
# adjustment to the bullet's speed
def update(self):
"""Move the bullet up the screen"""
#Uodate the decimal position of the bullet.
self.y -= self.settings.bullet_speed #when bullet is fired, it moves up the screen --> decreasing y value
#Update the rect position.
self.rect.y = self.y
def draw_bullet(self):
"""Draw the bullet to the screen"""
pygame.draw.ellipse(self.screen, self.color, self.rect) | true |
343cd7567341f94b32b70ac9b1089734aa79aaaf | trev3rd/gogo | /guess1.py | 1,622 | 4.46875 | 4 | import random
guessesTaken = 0 #this represents how many times the user has tried guessing the right number starting from zero
number = random.randint(1, 10)
print(number) #this shows the random number the computer picked good for seeing if code works properly
print(' I am thinking of a number between 1 and 10.')
while guessesTaken < 3: #this says while the user has tried less than 3 times the follwoing shall happen
print('Take a guess.')
guess = input() # this basically allows the user to input a response from the above print statement
guess = int(guess)# this makes sure that its a integer that should be guessed
guessesTaken = guessesTaken + 1 # the "count" basically that you had in your code for the increments
#this is where the if statements come in
if guess == number +1 or guess == number -1: #as i said in class to give output hot if its 1 higher or lower
print('Your guess is hot')
if guess == number +2 or guess == number -2:#if its 2 higher or lower from random number
print('Your guess is warm.')
elif guess > number +2 or guess < number -2:#if greater than 2(3 or more/3 or less) it will say cold
print('your guess is cold')
if guess == number: # if the user gets the right number the following happends
print('Good job! You guessed my number in ', guessesTaken)#outputs how many times it took user to guess
break
if guess != number: # this is outside of loop to avoid a paradox and confusion with the top 3 ifs in the while statement
print('Nope. The number I was thinking of was ', number)
| true |
0b5ce13bcb253816f93f40949150a0fc47b2dddd | faliona6/PythonWork | /letter.py | 404 | 4.125 | 4 |
word = input("What is the magical word?")
def Dictionary(word):
dictionary = {}
a = 0
for letter in word:
if letter in dictionary:
dictionary[letter] = dictionary[letter] + 1
else:
dictionary[letter] = 1
return dictionary
dictionary = Dictionary(word)
for let, count in dictionary.items():
print("Letter: " + let + "\tCount: " + str(count))
| true |
1b536c7de215a6511df46e606f059fef64529533 | j33mk/PythonSandboxProdVersion | /pythonsandbox/sandbox/newpython/dopamine.py | 872 | 4.1875 | 4 | #i was thinking how can i link my dopamine with programming, get back to programming and learn datascience, machine learning, and make myself expert in everything that i come across
# what is stopping me? What are the things that are stopping me
# this is the question that i am searching the answer
print('dopamine research')
import numpy as np
#lets build a little game to get back to what i am missing for quite long time
guess_numbers = [1,2,3,4,5,6,7,8,9,10]
guessed_number = np.random.choice(guess_numbers)
if guessed_number%2 == 0:
print("It seems the number is even")
else:
print("Well the number seems to be odd try to guess it")
user_input = int(input("Enter a number: "))
score = 0
if user_input == guessed_number:
score = score+1
print("You guess corrected :)")
print("Your score is : "+str(score))
else:
print("sorry try again :(")
| true |
eff5e1ac079573feb1d0cf78aacd4f2088e8c845 | turalss/Python | /day_2_a.py | 1,299 | 4.40625 | 4 | # Write a string that returns just the letter ‘r’ from ‘Hello World’
# For example, ‘Hello World’[0] returns ‘H’.You should write one line of code. Don’t assign a variable name to the string.
hello_world = 'Hello World'
print(hello_world[8])
# 2. String slicing to grab the word ‘ink’ from the word ‘thinker’
# S=’hello’,what is the output of h[1]
s = 'hello'
print(s[1]) # output is 'e'
thinker = 'thinker'
print(thinker[2:5])
# 3. S=’Sammy’ what is the output of s[2:]”
sammy = 'Sammy'
print(sammy[2:]) # outpur is 'mmy'.
# 4. With a single set function can you turn the word ‘Mississippi’ to distinct character word.
def split_string(string):
return [char for char in string]
mississippi = 'Mississippi!'
print(split_string(mississippi))
# 5. The word or whole phrase which has the same sequence of letters in both directions is called a palindrome.
def palidrome(data):
result = []
data = data[1:]
for string in data:
if ''.join(e for e in string if e.isalnum()).lower() == ''.join(e for e in string if e.isalnum())[::-1].lower():
result.append('Y')
else:
result.append('N')
return(result)
data = [3, 'Amore, Roma', 'No "x" in Nixon', 'Was it a cat I saw?']
print(palidrome(data))
| true |
8c4f0158e801cb77e85555ac6283c78f44c99ce9 | AISWARYAK99/Python | /tuples.py | 952 | 4.65625 | 5 | #tuples
#they are not mutable
my_tuple=()
my_tuple1=tuple()
print(my_tuple)
print(my_tuple1)
my_tuple=my_tuple+(1,2,3)
print(my_tuple)
my_tuple2=(1,2,3)
my_tupple4=tuple(('Python','Java','Php',1))
print(my_tuple2)
print(my_tupple4)
my_tuple5='example', #add comma if we want tuple with single elements
print(type(my_tuple5))
#Accessing elements
my_tuple6=(1,2,3,['Hindi','telugu'])
print(my_tuple6[0])
print(my_tuple6[:])
print(my_tuple6[3][1])#2 element of 3rd index
print(my_tuple6[::-1])#accessing elements in reverse order
print(my_tuple6[0:5:2])#0 to 4 will be printed with jumping of 2 elements instead of 1
my_tuple6[3][1]='English' #we can change values of a tuple since it is immutable but we since the 3rd index of tuple is a list we can change the list component of that tuple.
print(my_tuple6)
#tuple methods
my_tuple7=(1,2,3,'English')
print(my_tuple7.count('English'))
print(my_tuple7.index('English'))
| true |
b3fd5e9b71657eeb1333aa465f429d511ba27a2f | AISWARYAK99/Python | /start1.py | 1,685 | 4.28125 | 4 | #python beginning
'''
There are 6 data types in python.
1.Numeric(not mutable)
2.List(mutable)
3.Tuples
4.Dictionary
5.Set
6.String
'''
print('hello users welcome to the basics')
a=int(input('Enter num a:'))#input is read as a string so converting it to int.
b=int(input('Enter num s:'))#type conversion of string to int
print('The addition of a and is:',(a+b))
#data types
a=10
b=30
a=9
print(a)
#numeric dataype
a=10 #integer
b=-10
c=3.14 #Float
d=0.142
e=10+3j #Complex-numbers
f=6j
print(a+b,c-d,e-f,end='\n')
print(a-c,b-f,a*b,end='\n')
#type-conversions
s='10010' #String
c=(int)(s,2) # passing 2 since its a binary num we need to convert s to an integer of base 2 which is binary
print('After converting to integer base 2: %d ' %c,end='\n')
e=float(s)
print('After converting to float: %f ' %e,end='\n')
s='4' #initialising integer
c=ord(s) # char converted to integer
print('After converting character to integer : %d ' %c,end='\n')
c=hex(56)
print('After converting 56 to hexadecimal string : ' +c,end='\n')
c=oct(56)
print('After converting 56 to octal string : '+c,end='\n')
s='Aiswarya' #initialising string
c=tuple(s)
print('After converting string to tuple ',c,end='\n')
c=set(s)
print('After converting string to set ',c,end='\n')
c=list(s)
print('After converting string to list ',c,end='\n')
a=1
b=2
tup=(('a',1),('f',2),('g',3)) #initialising tuple
c=complex(1,2)
print('After converting integer to complex numbers ',c,end='\n')
c=str(a)
print('After converting integer to string ',c,end='\n')
c=dict(tup)
print('After converting tuple to dictionary ',c,end='\n')
| true |
eadc78f6241176af767fed72ac5fbf14b5440c4f | Ivasuissa/python1 | /isEven.py | 246 | 4.1875 | 4 |
def is_even(n):
if (n % 1) == 0:
if (n % 2) == 0:
print("True")
return True
else:
print("False")
return False
else:
print(f"{n} is not an integer")
is_even(-4) | true |
eb0146449cf4c1038ba3107983fbed12bb9db675 | mdmcconville/Solutions | /validPalindrome.py | 683 | 4.15625 | 4 | import string
"""
This determines whether a given string is a palindrome regardless of case,
punctuation, or whitespace.
"""
class Solution:
"""
Precondition: s is a string
Postcondition: returns a boolean
"""
def isPalindrome(self, s):
# Case: string is empty
if not s:
return True
else:
# Remove whitespace and punctuation and make all lower-case
s = ''.join(i for i in s if i not in(string.punctuation +
string.whitespace)).lower()
# Return whether the reversed string equals the original
return s == s[::-1]
| true |
9c86124bc1733189f8edab9712a4d79e3e074345 | mlesigues/Python | /everyday challenge/day_19.py | 1,916 | 4.125 | 4 | #Task: Vertical Order Traversal of a Binary Tree from Leetcode
#src:https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
#src:https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/253965/Python-8-lines-array-and-hashmap-solutions
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import defaultdict
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
#the horizontal distance of root is set to 0 => root: (x,y) = (0,0)
#will be used for the vertical nodes, min and max vertical indices
self.dic = collections.defaultdict(list)
""""
self.minimumLevel, self.maximumLevel = float("inf"), -float("inf")
#dfs function: takes in root, horizontal coordinate, vertical coordinate
def dfs(root, hor, ver):
self.maximumLevel = min(hor, self.minimumLevel)
self.minimumLevel = max(hor, self.maximumLevel)
dic[hor].append((ver, root.val))
if root.left:
dfs(root.left, hor-1, ver+1)
if root.right:
dfs(root.right, hor+1, ver+1)
dfs(root, 0,0)
result = []
for i in range(self.minimumLevel, self.maximumLevel + 1):
result += [[i for i,j in sorted(dic[i])]]
return result
"""
def dfs(node, hor, ver):
if node:
self.dic[hor].append((ver, node.val))
dfs(node.left, hor - 1, ver + 1)
dfs(node.right, hor + 1, ver + 1)
dfs(root, 0, 0)
return [list(map(lambda hor: hor[1], sorted(arr))) for x, arr in sorted(self.dic.items())]
| true |
551824b92a522ebbaa8d8efb5b2a790953662133 | mlesigues/Python | /everyday challenge/day_13.py | 1,713 | 4.125 | 4 | #TASK: Given a full name, your task is to capitalize the name appropriately.
#input: s is the full name
# Complete the solve function below.
def solve(s):
#s[0] = s.capitalize()
#cap = s.capitalize()
# for i in len(range(s)):
# if s[i] == " ":
# s[i+1] = s.capitalize()
# for i in range(0, len(s)):
# if [s+1] == " ":
# cap = s.capitalize()
# strSplit = s.split(" ")
# for i in range(0, len(s)):
# i[0] = s.capitalize()
# if s[i] == strSplit:
# if s[i+1] != strSplit:
# s[i+1] = s.capitalize()
# return s
#newString = s
#new_string = newString.capitalize()
newString = s
new_string = ' '.join(map(str.capitalize, newString.split(' ')))
return new_string
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
#TASK: matrix addition.
#input: user will input the two arrays => can be converted to matrices
from array import *
#src: https://www.geeksforgeeks.org/take-matrix-input-from-user-in-python/
userInput_Row = int(input("Enter the number of rows: "))
userInput_Col = int(input("Enter the number of columns: "))
print("Enter entries in a single line (press enter after each element): ")
#result = list(map(int, input("Enter array elements: ").split()))
result = []
#putting values into a matrix
for i in range(userInput_Row):
emp = []
for j in range(userInput_Col):
emp.append(int(input()))
result.append(emp)
#print matrix
for i in range(userInput_Row):
for j in range(userInput_Col):
print(result[i][j], end=" ")
print()
| true |
ece505a202ad37c9ca990f3b84f121cc076f5a02 | amrishparmar/countdown-solver | /countdown.py | 2,941 | 4.25 | 4 | import argparse
import sys
def load_words(filename):
"""Load all words (9 letters or less) from dictionary into memory
:param filename: A string, the filename to load
:return: A set, all relevant words in the file
"""
valid_words = set()
with open(filename, 'r') as word_file:
for word in word_file:
if len(word) < 11: # only want 9 letter words (accounts for \n extra char)
valid_words.add(word.rstrip('\n'))
return valid_words
def generate_solutions(words, letters, sort=True):
"""Generate a list of all possible solutions from the given letters
:param words: A set of all valid words
:param letters: A string, the letters from which is derive the solution
:return: A list of strings, the solutions
"""
solutions = []
def check_all_letters_valid(word):
"""Check whether a word can be made from the given letters"""
temp_letters = letters
for letter in word:
if letter in temp_letters:
index_of_letter = temp_letters.index(letter)
temp_letters = temp_letters[:index_of_letter] + temp_letters[index_of_letter + 1:]
else:
return False
return True
for word in words:
if check_all_letters_valid(word):
solutions.append(word)
if sort:
solutions.sort(key=lambda w: len(w))
return solutions
def pretty_print_solutions(solutions, reverse=False):
"""Print out the solutions organised by word length
:param solutions: A list of strings containing the possible solutions
:param reverse: A bool, whether to print longest to shortest (True) or shortest to longest (False)
"""
word_lists = [[word for word in solutions if len(word) == i] for i in range(1, 10)]
for i, sublist in enumerate(word_lists):
print('=== {} letter words ==='.format(i + 1))
for word in sorted(sublist, reverse=reverse):
print(word)
def main():
"""Main function"""
parser = argparse.ArgumentParser(description='Generate possible solutions to a Countdown puzzle.')
parser.add_argument('dictionary', type=str, help='A dictionary filename')
parser.add_argument('--letters', type=str, help='The puzzle letters')
args = parser.parse_args()
words = load_words(args.dictionary)
if args.letters:
solutions = generate_solutions(words, args.letters)
pretty_print_solutions(solutions)
else:
while True:
try:
letters = input('Enter letters (or Ctrl-D to quit): ')
except EOFError:
print('Quitting...')
sys.exit()
solutions = generate_solutions(words, letters)
print('Solutions are:')
pretty_print_solutions(solutions)
print()
if __name__ == '__main__':
main()
| true |
c77766a42c2ad2c69e0dbb57ae284d8aa04f5a64 | robinyms78/My-Portfolio | /Exercises/Python/Learning Python_5th Edition/Chapter 4_Introducing Python Object Types/Examples/Dictionaries/Nesting Revisited/Example1/Example1/Example1.py | 375 | 4.46875 | 4 | rec = {"name": {"first": "Bob", "last": "Smith"}, "jobs": ["dev","mgr"], "age": 40.5}
# "name" is a nested dictionary
print(rec["name"])
# Index the nested dictionary
print(rec["name"]["last"])
# "jobs" is a nested list
print(rec["jobs"])
# Index the nested list
print(rec["jobs"][-1])
# Expand Bob's job description in place
rec["jobs"].append("janitor")
print(rec)
| true |
461fdf8ec3a0c44f068c802e51eff664a205dc27 | dineshkumarkummara/my-basic-programs-in-java-and-python | /folders/python/instagram/45while_else.py | 295 | 4.53125 | 5 | #In Python, you can add the "else" block after a "while" loop.
# It will be executed after the loop is over.
x=3
while x<=5: #change the condition to check different outputs
print(x)
x+=1
#if the condition is false then else statement will be executed
else:
print("done")
| true |
131fea2d621c3a61c365d6794793cd4ba30ba951 | dineshkumarkummara/my-basic-programs-in-java-and-python | /folders/python/others/fun2.py | 605 | 4.4375 | 4 | def fun(*args):
for i in args:
print(i)
args=1,2,3,4,5,6
fun(*args)
#or
print("----------")
fun(7,8,9)
#You can't provide a default for args, for example func(*args=[1,2,3]) will raise a syntax error (won't evencompile).
# You can't provide these by name when calling the function, for example func(*args=[1,2,3]) will raise aTypeError.
# But if you already have your arguments in an array (or any other Iterable), you can invoke your function like this:func(*my_stuff).
# These arguments (*args) can be accessed by index, for example args[0] will return the first argument
print(args[3])
| true |
d3ec9f8db3eceae68a3392d8de84c8acd9155de2 | muskanmahajan486/communication-error-checksum | /parity/index.py | 409 | 4.40625 | 4 | # Python3 code to get parity.
# Function to get parity of number n.
# It returns 1 if n has odd parity,
# and returns 0 if n has even parity
def getParity( n ):
parity = 0
while n:
parity = ~parity
n = n & (n - 1)
return parity
# Driver program to test getParity()
n = 0
print ("Parity of no ", n," = ",
( "odd" if getParity(n) else "even")) | true |
706f75c1b7da25049bdc240b0620b8303fcc8e72 | rahulcode22/Data-structures | /Arrays/BubbleSort.py | 583 | 4.4375 | 4 | '''
Bubble sort is a example of sorting algorithm . In this method we at first compare the data element in the first position with the second position and arrange them in desired order.Then we compare the data element with with third data element and arrange them in desired order. The same process continuous until the data element at second last and last position
'''
def bubbleSort(arr,n):
for i in range(0,n):
for j in range(0,n):
if arr[j]>arr[i]:
arr[i], arr[j] = arr[j], arr[i]
return arr
arr = [3,2,6,4,1]
print bubbleSort(arr,5)
| true |
709312e9a2f50148b6393f5adc5bb9c59d722fb8 | rahulcode22/Data-structures | /Two Pointers/RemoveElements.py | 660 | 4.1875 | 4 | '''
Given an array and a value, remove all the instances of that value in the array.
Also return the number of elements left in the array after the operation.
It does not matter what is left beyond the expected length.
Example:
If array A is [4, 1, 1, 2, 1, 3]
and value elem is 1,
then new length is 3, and A is now [4, 2, 3]
Try to do it in less than linear additional space complexity.
'''
def removeElement(arr,target):
i = 0
j = 0
n = len(arr)
while i < n:
if arr[i] != target:
arr[j] = arr[i]
j += 1
i += 1
return len(arr[0:j])
arr = [4,1,1,2,1,3]
target = 1
print removeElement(arr,target)
| true |
387179e6134508a1d71e818542318548d568258b | rahulcode22/Data-structures | /Math/FizzBuzz.py | 670 | 4.125 | 4 | '''
Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. Also for number which are multiple of 3 and 5, prints “FizzBuzz”.
'''
class Solution:
# @param A : integer
# @return a list of strings
def fizzBuzz(self, num):
lis = []
for i in range(1,num+1):
if i%3 == 0 and i%5 == 0:
lis.append("FizzBuzz")
elif i%3 == 0:
lis.append("Fizz")
elif i%5 == 0:
lis.append("Buzz")
else:
lis.append(i)
return lis
| true |
f675a20b4fb1b4acd7b8ca903097b07a666909f2 | rahulcode22/Data-structures | /Tree/level-order-traversal.py | 952 | 4.125 | 4 | class Node:
def __init__(self,key):
self.val = key
self.left = None
self.right = None
def printLevelOrder(root):
h = height(root)
for i in range(1,h+1):
printGivenOrder(root,i)
def printGivenOrder(root,level):
if root is None:
return
if level == 1:
print "%d" %(root.val),
elif level >1:
printGivenOrder(root.left,level-1)
printGivenOrder(root.right,level-1)
def height(node):
if node is None:
return 0
else:
#Compute Height of each subtree
lheight = height(node.left)
rheight = height(node.right)
if lheight>rheight:
return lheight+1
else:
return rheight+1
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Level order traversal of binary tree is -"
printLevelOrder(root)
| true |
ba2d6b6297ea813c6fbfd92782aada21cb368555 | rahulcode22/Data-structures | /Doublylinkedlist/DLL_insertion.py | 1,145 | 4.28125 | 4 | #Insertion at front
def insertafter(head,data):
new_node=node(data)
new_node.next=head
new_node.prev=None
if head is not None:
head.prev=new_node
head=new_node
#Add a node after a given node
def insertafter(prev_node,data):
if prev_node is None:
return
#Allocate new node
new_node=node(data)
#Make ne xt of new_node as next of prev_node
new_node.next=prev_node.next
#Make next of prev_node as next of new_node
prev_node.next=new_node.next
#Make prev_node as previous of new_node
new_node.prev=prev_node
if (new_node.next is not None):
new_node.next.prev=new_node
#Add a Node at end
def insertend(head,data):
new_node=Node(data)
last=head
#This new node is going to be last node,so make it as NULL
new_node.next=None
if head is not None:
new_node.prev=None
head=new_node
return
while (last.next is not none):
last=last.next
#Change next of last node
last.next=new_node
#Make last node as previous of new node
new_node.prev=last
return
| true |
d3123c6a569f57767865a6972bde32d3b858d348 | SamanehGhafouri/Data-Structures-and-Algorithms-in-python | /Experiments/find_largest_element.py | 676 | 4.3125 | 4 | # ######### Find the largest element in array ########
def largest_element(arr):
if len(arr) == 0:
return None
max_num = arr[0]
for i in range(len(arr)):
print(i, arr[i])
if arr[i] > max_num:
max_num = arr[i]
return max_num
ar = [90, 69, 23, 120, 180]
print(largest_element(ar))
# ############# Test Cases ##############
test_data = [
([1, 45, 23, 5, 67], 67),
([-3, -7, 1, 4, 2, -9], 4),
([-4, -1, -9, -3], -1),
([1, 45, 23, 5, 67, 97, 35], 97),
([], None)
]
for item in test_data:
expected = item[1]
computed = largest_element(item[0])
print(expected, computed, expected == computed)
| true |
5692a8e56f59808656816b733166021af8f5d3c1 | SamanehGhafouri/Data-Structures-and-Algorithms-in-python | /Sorting/bubble_sort.py | 682 | 4.3125 | 4 | # Bubble sort: takes an unsorted list and sort it in ascending order
# lowest value at the beginning by comparing 2 elements at a time
# this operation continues till all the elements are sorted
# we have to find the breaking point
# Time Complexity: best case: O(n)
# average and worst case: O(n^2)
def bubble_sort(li):
sorted_li = False
while not sorted_li:
sorted_li = True
for i in range(len(li) - 1):
if li[i] > li[i+1]:
sorted_li = False
li[i], li[i+1] = li[i+1], li[i]
return li
if __name__ == '__main__':
l = [9, 3, 1, 6, 8, 22, 0]
result = bubble_sort(l)
print(result) | true |
e35fd14187b0b277064bfc4d2019079376ba4781 | SamanehGhafouri/Data-Structures-and-Algorithms-in-python | /Recursion/reverse_str.py | 516 | 4.15625 | 4 | # C-4.16 reverse a string
def reverse_str(string):
if len(string) == 0:
return '' # we cut the first character and put it in
# the back of the string each time
else: # call the recursive function on the string except the first
return reverse_str(string[1:]) + string[0] # character 'amaneh' + 's' and so on
st = reverse_str('samaneh')
print(st)
| true |
7a37455274916403acdee17331216be6d7cc0810 | SachinKtn1126/python_practice | /11_better_calculator.py | 905 | 4.40625 | 4 | # Title: Creating a better calculator
# Author: Sachin Kotian
# Created date (DD-MM-YYYY): 07-12-2018
# Last modified date (DD-MM-YYYY): 07-12-2018
#
# ABOUT:
# This code is to create a better calculator using if else statement and user input.
# Input values from the user and store it in variables
num1 = float(input("Enter num 1: "))
op = input("Enter operator: ")
num2 = float(input("Enter num 2: "))
# Performing mathematical functions using the if else statement
if op == "+":
print("The sum is " + str(num1 + num2))
elif op == "-":
print("The difference is " + str(num1 - num2))
elif op == "/":
print("The division is " + str(num1 / num2))
elif op == "*":
print("The multiple is " + str(num1 * num2))
elif op == "%":
print("The modulus is " + str(num1 % num2))
else:
print("Invalid operator")
| true |
ab0ca448a75ff4094c8c7cfe7f112647a22ec37d | SachinKtn1126/python_practice | /10_if_statements_comparisons.py | 1,217 | 4.15625 | 4 | # Title: If statement in python
# Author: Sachin Kotian
# Created date (DD-MM-YYYY): 07-12-2018
# Last modified date (DD-MM-YYYY): 07-12-2018
#
# ABOUT:
# This code is to try and test the working of if statement
# Defining boolean variables
is_male = False
is_tall = False
# If statement
if is_male:
print("You are male")
else:
print("You are female")
# If else statement
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("Ypu are a tall female")
else:
print ("you are a short female")
# Defining a function to return the maximum number from 3 numbers
def max_num(num1,num2,num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
# Input values from the user
num1 = input("Enter num1: ")
num2 = input("Enter num2: ")
num3 = input("Enter num3: ")
# calling the function to get the max number and printing it
print("The maximum number is " + str(max_num(int(num1), int(num2), int(num3))))
| true |
71111a542b32a7815b1dd9c7f55ea93d3e75c2b0 | green-fox-academy/criollo01 | /week-02/day-05/palindrome_maker.py | 299 | 4.3125 | 4 | #Create a function named create palindrome following your current language's style guide.
# It should take a string, create a palindrome from it and then return it.
word = str(input("Write a word! "))
def palin_maker(word):
new_word = word + word[::-1]
print(new_word)
palin_maker(word)
| true |
601f2398b30c816fb76ee389a8a93995b98d2fa5 | green-fox-academy/criollo01 | /week-02/day-02/reverse.py | 306 | 4.5625 | 5 | # - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
aj = [3, 4, 5, 6, 7]
# ---solution 1---
for i in reversed(aj):
print(i)
#
# ---solution 2--- (nicer)
print(list(reversed(aj))) | true |
d00d45e57e5f130d3356cefa7bc7b50d63a185fe | saikrishna96111/StLab | /triangle.py | 516 | 4.1875 | 4 | print("enter three sides of a Triangle in the range (0 to 10)")
a=int(input("Enter the value of a "))
b=int(input("Enter the value of b "))
c=int(input("Enter the value of c "))
if a>10 or b>10 or c>10:
printf("invalid input values are exceeding the range")
if (a<(b+c))and(b<(a+c))and(c<(a+b)):
if a==b==c:
print("Equilateral Triangle")
elif (a==b)or(b==c)or(a==c):
print("Isosceles Triangle")
else:
print("Scalene Triangle")
else:
print("Not a Triangle")
| true |
abc28cc6001d0f1c626995ec69eda14235636446 | brybalicious/LearnPython | /brybalicious/ex15.py | 2,707 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# This line imports the argv module from the sys package
# which makes the argv actions available in this script
# Interestingly, if you run a script without importing argv, yet you type
# in args when you run the script in shell (!= python interpreter), it
# still runs and just ignores the args...
from sys import argv
# Here we unpack argv and store them in variables
script, filename = argv
# Here we open a file which we're passed as an argv, but don't do anything
# with it yet besides storing the open file in a file object variable 'txt'
# The contents of the file aren't returned here...
txt = open(filename)
# The following block is good practice, so that any opened file is always closed in the end, regardless of what happens in between...
#>>> with open('workfile', 'r') as f:
#... read_data = f.read()
#>>> f.closed
#True
# Just telling you what the file is, to show how argv works
print "Here's your file %r:" % filename
# Here's the magic.. we read the file we've opened, and display it
print txt.read()
# This bit's just a useless way of showing you can take a filename from
# raw_input... and store that name in the file_again variable, then open
# a file object by passing the filename, and storing the open file object
# in txt_again
print "Type the filename again:"
file_again = raw_input("> \a")
txt_again = open(file_again)
# And then print the contents to shell in the same way - using read()
# On the opened file object...
print txt_again.read()
# Here we will close the file instances we have opened and stored in 'txt' and 'txt_again' file object variables
txt.close()
txt_again.close()
#The following prints a confirmation of whether the objects have been closed...
print "Is txt closed?:", txt.closed
print "Is txt_again closed?:", txt_again.closed
# The sample exercise wants you to type 'python' into shell to open the python interpreter
# Then, you're supposed to type the following at the prompt - note the '':
#>>> open('ex15_sample.txt').read()
# Then you should expect this output:
#"This is stuff I like to write.\nComes out when called up by a python script.\nA'ight!"
#The mistake I was making is that I was trying to open the python script ex15.py inside the interpreter... that requires something like
#>>> execfile('ex15.py')
#I guess we'll soon see, but that would be what you'd call to execute a script from inside another script, right?
#Pay attention to where you need to pass filenames as strings (bounded by '') and where you don't. I couldn't figure out how to pass the argv elements to execfile, but maybe because I was a n00b trying to pass them to open() | true |
25bc4acccf3f18d73ef6b5a3fa6ea39dd4ba329e | ABradwell/Portfolio | /Language Competency/Python/Basic_Abilities/Arrays, Lists, and Selection sort/Occurances in List.py | 1,226 | 4.3125 | 4 | '''
Count the number of an element
occurrences in a list
• Create a function that takes a list and an integer v, and
returns the number of occurrences of v is in the list. Add
the variable NP as to count number of times the loop
runs (and display a message).
• The main program should generate a list, call the
function, and display the result.
>>> l = 52 14 14 8 85 69 1 77 94 96 51 65 35 32 87 92 74 47 27 88 11 11 26 14 100 37 62 3 63 5 20 53 28 10 43 16 94 6 82 49 74 55 89 97 12 38 72 94 3 77 42 26 25 16 89 10 8 63 93 77 68 56 74 45 54 50 80 33 69 95 2 79 73 6 3 41 38 81 88 12 39 77 49 30 18 22 40 40 12 51 69 32 76 77 90 60 41 12 30 65
>>> account (l3,6)
Number of steps 100
2
'''
def account(M, v):
NP = 0
count = 0
breakout = False
for w in M:
NP = NP + 1
if w== v:
count = count + 1
return(count, NP)
M = []
run = True
entered = input('Please enter a series of integers, split by spaces to add to the list: ').strip().split()
for v in entered:
inty = int(v)
M.append(inty)
v = int(input('Please enter a number to be searched for: '))
count, NP = account(M, v)
print('Number of steps:', NP)
print(count)
| true |
d75e6cfdd1f826e8cbd9c8c8ca744f38b4c4e8fd | ABradwell/Portfolio | /Language Competency/Python/Basic_Abilities/Matricies/Matrix Trandformation.py | 876 | 4.125 | 4 | ##– Exercise 1: Matrix transposed
##– Exercise 2: Sum of an array
##– Exercise 3: Multiplication with arrays
#Exercise One
#November 6th, 2018
'''
for example use... 1 2 3,
4 5 6
'''
def transform(A):
AT = []
collums = len(A)
rows = len(A[0])
i = 0
for i in range(0, rows):
newrow = []
for j in range(0, collums):
newrow.append(A[j][i])
AT.append(newrow)
return(AT)
rows = int(input('Please enter the number of rows you would like the matrix to have: '))
A = []
index = 0
while index < rows:
newrow = input('Please enter the row integer values, seperated by spaces: ').strip().split()
for i in range(0, len(newrow)):
newrow[i] = int(newrow[i])
A.append(newrow)
index = index + 1
AT = transform(A)
print(AT)
| true |
1d0ba82cfb5a76e6b7efd43a3b1266cf658dbca5 | JennifferLockwood/python_learning | /python_crash_course/chapter_9/9-13_orderedDict_rewrite.py | 860 | 4.1875 | 4 | from collections import OrderedDict
glossary = OrderedDict()
glossary['string'] = 'simply a series of characters.'
glossary['list'] = 'is a collection of items in a particular order.'
glossary['append'] = 'is a method that adds an item to the list.'
glossary['tuple'] = 'is an immutable list.'
glossary['dictionary'] = 'is a collection of key-value pairs.'
glossary['items()'] = 'this method returns a list of key-value pairs.'
glossary['sorted()'] = 'function that displays a list in a particular order.'
glossary['values()'] = 'method that return a list of values without any keys.'
glossary['append()'] = 'this method add a new element to the end of a list.'
glossary['reverse()'] = 'reverses the original order of a list permanently.'
for word, meaning in glossary.items():
print("\n" + word.upper() + ":" +
"\n\t" + meaning.capitalize()) | true |
9082625477c61bdd518483945261039e3868c49d | JennifferLockwood/python_learning | /python_crash_course/chapter_10/10-8_cats_and_dogs.py | 610 | 4.28125 | 4 | def reading_files(filename):
"""Count the approximate number of words in a file."""
try:
with open(filename) as file_object:
lines = file_object.readlines()
except FileNotFoundError:
msg = "\nSorry, the file " + filename + " does not exist."
print(msg)
else:
# Print the contents of the file to the screen.
print("\nThe file " + filename + " has the following names:")
for line in lines:
print("\t" + line.rstrip())
filenames = ['cats.txt', 'birds.txt', 'dogs.txt']
for filename in filenames:
reading_files(filename)
| true |
f9a57cf4fbffe700b4f0c15111c0e78479f0a263 | Jinsaeng/CS-Python | /al4995_hw3_q1.py | 382 | 4.21875 | 4 | weight = float(input("Please enter your weight in kilograms:"));
height = float(input("Please enter your height in meters:"));
BMI = weight / (height ** 2)
if (BMI < 18.5):
status = ("Underweight")
elif (BMI < 24.9 ):
status = ("Normal")
elif (BMI <29.9):
status = "Overweight"
else:
status = "Obese"
print("Your BMI is", BMI, ". Status:",status);
| true |
d1c7ab2c0a3a608ff42596a52315fced6f632d00 | Jinsaeng/CS-Python | /al4995_hw2_q1b.py | 383 | 4.21875 | 4 | weight = float(input("Please enter your weight in pounds:"));
height = float(input("Please enter your height in inches:"));
BMI = (weight*0.453592) / ((height*0.0254) ** 2)
#conversion using the note in the hw, pounds to kilo and inches to meters
#the example BMI is close to the one produced by the program but not exact?
#possible due to rounding issues?
print(BMI)
| true |
233187ddede43970dd98411b388c2f2c863fd215 | mihirkelkar/languageprojects | /python/double_ended_queue/doubly_linked_list.py | 899 | 4.15625 | 4 | """
Implementation of a doubly linked list parent class
"""
class Node(object):
def __init__(self, value):
self.next = None
self.prev = None
self.value = value
class DoublyLinked(object):
def __init__(self):
self.head = None
self.tail = None
def addNode(self, value):
if self.head == None:
self.head = Node(value)
self.tail = self.head
else:
curr = Node(value)
self.tail.next = curr
curr.prev = self.tail
self.tail = self.tail.next
def printList(self):
curr = self.head
while(curr != None):
print "The value of the this node is %s" %curr.value
print "------------"
curr = curr.next
def main():
Doubly = DoublyLinked()
Doubly.addNode(12)
Doubly.addNode(23)
Doubly.addNode(34)
Doubly.addNode(45)
Doubly.addNode(56)
Doubly.printList()
if __name__ == "__main__":
main()
| true |
851d77deec23c2cf86d338bc831ec253065f056b | mihirkelkar/languageprojects | /python/palindrome.py | 280 | 4.25 | 4 | def check_palindrome(string):
if len(string) > 1:
if string[0] == string[-1]:
check_palindrome(string[1:][:-1])
else:
print "Not a palindrome"
else:
print "Palindrome"
text = raw_input("Please enter your text string")
check_palindrome(text.lower().replace(" ",""))
| true |
bfe427c331a3d1982b2aa13cf45707e063356568 | mwpnava/Python-Code | /My_own_Python_package/guesser_game/numberGuesserGame.py | 2,373 | 4.28125 | 4 | from random import randrange
from .GuesserGame import Guesser
class GuessMyNumber(Guesser):
""" GuessMyNumber class for calculating the result of arithmetic operations applied to an unknow number
given by the player
Attributes:
numberinMind represents the number a player has in mind at the end of the game
magicNumber represents the most important number in this game, it will be used to 'guess' the numberinMind
"""
def __init__(self, number=0):
Guesser.__init__(self,number)
self.magicNumber = 2
def play(self):
'''Function to play GuessMyNumber
Args:
None
Returns:
None
'''
self.giveInstructions()
self.numberinMind = self.guessingNumber()
print('...')
print('Your result is {}'.format(int(self.numberinMind)))
def giveInstructions(self):
'''Function to display directions to play
Args:
None
Returns:
None
'''
self.magicNumber = self.generateMagicNumber()
print('Follow these steps and I will guess your result')
input("Press Enter to continue...")
print('Let''s play!')
print('Think a number greater than 0, do not tell me')
input("Press Enter to continue...")
print('Multiple your number times 2')
input("Press Enter to continue...")
print('Add {}'.format(self.magicNumber))
input("Press Enter to continue...")
print('Divide your result by 2')
input("Press Enter to continue...")
print('Last step, subtract to your result the number you initially though')
input("Press Enter to continue...")
print('...')
print('Guessing your result...')
def generateMagicNumber(self):
'''Function to generate an even random number between 4 and 24
Args:
None
Returns:
Integer: An even number between 4 and 24
'''
n = randrange(4, 24, 2)
return int(n)
def guessingNumber(self):
'''Function to 'guess' the result of arithmetic operations calculated during the GuessMyNumber
game.
Args:
None
Returns:
Integer: the result of arithmetic operations
'''
return self.magicNumber / 2
| true |
4e97f7e8c80fedb802649a3e1c51c60800a15bee | mwpnava/Python-Code | /missingValue3.py | 453 | 4.25 | 4 | '''
Consider an array of non-negative integers.
A second array is formed by shuffling the elements of the first array and
deleting a random element. Given these two arrays, find which element is missing in the second array.
Approach 3
'''
def missingValue(arr1,arr2):
arr1.sort()
arr2.sort()
for n1,n2 in zip(arr1,arr2):
if n1 != n2:
return n1
return arr1[-1]
x = missingValue([1,4,3,2,5],[1,5,2,3])
print(x)
| true |
8362df19e83ad9aa361557272d9abed226133853 | vzqz2186/DAnA_Scripts | /Arrays.Lists/vazquez_hw021218_v1.00.py | 2,015 | 4.15625 | 4 | """
Program: Arrays/List
Author: Daniel Vazquez
Date: 02/10/2018
Assignment: Create array/list with 20 possible elements. Fill with 10
random integers 1 <= n <= 100. Write a function to insert value
in middle of list.
Due Date:
Objective: Write a function to insert value in middle of list.\
(WORKS: v1.00)
Execute via: >>python vazquez_hw021218_v1.00.py
Sample output: vazquez_hw021218_v1.00.py
lista before insertion:
[4, 48, 31, 15, 94, 29, 89, 88, 21, 95]
Type number to insert to lista: 54
n = 54
lista after insertion:
[4, 48, 31, 15, 94, '54', 29, 89, 88, 21, 95]
02/10/2018 10:35
** Template based on Dr. Nichols program example. **
"""
#-----------------------------------------------------------------------------80
import time # Used to get current time and the timer for the program.
import random # Used to fill the list with the 10 random numbers.
def main():
print("vazquez_hw021218_v1.00.py\n")
"""
Source for creating the list:
https://www.youtube.com/watch?v=G_-ZR-B9STw up until minute 0:50
lista means list in Spanish
"""
lista = random.sample(range(1, 100), 10)
print("lista before insertion: \n",lista,"\n")
n = input("Type number to insert to lista: ")
print("\nn =",n, "\n")
"""
This bit splices the list in two at the middle so n can be inserted into
the list without the need of using the .append() tool.
Source for splicing idea:
https://stackoverflow.com/questions/42936941/insert-item-to-list-
without-insert-or-append-python/42937056
"""
lista = lista[:5] + [n] + lista[5:]
print("lista after insertion: \n", lista,"\n")
disDate() # Prints date
# Source:
# https://www.pythoncentral.io/how-to-display-the-date-and-time-using-python/
def disDate():
print(time.strftime('%m/%d/%Y %H:%M'))
#Call Main--------------------------------------------------------------------80
main()
| true |
b7757a06f89cacb51cb96eba0c685b4cf31a9b4a | jdobner/grok-code | /find_smallest_sub2.py | 1,537 | 4.21875 | 4 | def find_substring(str, pattern):
""" Given a string and a pattern, find the smallest substring in
the given string which has all the characters of the given pattern.
:param str:
:param pattern:
:return: str
>>> find_substring("aabdec", 'abc')
'abdec'
>>> find_substring("abdbca", 'abc')
'bca'
>>> find_substring('adcad','abc')
''
"""
freq_map = dict.fromkeys(pattern, 0)
found_indexes = None
window_start = 0
chars_found = 0
for window_end in range(len(str)):
nextChar = str[window_end]
if nextChar in freq_map:
if nextChar in freq_map:
freq = freq_map[nextChar] + 1
freq_map[nextChar] = freq
if freq == 1:
chars_found += 1
while chars_found == len(freq_map):
charToRemove = str[window_start]
if charToRemove in freq_map:
newFreq = freq_map[charToRemove] - 1
freq_map[charToRemove] = newFreq
if newFreq == 0:
chars_found -= 1
newLen = window_end - window_start + 1
if not found_indexes or found_indexes[0] > newLen:
found_indexes = (newLen, window_start, window_end + 1)
window_start += 1
if found_indexes:
return str[found_indexes[1]:found_indexes[2]]
else:
return ""
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) | true |
02c484b6cb30a7187b1b67585dfb0158747db857 | jamestonkin/file_storage | /car_storage.py | 1,195 | 4.34375 | 4 | class Car_storage:
""" This adds functionality and stores car list makes and models"""
def __init__(self):
self.car_makes = list()
self.car_models = list()
def read_car_makes(self):
""" Reads car makes from car-makes.txt file """
with open('car-makes.txt', 'r') as makes:
for make in makes:
self.car_makes.append(make[:-1])
return self.car_makes
def read_car_models(self):
""" Reads car models from car-models.txt file """
with open('car-models.txt', 'r') as models:
for model in models:
self.car_models.append(model[:-1])
return self.car_models
def create_car_dict(self):
""" Combines the makes with models and stores them into a dictionary in model: make format"""
car_dict = dict()
demo.read_car_makes()
demo.read_car_models()
for make in self.car_makes:
for model in self.car_models:
if model[:1] == make[:1]:
car_dict[make] = model[2:]
print(car_dict)
demo = Car_storage()
demo.create_car_dict()
# demo.read_car_makes()
# demo.read_car_models()
| true |
febdf1ea7d39be0fd144488b75c2f145d07a5677 | iumentum666/PythonCrashCourse | /Kapittel 10 - 11/word_count.py | 894 | 4.46875 | 4 |
# This is a test of files that are not found. If the file is not present,
# This will throw an error. We need to handle that error.
# In the previous file, we had an error. Here we will create the file
# In this version we will work with several files
# So the bulk of the code is put in a function
def count_words(filename):
"""
Count the approximate number of words in a file.
"""
try:
with open(filename, encoding='utf-8') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# Count the approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename) | true |
a8fa29813cb4291a39db8d93c46ff0c9c8d5bded | acpfog/python | /6.00.1x_scripts/Week 8/Final Exam/problem3.py | 966 | 4.46875 | 4 | #
# dict_invert takes in a dictionary with immutable values and returns the inverse of the dictionary.
# The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d.
# The value for a key in the inverse dictionary is a sorted list of all keys in d that have the same value in d.
#
# Here are some examples:
# If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}
# If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}
# If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]}
#
def dict_invert ( d ):
r = {}
for key in d.keys():
if d[key] in r.keys():
t = r[d[key]]
t.append( key )
r[d[key]] = sorted(t)
else:
r.update({ d[key] : [ key, ] })
return r
#d = {1:10, 2:20, 3:30}
#d = {1:10, 2:20, 3:30, 4:30}
d = {4:True, 2:True, 0:True}
print dict_invert ( d )
| true |
ccb58e3365e0bbfc25781cee9c118715a0493513 | acpfog/python | /6.00.1x_scripts/Week 2/do_polysum.py | 979 | 4.3125 | 4 | # A regular polygon has 'n' number of sides. Each side has length 's'.
# * The area of regular polygon is: (0.25*n*s^2)/tan(pi/n)
# * The perimeter of a polygon is: length of the boundary of the polygon
# Write a function called 'polysum' that takes 2 arguments, 'n' and 's'.
# This function should sum the area and square of the perimeter of the regular polygon.
# The function returns the sum, rounded to 4 decimal places.
import math
def polysum( n, s ):
area = ( 0.25 * n * s ** 2 ) / math.tan ( math.pi / n )
perimeter = n * s
result = area + perimeter ** 2
result = round( result, 4 )
return result
print("A regular polygon has 'n' number of sides. Each side has length 's'.")
sides = int(raw_input("Enter number of sides: "))
length = float(raw_input("Enter length of a side: "))
if ( sides < 3 ):
print ("A regular polygon cannot have less than 3 sides")
else:
sides = float(sides)
print "The result is %s" % polysum ( sides , length )
| true |
a7699c41987cbf101e478a6a1623e5bf83221997 | paw39/Python---coding-problems | /Problem13.py | 1,257 | 4.34375 | 4 | # This problem was asked by Amazon.
#
# Run-length encoding is a fast and simple method of encoding strings.
# The basic idea is to represent repeated successive characters as a single count and character.
# For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
#
# Implement run-length encoding and decoding. You can assume the string to be encoded have
# no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
from collections import OrderedDict
def encoding(message):
count = 1
results = []
for i in range(1, len(message)):
if message[i] == message[i-1]:
count += 1
else:
results.append((count, message[i-1]))
count = 1
if i == len(message) - 1:
results.append((count, message[i]))
for result in results:
print(result[0], result[1], sep="", end="")
def decoding(message):
results = []
for i in range(len(message) - 1):
if message[i].isdigit():
results.append(int(message[i]) * str(message[i+1]))
else:
i += 1
print(*results, sep="")
if encoding("AAAABBBCCDAA") == decoding("4A3B2C1D2A"):
print("Decoding and encoding works!")
| true |
f40e03b6e5812149476681db8ddc24fd22e2063b | HS4MORVEL/Lintcode-solution-in-Python | /004_ugly_number_II.py | 1,009 | 4.25 | 4 | '''
Ugly number is a number that only have factors 2, 3 and 5.
Design an algorithm to find the nth ugly number.
The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Notice
Note that 1 is typically treated as an ugly number.
Example
If n=9, return 10.
Challenge
O(n log n) or O(n) time.
'''
from heapq import heappush, heappop
class Solution:
"""
@param: n: An integer
@return: the nth prime number as description.
"""
def nthUglyNumber(self, n):
if n <= 1:
return n
primes = [2, 3, 5]
min_heap = [1]
visited = set()
for i in range(n):
result = heappop(min_heap)
for j in range(len(primes)):
if result * primes[j] not in visited:
heappush(min_heap, result * primes[j])
visited.add(result * primes[j])
return result
# def main():
# s = Solution()
# print(s.nthUglyNumber(9))
#
#
# if __name__ == '__main__':
# main()
| true |
33fab8dd21256c3f107d68652af5e6cc9216809a | athina-rm/extra_labs | /extralabs_basic/extralabs_basic.py | 343 | 4.15625 | 4 | #Write a Python program display a list of the dates for the 2nd Saturday of every month for a
#given year.
from datetime import datetime
year=int(input("enter the year:"))
for j in range(1,13):
for i in range (8,15):
dates =datetime(year,j,i)
if dates.strftime("%w")=="6":
print(dates.strftime("%Y-%m-%d"))
| true |
a6737f8bc4d71bb4d48b3b62c8145626a578007e | athina-rm/extra_labs | /extralabs_basic/module5.py | 273 | 4.375 | 4 | # Find
#Find all occurrences of “USA” in given string ignoring the case
string=input("Enter the string : ")
count=0
count=string.lower().count('usa')
if count==0:
print('"USA" is not found in the entered string')
else:
print(f'"USA" is found {count} times')
| true |
b1020a0e36baa29b31dd14c9f476c80fe095ef95 | rob0ak/Hang_Man_Game | /app.py | 2,728 | 4.125 | 4 | import random
def set_up_game(word, list_of_letters, blank_list):
for letter in word:
list_of_letters += letter
blank_list += "-"
def find_letters(word_list, blank_list, guess, list_of_guesses):
count = 0
# Checks the users guess to see if its within the word_list
for letter in word_list:
if letter == guess:
print("correct")
blank_list[count] = guess
count += 1
if guess not in list_of_guesses:
list_of_guesses += guess
# Compares list_of_guesses and blank_list to remove letters that don't belong in the list_of_guesses
for letter in list_of_guesses:
if letter in blank_list:
list_of_guesses.remove(user_guess)
def check_for_win(word_list, blank_list):
if word_list == blank_list:
return True
else:
return False
def get_char():
user_input = input("Guess a letter from A-Z: ").upper()
allowed_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while len(user_input) != 1 or user_input not in allowed_chars:
user_input = input("Guess a letter from A-Z: ").upper()
return user_input
def text_animation(wrong_count):
animation = (
"""
|-----
| |
|
|
|
|------------
""",
"""
|-----
| |
| O
|
|
|------------
""",
"""
|-----
| |
| O
| |
|
|------------
""",
"""
|-----
| |
| O
| |\
|
|------------
""",
"""
|-----
| |
| O
| /|\
|
|------------
""",
"""
|-----
| |
| O
| /|\
| /
|------------
""",
"""
|-----
| |
| O
| /|\
| / \
|------------
"""
)
return animation[wrong_count]
list_of_words = ["strengthen","Hello","therapeutic","vegetable","chemical"]
word_choice = random.choice(list_of_words).upper()
letters_in_word = []
blank_word_list = []
wrong_guesses = []
set_up_game(word_choice, letters_in_word, blank_word_list)
hang_man = True
while hang_man:
print(text_animation(len(wrong_guesses)))
print(blank_word_list)
print(f'Guesses: {wrong_guesses}')
user_guess = get_char()
find_letters(letters_in_word, blank_word_list, user_guess, wrong_guesses)
if check_for_win(letters_in_word, blank_word_list):
print("Congratulations you won!!! :)")
break
if len(wrong_guesses) > 5:
print('Sorry you lose! :(')
print(text_animation(len(wrong_guesses)))
break
| true |
5c708d99765f36579409eca6fa9d389b0f83b16e | Albertpython/pythonhome | /home14.py | 328 | 4.375 | 4 | '''Write a Python program to find the
length of a tuple'''
# tup = ("black", "bmw", "red", "ferrary")
# res = 0
# for x in tup:
# res += 1
# continue
# print(res)
'''Write a Python program to convert a tuple to a string'''
# name = ('A', 'L', 'B', 'E', 'R', 'T')
# print(name[0]+name[1]+name[2]+name[3]+name[4]+name[5])
| true |
db53054877bc9e03ad2feba2efba6c0792857c32 | panovitch/code-101 | /1_shapes _and_color.py | 1,510 | 4.15625 | 4 | """
Here we introduce the concepts of statements and basic types: strings and integers.
WE talk about how a program is a list of senteses exuted from top to bottom, and
that some commands can result in a change of state, and some commands are just actions to execute.
We also explain what comments are :D
"""
# here we talk about how all programming languages are made of modules - and we are going to be using a turtle module!
# but we also say they shouldnt worry about it for now.
import turtle
tina=turtle.Turtle()
tina.shape("turtle")
# this is a statement that makes turtle go forward!
tina.forward(90)
# this is a statement that makes turtle turn!
tina.right(50)
# this is a statement that doesnt seem to do anything.
# notice how the argument to this command is different - we provide the color name instead of a numerical value
# in programming, we usually call text values "strings"
tina.color("blue")
# however, now see what happens when we draw!
tina.forward(20)
tina.reset()
# lets draw a square!
tina.forward(20)
tina.right(90)
tina.forward(20)
tina.right(90)
tina.forward(20)
tina.right(90)
tina.forward(20)
tina.reset()
# ====== task! ======
# draw a green triangle!
# advanced! draw a black circle surrounding the triangle (doesnt have to be centred, unless you are big on geometry)
# ====== expected result ======
import turtle
tina=turtle.Turtle()
tina.shape("turtle")
tina.color("green")
tina.forward(50)
tina.left(120)
tina.forward(50)
tina.left(120)
tina.forward(50)
| true |
2b4f5355db301ea1a0c2892d384a48dec3c3ecae | Ratheshprabakar/Python-Programs | /maxmin.py | 260 | 4.15625 | 4 | print("Enter the three numbers")
a=int(input("Enter the 1st Number"))
b=int(input("Enter the 2nd Number\n"))
c=int(input("Enter the 3rd Number"))
print("The maximum among three numbers",max(a,b,c))
print("The Minimum among three numbers",min(a,b,c))
| true |
4879b0be7e47945416bfe1764495968ae896726c | Ratheshprabakar/Python-Programs | /concatenate and count the no. of characters in a string.py | 318 | 4.3125 | 4 | #Concatnation of two strings
#To find the number of characters in the concatenated string
first_string=input("Enter the 1st string")
second_string=input("Enter the 2nd string")
two_string=first_string+second_string
print(two_string)
c=0
for k in two_string:
c+=1
print("No. of charcters in string is",c)
| true |
e54a34636c36321cb03605dfc39b69f1fab40f89 | Ratheshprabakar/Python-Programs | /Multiplication table.py | 241 | 4.28125 | 4 | #To display the multiplication table
x=int(input("Enter the table no. you want to get"))
y=int(input("Enter the table limit of table"))
print("The Multiplication table of",x,"is:")
i=1
while i<=y:
print(i,"*",x,"=",x*i)
i+=1
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.