blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
57442e4aa8b9f92750dc9336bbc0addefdaedf31 | haticerdogan/python-3-sandbox | /basics.py | 1,584 | 4.4375 | 4 | # Lesson 3 - Numbers
# https://www.youtube.com/watch?v=Gqby4v5JOu4&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=3
# everything in Python is an object, and objects have attributes & methods that are functions
type(500)
# <class 'int'>
type(5.1)
# <class 'float'>
5 / 5
# 1.0 <= retruns a float
5 / 5
# 1 <= retruns an integer
10 % 3
# 1 <= remainder, or 'modulus'
5 ** 5
# 3125 <= 5 to the power of 5
5 + 5 * 3
# 20
(5 + 5) * 3
# 30
# (BIDMAS) Brackets -> Indices -> Multiplication -> Addition -> Subtraction
age = 25
age += 5 # or -= for the opposite
age
# 35
wages = 1000
bills = 200
rent = 500
food = 200
savings = wages - bills - rent - food
savings
# 100
# Lesson 4 - Strings
# https://www.youtube.com/watch?v=Gqby4v5JOu4&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=4
noun = 'you\'re here' # canceler
greet = 'hello'
greet[0:4]
# 'hell'
greet[2:-1]
# 'll'
greet + " " + noun
# hello you're here
greet * 3
# 'hellohellohello'
greet.upper()
# Hello
len(greet)
# 5
cheeses = "Brie, Chedder, Stilton"
cheeses.split(',')
# ['Brie', 'Chedder', 'Stilton']
# Lesson 5 - Lists
# https://www.youtube.com/watch?v=Gqby4v5JOu4&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=5
list1 = ['Bob', 'Tom', 'Ron'] # Ruby or JavaScript "array"
list1[1]
# 'Tom'
list2 = list1 + ["Cat"]
# ['Bob', 'Tom', 'Ron', 'Cat']
list2.append('Dan')
# ['Bob', 'Tom', 'Ron', 'Cat', 'Dan']
list2.pop() # removes the last item ('Dan')
# ['Bob', 'Tom', 'Ron', 'Cat']
list2.remove('Tom')
# ['Bob', 'Ron', 'Cat']
del(list2[0])
# ['Ron', 'Cat']
nest = [[1, 2], [3, 4], [5, 6]]
nest[2][1]
# 6
| false |
36f66aa5e656cc03fe2997b5c1817d454ee6566f | haticerdogan/python-3-sandbox | /lessons/intro_to_classes.py | 2,572 | 4.1875 | 4 | name = 'Me'
age = 92
qaimah = [1, 2, 3]
qamous = {"A":1, "B":2, "C":3}
type(name) #=> <class 'str'>
type(age) #=> <class 'int'>
type(qaimah) #=> <class 'list'>
type(qamous) #=> <class 'dict'>
# class name must have capitol letter
class Planet:
# initializer (init function) that runs when we create a new instance
# similiar to a constructor method in JavaScript
def __init__(self):
# self is like "this" in JavaScript
self.name = "Hoth"
self.radius = 200000
self.gravity = 5.5
self.system = "Hoth System"
# a class function takes in 'self' as a variable:
def orbit(self):
return f'{self.name} is orbiting in the {self.system}'
# new instance of the Planet object is invoked by calling it like "Planet()"
hoth = Planet()
print(f'Name is: {hoth.name}')
print(f'Radius is: {hoth.radius}')
# calling a class function
print(hoth.orbit())
# now let's create an object where we require the instance variables upon creation
# of a new class instance
class Kaoukab:
# class attributes go here:
shape = 'all kaouakibu are spherical'
# This is a class method:
@classmethod
def commons(cls): # 'cls' referrs to the class
return f'I think that it\'s true to say that:{cls.shape}'
# https://www.youtube.com/watch?v=LwFnF9XoEfM&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=18
# Static methods doen't have access to 'delf' or the class itself...
# it only has access to the parameters we pass into it individually
@staticmethod
def spin(speed = "2000 miles per hour"):
return f'the planet spins at {speed}'
def __init__(self, name, radius, gravity, system):
# self is like "this" in JavaScript
self.name = name # instance attribute or instance method
self.radius = radius # instance attribute or instance method
self.gravity = gravity # instance attribute or instance method
self.system = system # instance attribute or instance method
def orbit(self):
return f'{self.name} is orbiting in the {self.system}'
# new instance of the Kaoukab object is invoked by calling it like "Planet()"
naboo = Kaoukab('Naboo', 200000, 5.5, 'Naboo System')
print(f'Name: {naboo.name}')
print(f'Gravity: {naboo.gravity}')
print(naboo.orbit())
print(Kaoukab.shape) # same as "naboo.shape" b.c. each instance has the same value
# in order to use a class method, you have to call it "()" on the class name:
print(Kaoukab.commons())
print(naboo.spin('a very high speed')) # same value using static method
print(Kaoukab.spin('a very high speed'))# same value using static method
| true |
478d373625d0e07326947865540f964ac667d96f | haticerdogan/python-3-sandbox | /projects/ipsum_gen.py | 1,205 | 4.125 | 4 | # Lesson 28
# https://www.youtube.com/watch?v=iLS4Hk-kJXE&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=28
from random import randint
# we will take these ninja works and randomly inject them into the loreum ipsum text
ninja_words = [
'Aiki', 'Buyu', 'Chimonjutsu', 'Cho sen', 'Dojo', 'Gakusei', 'Haiboku',
'Jin', 'Kenshi', 'Obake ken', 'Rakusha', 'Sanmaru', 'Tekkon', 'Yoko'
]
# this takes in a wor each time we are looping
def ninjarize(word):
random_pos = randint(0, len(ninja_words) - 1)
return f'{word} {ninja_words[random_pos]}'
# this will use the "input()" method to get an ansewr from the user in bash
paragraphs = int(input('How many paragraphs of ninja ipsum: '))
# grabbing the .txt file external to this script:
with open('ipsum.txt') as ipsum_original:
# ".read()" will read the file
# ".split()" will take each work and make it an element in a list called "items"
items = ipsum_original.read().split()
# now we need to loop through each paragraph
for n in range(paragraphs): # this is an integer from the user
ninja_text = list(map(ninjarize, items) )
with open('ninja_ipsum.txt', 'a') as ipsum_ninja:
ipsum_ninja.write(' '.join(ninja_text) + '\n\n')
| false |
c3939d358034b7645abb3cf0502b4a5541f927be | haticerdogan/python-3-sandbox | /lessons/comprehension.py | 835 | 4.53125 | 5 | # let's say we have a list of prizes and we want to double each one
prizes = [5, 10, 50, 100, 1000]
double_prizes = [] # create an empty array
for prize in prizes:
double_prizes.append(prize*2)
print(double_prizes)
# comprehension method: this gives the same values as above but is much shorter
double_prizes = [prize*2 for prize in prizes]
print(double_prizes)
# squaring of even numbers from 1 to 10.
nums = [1,2,3,4,5,6,7,8,9,10]
squared_even_numbers = []
# Let's see another example of how to use comprehension
for num in nums:
# if the number squared modulus 2 (if the number is even)
if(num**2) % 2 == 0:
squared_even_numbers.append(num**2)
print(squared_even_numbers)
# another use of the comprehension method:
squared_even_numbers = [
num**2 for num in nums if(num**2) % 2 == 0
]
print(squared_even_numbers)
| true |
77c108253545d0b02b5928afd024cc83d5937158 | haticerdogan/python-3-sandbox | /lessons/dictionary.py | 1,622 | 4.625 | 5 | # Lesson 14 - Dictionaries
# https://www.youtube.com/watch?v=Gqby4v5JOu4&list=PL4cUxeGkcC9idu6GZ8EU_5B6WpKTdYZbK&index=14
# Dictionaries are the same as Javascript objects or Ruby hashes.
people_ages = {'ron':12, 'bob':5, 'tom':36, 'dan':41, 'cat':39, 'alf':73}
print(people_ages)
# check to see if a key exists inside the dictionary
print('ron' in people_ages)
# find the value for the key in the dictionary
print(people_ages['ron'])
# get the keys for the dictionary
print(people_ages.keys())
# get the same thing returned as an actual list (i.e. "array" in Ruby or JS)
print(list(people_ages.keys()))
# get the values back as a list (i.e. "array" in Ruby or JS)
print(list(people_ages.values()))
my_names = list(people_ages.keys())
print("there's ", my_names.count('ron'), "ron in the list!")
# this is a different way to declare a dictionary
person = dict(name='shaun', age=27, height=6)
# When called, the syntax has ":" instead of "=" and the keys are in quotations 'name'
print(person) #=> {'name': 'shaun', 'age': 27, 'height': 6}
ninja_belts = {}
while True:
ninja_name = input('enter a ninja name:')
ninja_belt = input('enter a belt color:')
# grab the key (in the dictionary) you just defined above and give it a value
# you assigned right below it
ninja_belts[ninja_name] = ninja_belt
another = input('add another? (y/n)')
if another == 'y':
continue
else:
break
print(ninja_belts)
def ninja_intro(dictionary):
# cycle through the dictionary
for key, val in dictionary.items():
print(f'I have a key of: {key} and a value of: {val} !')
ninja_intro(ninja_belts)
| true |
955a214fdc776fff7f4d5d1771dffebdb8bdac7a | TungTNg/itc110_python | /Mon_07_09/volumArea.py | 568 | 4.375 | 4 | # volumeArea.py
# a program which calculates the volume and surface are of a sphere from its radius, given as input
import math
def main():
print('# This is a program which calculates the volume and surface are of a sphere')
print()
radius = float(input('Enter the radius of the sphere: '))
volume = 4.0 / 3.0 * math.pi * math.pow(radius, 3)
area = 4.0 * math.pi * math.pow(radius, 2)
print()
print('The volume of the sphere is:', round(volume, 5))
print('The surface are of the sphere is:', round(area, 5))
main()
| true |
5cc1874098689afa851baf216a254d2259dfa46f | TungTNg/itc110_python | /Assignment/wordCalculator.py | 600 | 4.375 | 4 | # wordCalculator.py
# A program to calculate the number of words in a sentence
# by Tung Nguyen
def main():
# declare program function:
print("This program calculates the number of words in a sentence.")
print()
# prompt user to input the sentence:
sentence = input("Enter a phrase: ")
# split the sentence into a list that contains words
listWord = sentence.split()
# count the number of words inside the list
countWord = len(listWord)
# print out the number of words as the result
print()
print("Number of words:", countWord)
main() | true |
a61f6d3b35429b5596e9eca89cac63e55b3e2160 | ottersome/progra_class | /python2/HW/0616115_hw9-2.py | 2,154 | 4.53125 | 5 | #!/usr/bin/python
import math
#this function is always run to check the validity of the input
def filterinput(inputo):
#the given string is stripped from its parenthesis and then split into three through at the commas
divider = inputo[1:]
divider = divider[:-1]
divider = divider.split(",")
#we test if the user wrote exit, if so we quit the program and of course let the user know
if(inputo.lower() == "exit"):
print("Now exiting...")
quit()
#we test that we have all three required arguments
if(len(divider) != 3):
print("The amount of arguments is not three")
return None
#we try to conver this values into tuples and if it doesnt work we let the users know
else:
try:
tuplo = (float(divider[0]),float(divider[1]),float(divider[2]))
return tuplo
except ValueError:
print("Please enter a value that corresponds with the requested format")
return None
#not much to explain on this funciton. we simply add the lengths of both balls and compare with the distance obtained through the use of pythagoras. if the sum of radii is larger we say they collide
def compareinputs(inputo1,inputo2):
sum_of_radii = inputo1[2] + inputo2[2]
distance = math.sqrt(((inputo2[0]-inputo1[0])**2)+((inputo2[1]-inputo1[1])**2))
if(sum_of_radii > distance):
print("There is a collision!!")
else:
print("There is no collision")
#we run this in a loop to make sure it continues asking for inputs
while(True):
#we state our variables
tuplo1 = None
tuplo2 = None
#these two while loops test for the valiidy of the input and only break when the values are determined safe and valid
while(tuplo1 == None):
tuplo1 = filterinput(input("Enter the first ball (x,y,range) enter \"exit \" to quit the program:\n"))
while(tuplo2 == None):
tuplo2 = filterinput(input("Enter the second ball (x,y,range) enter \"exit \" to quit the program:\n"))
#this function will compare the values and let us know wether they collide or not
compareinputs(tuplo1,tuplo2)
print(' ')
| true |
3bbf75477b3424bc848e21ee6b6c161a7e60853c | Candy-Sama/Python-Mini-Programs | /Validating Inputs.py | 1,071 | 4.1875 | 4 | def user_choice():
#Variables
#inital variables
choice = 'Wrong' #initialise the variable as a false non-digit
acceptable_range = range(0,10)
within_range = False
#Check for two conditions in while loop
#digit OR within_range == False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a number (0-10): ")
#What the player writes will be checked. If it's not a digit, the while loop will keep running
#digit check
if choice.isdigit() == False:
print("Sorry, that is not a valid input!")
#if it's not a digit, print out this line
#range check
# (By the time it comes to this line, you are assuming choice.isdigit() == true)
if choice.isdigit() == True:
if int(choice) in acceptable_range:
within_range = True
else:
print("Sorry, that is not a valid number!")
within_range = False
return int(choice) | true |
0012a3e390179373f71989e4154dc4f383042efb | muthuguna/python | /Sample4.py | 583 | 4.15625 | 4 | myDictionary ={}
def addItem():
inptCity = input("Enter the City:")
inptZip = input("Enter the Zip:")
myDictionary[inptCity]=inptZip
def printItem():
print(myDictionary);
def deleteItem():
itemToDelete = input("Enter the City to delete:")
myDictionary.pop(itemToDelete)
while(1):
optionInput = input("Enter the option 'a' to Add, 'p' to Print, 'd' to Delete")
if(optionInput == 'a'):
addItem()
elif(optionInput == 'p'):
printItem()
elif(optionInput == 'd'):
deleteItem()
else:
break
| true |
674e8f75bfc2d8087dcbfdec8721e8fd268e9401 | muthuguna/python | /Sample3.py | 929 | 4.15625 | 4 | """
myDictionary= {}
def add():
nameValue = input("Enter name to add:")
movieValue = input("Enter movie to add:")
myDictionary[nameValue] = movieValue
def printItems():
print(myDictionary)
def deleteItem():
nameValue = input("Enter name to delete:")
del myDictionary[nameValue]
while(1):
option = input("Enter option 'a' (Add), 'p' (Print), 'd' (Delete :")
if option == 'a':
add()
elif option == 'p':
printItems()
elif option == 'd':
deleteItem()
else:
break
"""
#Go to this link and select Turn On
#https://www.google.com/settings/security/lesssecureapps
import smtplib, getpass
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
userName = input("Enter userName:")
pwd = getpass.getpass("Enter Password:")
server.login(userName, pwd)
server.sendmail("From Email id", "To Email id", "Test mail")
server.quit()
#Go to this link and select Turn Off | true |
364f3e308398fe7d589bd48345d8bea3ff9e1e8b | anneharris4/Hackbright-Intro-to-Programming-Assignments | /Lesson_8/ultimatebillcalc.py | 1,200 | 4.125 | 4 | total_bill = 0.0
tip = 0.0
bill_before_tip = 0.0
people_number = 1.0
bill_per_person= 0.0
def prompt_user():
global total_bill
global tip
global bill_before_tip
global people_number
bill_before_tip = float(raw_input('how much is on the bill not including tip?'))
dine_alone = raw_input('did you dine alone? y/n')
if dine_alone == 'no':
people_number = float(raw_input('how many people were at dinner?'))
else:
people_number = 1.0
tip_percentage = raw_input('is 18% tip ok?')
if tip_percentage == 'no':
tip = float(raw_input('how much would you like to leave for tip?'))
else:
tip = .18
def calculate_bill():
global bill_before_tip
global tip
global bill_per_person
global total_bill
total_bill = bill_before_tip + (tip * bill_before_tip)
bill_per_person = total_bill/people_number
def display_bill_amounts():
global bill_before_tip
global tip
global bill_per_person
global total_bill
print 'the bill before tip is', bill_before_tip
print 'the tip is', tip
print 'the bill with tip is', total_bill
print 'the bill per person is', bill_per_person
def main():
prompt_user()
calculate_bill()
display_bill_amounts()
if __name__ == '__main__':
main()
| false |
1c7b12aae485cd956ed12bb8d3c4b8dc34950de0 | RiddhiDamani/Python | /Ch3/dates_start.py | 1,142 | 4.375 | 4 | #
# Example file for working with date information
#
# we are telling the python interpreter here that from the datetime standard built in module that comes with the standard library - importing date, time, datetime classes. These are the predefined pieces of functionality in the Python library. To use it, you need to import it.
from datetime import date
from datetime import time
from datetime import datetime
def main():
## DATE OBJECTS
# Get today's date from the simple today() method from the date class
today = date.today()
print("todays date is:", today)
# print out the date's individual components
print("Dates Components: ", today.day, today.month, today.year)
# retrieve today's weekday (0=Monday, 6=Sunday)
print("Today's week day number is: ", today.weekday())
days = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"]
print("Which is a : ", days[today.weekday()])
## DATETIME OBJECTS
# Get today's date from the datetime class
today = datetime.now()
print(today)
# Get the current time
t = datetime.time(datetime.now())
print(t)
if __name__ == "__main__":
main()
| true |
c94ea9fb0e996c7c1bd777a4562f347c2bc2ad7e | RiddhiDamani/Python | /Chap11/hello.py | 2,075 | 4.6875 | 5 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# Strings are the first class objects in Python3.
# The below is a literal string. You can call methods on it.
# A string is immutable - it cannot be changed. So, when we use one of the below transformation methods,
# the return string is a different object.
print('Hello, World.')
print('Hello, World.'.upper())
print('Hello, World.'.swapcase())
print('Hello, World. {} '.format(42 * 7))
s = 'Hello Riddhi'
print(s.upper())
# str is a built-in string class in Python3
class MyString(str):
def __str__(self):
return self[::-1]
x = MyString('Hello Coder! ')
print(x)
# .upper() - prints all upper case letters
# .lower() - prints all lower case letters
# .capitalize() - capitalizes just the first letter of the string and makes everything else lowercase
# .title() - capitalizes the first letter of every word
# .swapcase() - swap the case of every letter. i.e. lower to upper and upper to lower
# .casefold() - makes everything lower case. casefold is more aggressive and it removes all distinction even in unicode.
s1 = 'Helo Coder!'
s2 = s1.upper()
# both are different objects
print(id(s1))
print(id(s2))
s1 = 'Helo Coder!'
s2 = 'How are you?'
# Literal strings can be concatenated like this.
s3 = s1 + ' ' + s2
s4 = 'Riddhi S. ' ' ' 'Damani'
print(s3)
print(s4)
#format() method is used to format the strings
x = 42
y = 73
print('the number is {} {}'.format(x, y))
print('the number is {xx} {bb}'.format(xx = x, bb = y))
print('the number is {1} {0} {0}'.format(x, y))
# formatting instructions are preceded by colon ; number of spaces including the value. I can also have leading zero.
# sign takes up one of the 5 positions.
print('the number is {0:<5} {1:+05}'.format(x, y))
print(f'the number is {x}')
y = 42 * 747 * 100
print('the number is {:,}'.format(y).replace(',','.'))
# can specify fixed number of decimal places
# 3 places to the right of decimal point.
print('the number is {:.3f}'.format(y))
z = 42
print('the number is {:b}'.format(z))
print(f'the number is {x:.3f}') | true |
353faed27acb5088ba6d0fa4bb25e32bdf25cea2 | RiddhiDamani/Python | /Chap06/while.py | 461 | 4.25 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
secret = 'swordfish'
pw = ''
auth = False
count = 0
max_attempt = 5
# the below loop ends when u enter 'swordfish' as the password. then, pw == secret breaks the loop.
while pw != secret:
count += 1
if count > max_attempt: break
if count == 3: continue
pw = input(f"{count}: What's the secret word? ")
else:
auth = True
print("Authorized" if auth else "Calling the FBI...") | true |
4a6a6028a00df460c4de1e2ae9f539c16a4b215f | RiddhiDamani/Python | /Ch6/definition_start.py | 1,672 | 4.21875 | 4 | # Python Object Oriented Programming by Joe Marini course example
# Basic class definitions
# TODO: create a basic class
class Book:
# pass statement is used as a placeholder for future code.
# When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.
# Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
# pass
# overiding built in init function
# init function is one of the special function of python when working with classes.
# when we create an instance of the class i.e. b1 = Book(), the init function is called to initialize the new object with information. And it is called before any other functions that you have defined on the class. This is specifically an initializer function and not the constructor func like Java or C.
# the object is already been created or constructed before the initializer func is called. So, you know that it is safe to start initializing attributes.
# whenever we call a method on a Python object, the object itself gets automatically passed in as the first argument. The word 'self' is just the naming convention. We dont need to call it that, but mmost Python programs follow this convention.
def __init__(self, title):
# creating a new attibute on an object called title and it is being used to hold the title of the book.
self.title = title
# TODO: create instances of the class
b1 = Book("Brave new world")
b2 = Book("War and Peace")
# TODO: print the class and property
# accessing the attribute of an object using the dot property
print(b1)
print(b1.title) | true |
027eb6a226bc7d565613976080d423cdafdde799 | RiddhiDamani/Python | /Chap09/methods.py | 1,973 | 4.21875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# A function that is associated with a class is called a method.
# This provides the interface to the class and its objects.
class Animal:
def __init__(self, **kwargs):
self._type = kwargs['type'] if 'type' in kwargs else 'kitten'
self._name = kwargs['name'] if 'name' in kwargs else 'fluffy'
self._sound = kwargs['sound'] if 'sound' in kwargs else 'meow'
# serves as both getter and the setter.
# first arg is self and that makes this is a method, not just a plain function.
def type(self, t=None):
# if there is a value associated with t variable, then it will set to the type variable.
# if there is no t value, then this if will fail and it'll just return the value of type.
if t: self._type = t
# else it will set value none and return it. t has default value of None.
# this makes it a setter and getter method.
return self._type
def name(self, n=None):
if n: self._name = n
return self._name
def sound(self, s=None):
if s: self._sound = s
return self._sound
# special named method which provides string representation of the object
# and it allows us to print it with simply this print and the object like that.
# without needing to have a special function just for the print statement.
def __str__(self):
return f'The {self.type()} is named "{self.name()}" and says "{self.sound()}".'
def main():
a0 = Animal(type='kitten', name='fluffy', sound='rwar')
a1 = Animal(type='duck', name='donald', sound='quack')
# set the variable sound using the setter getter.
a0.sound('bark')
print(a0)
print(a1)
if __name__ == '__main__': main()
# Methods are the primary interface for classes and objects.
# They work exactly like functions except they are bound to the object through their first arguments
# commonly named self.
| true |
434a299748a5986e50b528d80351206bb7e618b7 | maxawolff/code-katas | /src/find_outlier.py | 746 | 4.25 | 4 | """Find the pairity outlier.
best practice solution:
def find_outlier(int):
odds = [x for x in int if x%2!=0]
evens= [x for x in int if x%2==0]
return odds[0] if len(odds)<len(evens) else evens[0]
"""
def find_outlier(integers):
"""Return whatever number is an outlier from a list, even or odd."""
def is_even(number):
if number % 2:
return -1
else:
return 1
odd_or_even = is_even(integers[0])
+ is_even(integers[1]) + is_even(integers[2])
if odd_or_even > 0:
for number in integers:
if is_even(number) == -1:
return number
else:
for number in integers:
if is_even(number) == 1:
return number
| false |
f455463a341d56c4005d6000fb83fd840a9d53fb | ThompsonBethany01/Python_Practice_Problems | /Codeup_Challenges/Alphabet_Soup.py | 1,007 | 4.375 | 4 | # Alphabet Soup Solution
# By Bethany Thompson
# 1/20/2021
def alphabetize_words(my_string):
'''
This functions accepts a string and returns the string sorted alphabetically
by each word.
'''
# splitting string by spaces
my_string_list = str.split(my_string)
# initialzing variable as empty string to add the sorted words to
my_string_sorted = ''
# looping through each word in the string
for x in range(0, len(my_string_list)):
# resetting word to sorted word
my_string_list[x] = sorted(my_string_list[x])
# adding sorted word to new string
if x != len(my_string_list):
# only adding trailing space if not the last word in the string
my_string_sorted += (''.join(my_string_list[x]) + ' ')
else:
# does not add trailing space because last word in the string
my_string_sorted += (''.join(my_string_list[x]))
return my_string_sorted | true |
e8004ef41a316324731cc23854912343acdda8d9 | HanBao224/code_sample | /code_sample/data-cleansing-sample/dir_to_file.py | 2,711 | 4.125 | 4 |
import os
def dir_to_file(dir, file="dir.txt"):
""" Find the files and directories in 'dir', remove hidden files,
also get the files at the next level, and put everything
into 'file' with this format:
Contents of dir
f1
f2
D: d1
f1
f2
D: d2
f1
"""
# Check input
if not isinstance(dir, str):
raise TypeError("dir is not a string")
if not isinstance(file, str):
raise TypeError("file_name is not a string")
if not os.path.isdir(dir):
raise TypeError("dir is not a directory")
try:
sub = os.listdir(path=dir)
except FileNotFoundError:
return -1
dir_list = []
file_list = []
# Get level 1 files and directories and drop hidden files
for file_name in sub:
if file_name[0:1] == '.':
try:
os.remove(os.path.join(dir, file_name))
except FileExistsError:
return -2
elif os.path.isdir(os.path.join(dir, file_name)):
dir_list.append(file_name)
else:
file_list.append(file_name)
# Initialize output text
try:
with open(file, "r") as my_file:
text = my_file.read()
if text is None:
print("no content exists")
else: # overload file
my_file.truncate()
except PermissionError:
print("Permission error")
except FileNotFoundError:
print("File Not Found")
except UnicodeDecodeError:
print("Unicode Error")
# Helper to put filenames into a str, optionally indenting
# Input is a list of file names, their path, and an indent switch
# Add level 1 files to output text
# Get directories at level 1
# Add directory and files for each level 1 directory
level2_file = [os.listdir(path=dir+dir_name) for dir_name in dir_list]
# Write to file
try:
with open(file, "w") as my_file:
for file_name in file_list:
my_file.write("\n".join(file_name))
for i, dir_name in enumerate(dir_list):
my_file.write("\n".join(dir_name))
for sub_file_name in level2_file[i]:
my_file.write("\n".join(" ").join(sub_file_name))
except PermissionError:
print("Permission error")
except FileNotFoundError:
print("File Not Found")
except IOError:
print("Unicode Error")
return None
if __name__ == "__main__":
dir_to_file("")
| true |
dde0477c5129a5a37fc7136e36ffaec4c897360a | MohammedHmmam/Python_a-z | /lists/map_function.py | 1,266 | 4.5 | 4 | #The map() Function executes a specified for each item in an iterable.
##The item is sent to the function as a parameters
#### Syntax: map(Function , iterable)
############# Parameters :
############################# Function: Required|| - The function to execute for each item
############################# Iterable: Required|| - A sequence, collection or an iterable
###################################################-> You can send as many iterables as like, just make the function
###################################################=> has one parameter for each iterable.
#Example 1
"""
def myFanc(a,b):
return a+b
x = map(myFanc , ('Apple' , 'Banana' , 'Cherry') , ('Orange' , 'lemon' , 'Tex'))
print(list(x))
"""
#------------------------------------------------------------#
#-------------------------------------------------------------#
""" ---------------------------------------------------- """
#Example 2
""" Consider a situation in which you need to calculate the price after tax for a list of transaction """
txns = [1.09, 23.56, 57.84, 4.56, 6.78]
TAX_RATE = .08
def get_prices_with_tax(txn):
return txn * (1 + TAX_RATE)
final_prices = map(get_prices_with_tax , txns)
print(list(final_prices))
| true |
cb5cefb219b9ca70489678e164e45ac1c4258f7e | Levijom/nth_Digit_of_PI | /nth_Digit_of_PI.py | 611 | 4.21875 | 4 |
import math
#find the nth digit of PI
userInput = int(input("what digit of PI would you like?: "))
if userInput <= 0:
print("You must input a value larger than 0!")
#get the nth value to one's place, convert to int
digit = userInput - 1
power = 10 ** digit
digit = math.pi * power
integer = int(digit)
#calculates preceeding digits of PI excluding one's place
preceeding = digit/10
preInt = int(preceeding)
preIntTen = (preInt * 10)
#gives the final value
finalValue = integer - preIntTen
#print(digit)
#print(integer)
#print(preIntTen)
print(finalValue)
| true |
337d1156a06f5202b51579a0defeb4c1b6bb6ad3 | Anurag-Bharati/pythonProjectLab | /First.py | 1,476 | 4.25 | 4 | # Program to convert Binary to Decimal or vice versa
import keyboard
print("\nPress 'b' to convert decimal number into binary, 'd' to convert binary to decimal or 'e' to exit.\n")
while True:
if keyboard.is_pressed("b"):
keyboard.send("backspace")
print("\nDecimal to binary\n")
keyboard.send("backspace")
a = (input("Enter decimal no: "))
b = bin(int(a))
print("\n", a, "in binary is ", b[2:])
print("\nPress 'b' to convert decimal number into binary, 'd' to convert binary to decimal or 'e' to exit.\n")
elif keyboard.is_pressed("d"):
keyboard.send("backspace")
print("\nBinary to Decimal\n")
keyboard.send("backspace")
a = input("Enter binary no: ")
still_testing = True
while still_testing:
if len(a):
still_testing = False
for (num) in a:
if int(num) not in [0, 1]:
print("Invalid input for", num)
a = input()
still_testing = True
while not still_testing:
print(f"\n {a} in decimal is ", int(a, 2))
print("\nPress 'b' to convert decimal number into binary, 'd' to convert binary to decimal or 'e' to exit."
" \n")
still_testing = True
elif keyboard.is_pressed("e"):
print("\n\nNow Exiting...")
keyboard.send("ctrl+F2")
break
| true |
d1622fc0447894b03a0e125dfb7a695304fb5bfa | VijayUpadhyay/python | /PythonBasics/com/vijay/basics/GeekForGeeks/ClosureTest1.py | 391 | 4.1875 | 4 | #As we can see innerFunction() can easily be accessed inside the outerFunction body
#but not outside of it’s body. Hence, here, innerFunction() is treated as nested
#Function which uses text as non-local variable.
def outerFunction(text):
custName = text
def innerFunction():
print(custName)
innerFunction()
if __name__ == '__main__':
outerFunction('Ram!') | true |
58e4039bc04d16727bebc574ccbec57f98e2a8c6 | VijayUpadhyay/python | /PythonBasics/com/vijay/basics/GeekForGeeks/ItrTest3.py | 539 | 4.15625 | 4 | import itertools
from collections import Counter
list1 = [1, 2, 3, 4, 5, 6, 44]
list2 = [44, 55, 77, 55, 68, 88]
list3 = [44, 77, 854, 545, 8, 89]
print("Summation of 1st list: ", list(itertools.accumulate(list1)))
print("Summation of 2nd list: ", list(itertools.accumulate(list2)))
print("Summation of 3rd list: ", list(itertools.accumulate(list3)))
print("Chain of lists is: ", list(itertools.chain(list1, list2, list3)))
finalList = list(itertools.chain(list1, list2, list3))
print("finalList after counter impl: ", Counter(finalList))
| true |
ed6f77bd9d80c0279fb339215ee6f1c008a0885a | MananKavi/assignment | /src/assignment2/que6.py | 881 | 4.125 | 4 | # Program to display grade
bigData = int(input("Enter marks of Big Data out of 100 : "))
dataMining = int(input("Enter marks of Data Mining out of 100 : "))
python = int(input("Enter marks of Python out of 100 : "))
java = int(input("Enter marks of Java out of 100 : "))
computerGraphics = int(input("Enter marks of Computer Graphics out of 100 : "))
percentage = ((bigData + dataMining + python + java + computerGraphics) * 100) / 500
if percentage > 90:
print("Your Grade is A+")
elif 80 < percentage <= 90:
print("Your Grade is A")
elif 70 < percentage <= 80:
print("Your Grade is B+")
elif 60 < percentage <= 70:
print("Your Grade is B")
elif 50 < percentage <= 60:
print("Your Grade is C+")
elif 40 < percentage <= 50:
print("Your Grade is C")
elif 33 < percentage <= 40:
print("Your Grade is D")
else:
print("Your Failed!!!")
| false |
5e73e6155f45815605950c6411eb592aa1863347 | Joes-BitGit/LearnPython | /DataStructs_Algos/list_based/stacks.py | 1,638 | 4.21875 | 4 | class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
"""
Linked list class is used to hold elements but will act as a stack.
Which means it will delete and insert only from the top of the Stack
"""
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
# Inserting
# Step 1 make the new_element.next point to where head is pointing to
# Step 2 make the head point to the new_element
# Step 1 assign head to new_element.next
new_element.next = self.head
# Step 2 assign the new_element to head
self.head = new_element
def delete_first(self):
# Deleting
# Step 1 Check if the LinkedList exists
# Step 2 Assign the new head value to be the next node
to_delete = self.head
if self.head:
self.head = self.head.next
to_delete.next = None
return to_delete
class Stack(object):
"""
Stack is a lifo data structure
Access: O(N)
Insertion: O(1)
Deletion: O(1)
Search: O(N)
Space: O(N)
"""
def __init__(self, top=None):
self.ll = LinkedList(top)
def push(self, new_element):
self.ll.insert_first(new_element)
def pop(self):
return self.ll.delete_first()
| true |
1e08a1107ea947c001972670f2a7d8a1d24901ff | mikewarren02/PythonReview | /palindrome.py | 518 | 4.375 | 4 | def palindrome():
word = str(input("Pick a word: "))
reverse = word[::-1]
if word == reverse:
print(f"{word} is a Palindrome!")
else:
print(f"{word} is Not a Palindrome!")
# palindrome()
#another way
# word = input("Please enter word: ")
# reversed_word = ""
# for index in range(len(word) -1,-1,-1):
# #reversed_word = reversed_word + word[index]
# reversed_word += word[index]
# if word == reversed_word:
# print("PALINDROME")
# else:
# print("Not a palindrome")
| false |
253602612d0e10cfa6c1af5e39ea8b3c7af46b5b | mikewarren02/PythonReview | /strings.py | 671 | 4.21875 | 4 | # Data types in Python
print("Hello World")
company = "digitalCrafts"
cohort = "Feb 2021"
message = f"Welcome to {company} and cohort is {cohort}"
print(message)
full_name = input("Please ener your full name: ")
car_make = input("Please ener your car make: ")
car_model = input("Please ener your car model: ")
address = input("Please ener your full address: ")
print(full_name)
print(car_make)
print(car_model)
print(address)
information = f"Hello, My name is {full_name}, I have a {car_make} {car_model}, Im currently at {address} "
first_name = "Michael"
last_name = "Warren"
greeting = f"Hello, My name is {first_name}, {last_name} "
print(information)
| true |
76b5f30ed149e32b4435d8859678e1355a3eb3b2 | EmanuelGP/pythonScripts | /dataStructuresAlgorithms/poo/pooEjemplo6/claseSequence.py | 974 | 4.125 | 4 | from abc import ABCMeta, abstractmethod
class Sequence(metaclass=ABCMeta):
"""Our own version collections.Sequence abstrac base class."""
@abstractmethod
def __len__(self):
"""Return the length of the sequence."""
@abstractmethod
def __getitem__(self, j):
"""Return the element at index j of the sequence."""
def __contains__(self, val):
"""Return True if val found in the sequence; False otherwise."""
for j in range(len(self)):
if self[j] == val: # found match
return True
return False
def index(self, val):
"""Return leftmost index at wich val is found (or raise ValueError)."""
for j in range(len(self)):
if self[j] == val: # leftmost match
return j
raise ValueError("value not in sequence") # never found a match
def count(self, val):
"""Return the number of elements equal to given value"""
k = 0
for j in range(len(self)):
if self[j] == val: # found a match
k += 1
return k | true |
df52733153c04a2aebf6b3d74e5056d3d15062c2 | billputer/project-euler | /problem9.py | 870 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
import math
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
def is_pythagorean_triplet(a, b, c):
return math.pow(a, 2) + math.pow(b, 2) == math.pow(c, 2)
def get_triplets(n):
""""Return all triplets of natural numbers that add up to n"""
for x in range(1, n / 3):
for y in range(x + 1, int((n - x) / 2 + 1)):
for z in range(y + 1, n - x - y + 1):
if x + y + z == n:
yield x, y, z
# (3,4,5) is a triplet of 12
assert((3,4,5) in get_triplets(12))
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
for trip in get_triplets(1000):
a, b, c = trip
if(is_pythagorean_triplet(a,b,c)):
print a * b * c
| false |
2532033dbec188409ffa1434369c059414268151 | justanotheratom/Algorithms | /Python/DynamicProgramming/Fibonacci/Staircase/staircase_bottomup.py | 567 | 4.375 | 4 |
def countways(n):
'''
Given a staircase with n steps, find the number of was you can climb it
by taking 1 step, 2 steps, or 3 steps at each turn.
:param n: Number of steps in the staircase
:return: Number of possible ways.
>>> countways(0)
1
>>> countways(1)
1
>>> countways(2)
2
>>> countways(3)
4
>>> countways(4)
7
>>> countways(5)
13
>>> countways(6)
24
'''
# TODO : Implement bottom-up table based solution
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
308c1b45a02cda333a5e053f23e101132bd398f3 | charleenchy/Task3 | /Question2.py | 392 | 4.25 | 4 | #Write a Python program to convert temperatures to and from celsius, fahrenheit
ans=int(input("1 for cel to Fah, 2 for Fah to cel"))
If ans == 1:
cel = int(input("enter a temp in cel"))
fah = (cel - 9/5) + 32
print('%.2f Celsius is: %.2f Fahrenheit' %(cel, fah))
else:
fah = int(input("yourtemp in Fah"))
cel = (fah - 32) * 5/9
print('%.2f Fahrenheit is: %.2f Celsius' %(fah, cel))
| false |
120826e3f3a0455de2ca9b6ba33ea664a949a86a | overnightover/git-test | /src/py/f05.py | 638 | 4.15625 | 4 | # 水仙花数是指一个 n 位数,它的每个位上的数字的 n 次幂之和等于它本身。例如:1^3 + 5^3 + 3^3 = 153。
# 在Python中,我们可以使用一个简单的循环来找出所有的水仙花数。以下是一个示例代码:
for num in range(100, 1000):
# 将数字转换为字符串,方便获取每一位数字和位数
str_num = str(num)
n = len(str_num)
# 计算每一位数字的n次幂之和
sum_of_powers = sum(int(digit) ** n for digit in str_num)
# 如果这个和等于原来的数字,那么这个数字就是水仙花数
if sum_of_powers == num:
print(num)
| false |
9c15808f00f1964de2dfc605b3e106a0ed6b56af | jmwoloso/Python_2 | /Lesson 8 - GUI Layout/grdspan.py | 1,603 | 4.125 | 4 | #!/usr/bin/python3
#
# A Program Demonstrating the 'rowspan' and 'columnspan' Keywords
# for the grid() Method Geometry Manager in Tkinter
#
# Created by: Jason Wolosonovich
# 03-11-2015
#
# Lesson 8 - Exercise 3
"""
Demonstrates the 'rowspan' and 'columnspan' keywords of the
Geometry Manager for the grid() method.
"""
from tkinter import *
ALL = N+S+W+E
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.rowconfigure(0,
weight=1)
self.master.columnconfigure(0,
weight=1)
self.grid(sticky=ALL)
for r in range(5):
self.rowconfigure(r,
weight=1)
Button(self,
text="Row {0}".format(r)).grid(row=r,
column=0,
sticky=ALL)
self.rowconfigure(5,
weight=1)
for c in range(5):
self.columnconfigure(c,
weight=1)
Button(self,
text="Col {0}".format(c)).grid(row=5,
column=c,
sticky=ALL)
f = Frame(self,
bg="red")
f.grid(row=2,
column=1,
rowspan=3,
columnspan=2,
sticky=ALL)
root = Tk()
app = Application(master=root)
app.mainloop()
| true |
a81209dbff0df01c8f4324bcb93d0a917abb24a6 | jmwoloso/Python_2 | /Lesson 3 - TDD/adder.py | 521 | 4.34375 | 4 | #!/usr/bin/python3
#
# Lesson 3 Exercise 1 Adder Module
# adder.py
#
# Created by: Jason Wolosonovich
# 02-20-2015
#
# Lesson 3, Exercise 1
"""adder.py: defines an adder function according to a slightly
unusual definition."""
import numbers
def adder(x, y):
if isinstance(x, list) and not isinstance(y, list):
return x + [y]
elif isinstance(y, list) and not isinstance(x, list):
return y + [x]
elif isinstance(x, numbers.Number) and isinstance(y, str):
return str(x) + y
return x + y | true |
be3e61e14026462d2014682dc71d6d511610f628 | jmwoloso/Python_2 | /Lesson 11 - Database Hints/animal.py | 1,910 | 4.21875 | 4 | #!/usr/bin/python3
#
# A Program That Uses a Class to Represent an Animal in the Database
# animal.py
#
# Created by: Jason Wolosonovich
# 03-20-2015
#
# Lesson 11 - Exercise 2
"""
animal.py: a class to represent an animal in the database
"""
class Animal:
def __init__(self, id, name, family, weight):
self.id = id
self.name = name
self.family = family
self.weight = weight
def __repr__(self):
return "Animal({0}, '{1}', '{2}', {3})".format(self.id,
self.name,
self.family,
self.weight)
### ALTERNATE VERSION ###
# the code below selects the fields from within the actual format rather than
# having to pass along a list of the variables to the format function
# the '!r' syntax tells the interpreter to substitute the objects repr()
# representation (that's why strings will be displayed with quotation
# marks around them, even though none appear in the format
# return "Animal({0.id!r}, {0.name!r}, {0.family!r}, {0.weight!r})".format(self)
if __name__=="__main__":
import mysql.connector
from database import login_info
db = mysql.connector.Connect(**login_info)
cursor = db.cursor()
cursor.execute("""SELECT id, name, family, weight
FROM animal""")
animals = [Animal(*row)
for row in cursor.fetchall()]
from pprint import pprint
pprint(animals)
### Tailored Class ###
"""A function that returns a tailored class"""
# RC = RecordClass("animal", "id name family weight"))
"""Create instances of the class by calling the function with
values for each of the named columns."""
# for row in cursor.fetchall():row_record = RC(*row)) | true |
19dd21f1ee8babc06d3b444dfdbb06fdee9480e5 | philipslan/programmingforfun | /2_basicds/queuelist.py | 567 | 4.34375 | 4 | # Implement the Queue ADT, using a list such that the rear of the queue
# is at the end of the list.
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.append(item)
print self.items
def dequeue(self):
a= self.items[0]
del self.items[0]
print self.items
return a
def size(self):
return len(self.items)
queue= Queue()
queue.enqueue(4)
queue.enqueue(7)
queue.enqueue(3)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print queue.dequeue()
print queue.isEmpty() | true |
c70f0169560febece4f7f18e8c57ecc9055e073a | PeterELytle/LTCTHW-Python | /ex18.py | 1,328 | 4.28125 | 4 | # This line defines the "print_two" function, and it will have arguments.
def print_two(*args):
# This line defines two arguments to be used in the function.
arg1, arg2 = args
# This line displays some text, and both variables (which are defined as the function arguments).
print "arg1: %r, arg2: %r" % (arg1, arg2)
# This line defines the "print_two_again" function, and it will have two arguments, named arg1 and arg2.
def print_two_again(arg1, arg2):
# This line displays some text, and both variables (which are defined as the function arguments).
print "arg1: %r, arg2: %r" % (arg1, arg2)
# This line defines the "print_one" function, and it will have a single argument.
def print_one(arg1):
# This line displays some text, and the variable (which is defined as the function argument).
print "arg1: %r" % arg1
# This line defines the "print_none" argument. It has no arguments.
def print_none():
# This line displays some text.
print "I got nothin'."
# This line calls the "print_two" function, and defines its arguments.
print_two("Peter","Lytle")
# This line calls the "print_two_again" function, and defines its arguments.
print_two_again("John","Doe")
# This line calls the "print_one" function, and defines its argument.
print_one("First!")
# This line calls the "print_none" argument.
print_none()
| true |
4198371c811f2f7eab2395c816dae90267f43c9c | PeterELytle/LTCTHW-Python | /ex3.py | 1,621 | 4.4375 | 4 | print "I will now count my chickens:"
# This line displays some text describing what the next lines will do.
print "Hens", 25.00 + 30.00 / 6.00
# This line displays a descriptor and the result of an arithmetic equation.
print "Roosters", 100.00 - 25.00 * 3.00 % 4.00
# This line displays a descriptor and the result of an arithmetic equation.
print "Now I will count the eggs:"
# This line displays some text describing what the next lines will do.
print 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 + 6.00
# This line displays the result of an arithmetic equation.
print "Is it true that 3 + 2 < 5 - 7?"
# This line displays some text describing what the next lines will do.
print 3.00 + 2.00 < 5.00 - 7.00
# This line displays the result of an arithmetic equation as a true or false statement.
print "What is 3 + 2?", 3.00 + 2.00
# This line displays some text and the result of an arithmetic equation.
print "What is 5 - 7?", 5.00 - 7.00
# This line displays some text and the result of an arithmetic equation.
print "Oh, that's why its false."
# This line displays some text.
print "How about some more?"
# This line displays some text describing what the next lines will do.
print "Is it greater?", 5 > -2
# This line displays some text, and the result of an arithmetic equation as a true or false statement.
print "Is it greater or equal?", 5 >= -2
# This line displays some text, and the result of an arithmetic equation as a true or false statement.
print "Is it less or equal?", 5 <= -2
# This line displays some text, and the result of an arithmetic equation as a true or false statement.
| true |
af47e372315456ee4ec7b3d2f1875404c3e66ce1 | Hallad35/Development | /5.py | 735 | 4.25 | 4 | name=input('please, give me your name ')
surname=input('please, give me your surname')
telnumber=input('please, give me your telephone number')
print("Czy imię składa się tylko z liter?", name.isalnum())
print("Czy nazwisko składa się tylko z liter?", surname.isalnum())
print("Czy numer telefonu składa się z cyfr", telnumber.isdigit())
name=name.capitalize()
surname=surname.capitalize() #pierwsza litera ciagu z duzej
telnumber=telnumber.replace(' ','').replace('-', '') #najpierw zamienia spacje na puste a potem myslnik na puste
print(name, surname)
print(telnumber)
print('jest to imie kobiece', name.endswith('a'))
personal=name+' '+surname+' '+telnumber
print(personal)
print(len(personal))
print(len(name+surname)) | false |
da90149afebf3c0afc560a90b3c7583ede002ba3 | nordhagen/cs | /python/3-lists.py | 1,358 | 4.3125 | 4 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print bicycles
# Python has string operation functions like .title() for title casing.
print bicycles[0].title()
# Negative array access will count from the end
print bicycles[-1]
message = 'My first bicycle was a '+ bicycles[0].title() + '.'
print message
motorcycles = ['honda', 'yamaha', 'suzuki']
print motorcycles
# Array elements can be edited in place, just like JS
motorcycles[0] = 'ducati'
print motorcycles
# append() is like push() in JS
motorcycles.append('honda')
print motorcycles
# Unlike JS, Python has an dedicated insert method
motorcycles.insert(1, 'bmw')
print motorcycles
# Deleting items in an array uses the del keyword
del motorcycles[2]
print motorcycles
# pop() just like JS
print motorcycles.pop()
print motorcycles
# Almost, in Python you can pop at any index
print motorcycles.pop(1)
print motorcycles
# Remove by value (stops searching after first match)
motorcycles.remove('ducati')
print motorcycles
cars = ['bmw', 'audi', 'toyota', 'subaru']
# Sorting in-place
cars.sort()
print cars
# Sorting in reverse order
cars.sort(reverse=True)
print cars
# Use sorted() to return a copy instead of sorting in-place like sort()
print sorted(cars)
# Reversing
print cars
cars.reverse()
print cars
# Counting array length
print str(len(cars)) + ' cars in list' | true |
efd841d774d8cdb7ccfe887fb158d3432ccfa0b1 | chintaluri/Coding-Exercises | /p-prac-ex1.py | 892 | 4.1875 | 4 | # Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Extras:
#
# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.
# (Hint: order of operations exists in Python)
# Print out that many copies of the previous message on separate lines.
# (Hint: the string "\n is the same as pressing the ENTER button)
name = input('Please give me your name! ')
age = int(input('Please give me your age '))
calcul = str(2019-(100-age))
another_number = int(input('How many times would you like the above statement to be printed? '))
print(('Hello'+ name +' you will be 100 years old in the year' + calcul + '\n')*another_number)
| true |
deb01bf8f07f75fd93feb197f5bdaf5a7aa3db16 | adityakaria/3-Sem | /py/labs/lab3/mystack.py | 865 | 4.3125 | 4 | class Stack:
"""Define the Stack class here.
Write a constructor and implement the push, pop and isEmpty functions
using Python lists.
"""
def __init__(self):
self.my_stack = []
self.top = -1
def push(self, x):
self.my_stack.append(x)
self.top += 1
print ("Push Successful\nThe stack now is: " + str(self.my_stack))
def pop(self):
popped = self.my_stack[self.top]
self.my_stack.pop(self.top)
self.top -= 1
print("Popped", popped, "\nThe stack is now: ", self.my_stack)
return popped
def isEmpty(self):
if (len(self.my_stack) == 0):
return True
else:
return False
def peek(self):
print("The top element is: ", self.my_stack[self.top])
return self.my_stack[self.top]
def main():
s = Stack()
s.push(1)
s.push(9)
s.push(69)
s.pop()
s.peek()
print("isEmpty: ", s.isEmpty())
if __name__ == "__main__":
main() | true |
a08ace17e89a52ed82d2467cb7dea5823fac6923 | RansomBroker/self-python | /Recursive/binarySearchTree.py | 1,101 | 4.15625 | 4 | class Node:
#make constructor for insert data
def __init__(self, key):
self.left = None
self.right = None
self.value = key
#insert item based on root
def insertTree(self, root, node):
if root is None:
root = node
else:
#insert value to right
if root.value < node.value:
if root.right is None:
root.right = node
else:
self.insertTree(root.right, node)
if root.value > node.value:
if root.left is None:
root.left = node
else:
self.insertTree(root.left, node)
# will print tree
def tree(self, root):
if root:
self.tree(root.left)
print(root.value)
self.tree(root.right)
root = Node(40)
root.insertTree(root, Node(10))
root.insertTree(root, Node(15))
root.insertTree(root, Node(9))
root.insertTree(root, Node(6))
root.insertTree(root, Node(24))
root.insertTree(root, Node(32))
root.tree(root) | true |
36be5969915f5f20c67366462148ba4e34d2528b | marlavous/intro-to-programming-class | /listproject.py | 1,792 | 4.4375 | 4 | master_list = {"Target": ["socks", "soap", "detergent", "sponges"], "Safeway": ["butter", "cake", "cookies", "bread"]}
test_list = ["apples", "wine", "cheese"]
def main_menu():
print "Select one"
print "0 - Main Menu"
print "1 - Show all lists."
print "2 - Show a specific list."
print "3 - Add a new shopping list for a specific store."
print "4 - Add an item to shopping list."
print "5 - Remove an item from a shopping list."
print "6 - Remove a list by name."
print "7 - Exit"
choice = int(raw_input())
return choice
def display_lists():
return master_list
def specific_list():
specific = raw_input("which store list would you like to see?")
print master_list[specific]
def new_list():
store = raw_input("what store is this list for?")
master_list[store] = []
def delete_list():
store = raw_input("what store's list do you want to remove?")
del master_list[store]
# def alphabetize():
# master_list.sort()
# return master_list
def add_item():
# item = item.lower()
store = raw_input("which store list would you like to add the item to?")
if store in master_list:
item = raw_input("What would you like to add?")
master_list[store].append(item)
else:
print "you do not have a list for that store"
def remove_item():
pass
def check_repeat():
pass
def main():
while(True):
choice = main_menu()
if choice == 1:
# alphabetize()
print display_lists()
elif choice == 2:
print specific_list()
elif choice == 3:
print new_list()
#put add_item function here automatically (so they can add items right after creating a store list)
elif choice == 4:
add_item()
elif choice == 5:
remove_item()
elif choice == 6:
delete_list()
elif choice == 7:
break
else:
return
if __name__ == '__main__':
main() | true |
d05b00a2b2b153f4c3908047c55b0c432dff4c08 | aguecig/Project-Euler | /Problems 11 - 20/pe_15.py | 1,456 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 17:42:18 2019
@author: aguec
"""
def pascal_middle(n):
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# 1 5 10 10 5 1
# 1 6 15 20 15 6 1
# 1----1---1---1---1---1
# | | | | | | we can see the relationship b/w pascal's
# 1---2---3---4---5---6- triangle and the grid movements
# | | | | | |
# 1---3---6---10------- every corner is the middle entry in the
# | | | | | | 2^n row of the triangle
# 1---4---10--20-------
# | | | | | | thus if we can write a program for the
# 1-------------------- triangle, we access that value for the
# | | | | | | nxn grid to see how many ways we can
# 1--------------------- complete it.
pascal = [[1],[1,1]]
for i in range(2,n):
row =[1]
for j in range(i-1):
row.append(pascal[i-1][j]+pascal[i-1][j+1])
row.append(1)
pascal.append(row)
# for an nxn grid, we want the mimddle entry of the 2*n row
# the middle entry is the n/2 position in that row
# set n >= 41 to get the correct result for the 20x20 grid:
print(pascal[40][20]) | false |
4fa482193c3c69a6f7fdb43d7a936bb34ebc12f3 | osiddiquee/SP2018-Python220-Accelerated | /Student/osiddiquee/lesson09/Acitivity09.py | 1,824 | 4.125 | 4 | '''
Notes for concurrency and async
'''
import sys
import threading
import time
from Queue import Queue
'''
This is an intengration function
def f(x):
'''
return x**2
def integrate(f, a, b, N):
s = 0
dx = (b-a)/N
for i in xrange(N):
s += f(a+i*dx)
return s * dx
'''
This starts threading
'''
def func():
for i in xrange(5):
print("hello from thread %s" % threading.current_thread().name)
time.sleep(1)
threads = []
for i in xrange(3):
thread = threading.Thread(target=func, args=())
thread.start()
threads.append(thread)
'''
This is an example of subclassing
'''
class MyThread(threading.Thread):
def run(self):
print("hello from %s" % threading.current_thread().name)
thread = MyThread()
thread.start()
'''
Mutex locks (threading.Lock)
Probably most common
Only one thread can modify shared data at any given time
Thread determines when unlocked
Must put lock/unlock around critical code in ALL threads
Difficult to manage
Easiest with context manager:
'''
x = 0
x_lock = threading.Lock()
# Example critical section
with x_lock:
# statements using x
'''
Locking threads
'''
lock = threading.Lock()
def f():
lock.acquire()
print("%s got lock" % threading.current_thread().name)
time.sleep(1)
lock.release()
threading.Thread(target=f).start()
threading.Thread(target=f).start()
threading.Thread(target=f).start()
'''
This is a nonblocking locks
'''
lock = threading.Lock()
lock.acquire()
if not lock.acquire(False):
print("couldn't get lock")
lock.release()
if lock.acquire(False):
print("got lock")
'''
Queueing
'''
#from Queue import Queue
q = Queue(maxsize=10)
q.put(37337)
block = True
timeout = 2
print(q.get(block, timeout))
| true |
615773162eb00f0f6052e5165174a3085d5e40b1 | Bdnicholson/Python-Projects | /Imperial-To-Metric/Bora_Nicholson_Lab3a.py | 1,311 | 4.25 | 4 | print('Hello, Please input the Imperial values!')
#Miles
Miles = float(input('Miles to Kilometers: '))
totalKilometers = (1.6 * Miles)
if Miles < 0:
print('Please no negative numbers')
else:
if Miles > 0:
print("The metric conversion is ", totalKilometers)
#Fahrenheit
Fahrenheit = float(input('Fahrenheit to Celsius: '))
totalCelcius = ((Fahrenheit - 32) * 5/9 )
if Fahrenheit < 0 or Fahrenheit > 1000:
print('Please check your Fahrenheit number, It must be greater than 0 and less than 1000')
else:
if Fahrenheit > 0 or Fahrenheit < 1000:
print("The metric conversion is ", totalCelcius)
#Gallons
Gallons = float(input('Gallons to Liters: '))
totalLiters = (3.9 * Gallons)
if Gallons < 0:
print('Please no negative numbers')
else:
if Gallons > 0:
print("The metric conversion is ", totalLiters)
#Pounds
Pounds = float(input('Pounds to Kilograms: '))
totalKilograms = (.45 * Pounds)
if Pounds < 0:
print('Please no negative numbers')
else:
if Pounds > 0:
print("The metric conversion is ", totalKilograms)
#Inches
Inches = float(input('Inches to Cenitmeters: '))
totalCentimeters = (2.54 * Inches)
if Inches < 0:
print('Please no negative numbers')
else:
if Inches > 0:
print("The metric conversion is ", totalCentimeters)
| true |
6f2ff90aa2e66dd4eb578b26ee00ed4b84c4a9ec | YabZhang/algo | /kth_largest_element.py | 1,080 | 4.15625 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
@Author: yabin
@Date: 2017.5.21
Find K-th largest element in an array.
Example
In array [9,3,2,4,8], the 3rd largest element is 4.
In array [1,2,3,4,5], the 1st largest element is 5,
2nd largest element is 4, 3rd largest element is 3 and etc.
Note
You can swap elements in the array
Challenge
O(n) time, O(1) extra memory.
摘录来自: yuanbin. “Data Structure and Algorithm notes”。 iBooks.
"""
def solution(s, k):
if len(s) < k:
return -1
return helper(s, 0, len(s) - 1, k)
def helper(s, l, u, k):
m = l
for i in range(l + 1, u + 1):
if s[i] > s[l]:
m += 1
s[i], s[m] = s[m], s[i]
s[l], s[m] = s[m], s[l]
if k == m - l + 1:
return s[m]
elif k < m - l + 1:
return helper(s, l, m - 1, k)
else:
return helper(s, m + 1, u, k - (m - l + 1))
if __name__ == '__main__':
s = [9, 3, 2, 4, 8]
print(solution(s, 3))
s = [1, 2, 3, 4, 5]
print(solution(s, 1))
print(solution(s, 2))
print(solution(s, 3))
| false |
703a54f231c85e320e10950ed1c7403daa6a6d09 | YabZhang/algo | /remove_element.py | 798 | 4.15625 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
@Author: yabin
@Date: 2017.5.20
“Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
Example
Given an array [0,4,4,0,0,2,4,4], value=4
return 4 and front four elements of the array is [0,0,0,2]”
摘录来自: yuanbin. “Data Structure and Algorithm notes”。 iBooks.
"""
def remove_element(alist, val):
n = len(alist)
i = 0
while(i < n - 1):
if alist[i] == val:
alist[i] = alist[n - 1]
n -= 1
i -= 1
i += 1
return n
if __name__ == '__main__':
s = [0, 4, 4, 0, 0, 2, 4, 4]
r = remove_element(s, 4)
print('result: ', r)
| true |
745304d06b6afc863d2b76b498f0370f6d05cff2 | JARVVVIS/ds-algo-python | /sorting_algo/rec_bubble.py | 674 | 4.21875 | 4 | ## just for fun things
def rec_bubble(arr):
## bring the largest element to the last
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
## now call the function on last-1 elements
## we are basically passing the same array
## and calling the recursion stack n times
## same as loop
rec_bubble(arr)
def main():
print('Enter elements: ')
arr = [int(x) for x in input().split()]
rec_bubble(arr)
## print the sorted array
print('Sorted array: {}'.format(arr))
if __name__ == '__main__':
main() | true |
38057ac597ef329b7afc371c8cc7b9225d0072fb | reesep/reesep.github.io | /classes/summer2021/127/lectures/examples/calculator.txt | 1,186 | 4.21875 | 4 |
# Write a calculator program that will ask for
# two numbers from the user. The program
# should then as the user what operation they
# want to do (addition, subtraction,
# multiplication, division). The program
# should then do the requested operation and
# print out the answer.
def addition(num1, num2):
return num1 + num2
def subtraction(num1, num2):
return num1 - num2
def multiplication(num1, num2):
return num1 * num2
def division(num1, num2):
return num1 / num2
def main():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
operation = input("What would you like to do? (Addition, Subtraction, Multiplication, Division: ")
#update string to only lowercase letters
operation = operation.lower()
if(operation == "addition"):
answer = addition(num1,num2)
print(answer)
if(operation == "subtraction"):
answer = subtraction(num1,num2)
print(answer)
if(operation == "multiplication"):
answer = multiplication(num1,num2)
print(answer)
if(operation == "division"):
answer = division(num1,num2)
print(answer)
main()
| true |
0c7cf800ec9927506315dfdac8ce5c83fe3f560b | reesep/reesep.github.io | /classes/snowmester2020/127/lectures/examples/pizza_price.py | 343 | 4.3125 | 4 |
# Write a program that will calculate the cost per square inch of a
# circular pizza, given its diameter (inches) and price.
diameter = float(input("Enter diameter of pizza: "))
price = float(input("Enter price of pizza: "))
area = (3.14159) * (diameter / 2) ** 2
ppsi = price / area
print("The price per square inch is:" + str(ppsi))
| true |
9613d7aff69a1ece0a9da7c99c3a0063d11d6866 | OmgMrRobot/XLAM | /X or 0.py | 867 | 4.125 | 4 |
board = [" "," "," "," "," "," "," "," "," ",]
def print_state(state):
for i,c in enumerate(state):
if (i+1)%3==0:
print(f'{c}')
else:
print(f'{c}|', end='')
print_state(board)
winnig_combination = [(0,1,2), (3,4,5),(6,7,8),(0,3,8),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def get_winner(state, combination):
for (x,y,z) in combination:
if state[x]==state[y] and state[y]==state[z] and (state[x]=="X" or state[x]=="O"):
return state[x]
return ''
def play_game(board):
current_sign ='X'
while get_winner(board,winnig_combination)=="":
index = int(input(f'Where do you want to draw {current_sign}'))
board[index] = current_sign
print_state(board)
winner_sign = get_winner(board,winnig_combination)
if winner_sign !='':
print(f'We have a winner:{winner_sign}')
current_sign = 'X' if current_sign =='O' else "O"
play_game(board) | false |
1a821d4a20223b0cd5ec519fbc91e062ae3582ed | andpet27/Python | /StringFormatting/StringsEx2.py | 716 | 4.28125 | 4 | string = "Strings are awesome!"
print("Lenghts of string = %d" % len(string))
print("The first occurence of letter a = %d" %string.index("a"))
print("a occures %d times" %string.count("a"))
print("the first five characters are '%s'" %string[:5])
print("the next five characters are '%s'" %string[5:10])
print("the 13th character is '%s'" %string[12])
print("the characters with odd index are '%s'" %string[1::2])
print("the last five charaters are '%s'" %string[-5:])
print(string.upper())
print(string.lower())
if string.startswith("Strings"):
print("Starts with Strings, bro")
if string.endswith("awesome!"):
print("Ends with awesome!, bro")
print("Split the words of the string: %s" %string.split(" ")) | true |
39525d30ac77a038f0277bcd6d39838b7df14912 | olugbengs12/pythonlearn | /classwork.py | 454 | 4.40625 | 4 | #program that takes count of numbers entered by a user and also notes the number, do a sum and return an average
total = 0
count = 0
average = 0
while True:
number = input("Enter a number:")
try:
if number == "done":
break
total += float(number)
count += 1
average = total / count
except:
print ("Invalid input")
print ("total:", total, "count:", count, "average:", average)
| true |
48f2ba2e155b451e7934815738bad75cb9123f58 | GenerationTRS80/JS_projects | /python_starter/tuples_sets.py | 912 | 4.3125 | 4 | # A Tuple is a collection which is ordered and >> unchangeable <<. Allows duplicate members.
# Create tuple
# You create a tuple using parenthese in stead brackets like lists
fruits = ('Appels', 'Grapes', 'Oranges')
#fruits2 = (('Apples','Grapes','Oranges'))
#Trailing value needs a single comma
fruits2 = ('Apple',)
#print(fruits[1])
#***Can't change value ###
# CAN'T assign value to an objects
# fruits[0] = 'Pears'
#Delete Tuple
del fruits2
print(len(fruits))
# A Set is a collection which is unordered and unindexed. No duplicate members.
#Creat Set {User curly braces for sets}
fruits_set = {'Apples','Oranges','Mango'}
#Check if in set
print('Apples' in fruits_set)
#Add to set
fruits_set.add('Grape')
print(fruits_set)
#Remove from set
fruits_set.remove('Oranges')
print(fruits_set)
#Clear the set
fruits_set.clear()
print(fruits_set)
#delete the set
del fruits_set
print(fruits_set) | true |
40d316229ad3450f817516625f950fa29d9af9df | srithanrudrangi/PythonCoding | /color.py | 224 | 4.15625 | 4 | color1 = input('Enter one primary color: ')
color2 = input('Enter another primary color: ')
if ((color1 == 'red' and color2 == 'blue') or (color1 == 'blue' and color2 == 'red')):
print('Your secondary color is Purple.')
| true |
2472673124d46f00d6f260fcf33d9c27205ac68a | srithanrudrangi/PythonCoding | /rectangle.py | 239 | 4.125 | 4 | length = int(input('What is the length of your rectangle? '))
width = int(input('What is the width of your rectangle? '))
area = length*width
perimeter = 2 * (length+width)
print('The perimeter is ', perimeter)
print('The area is ', area)
| true |
49ba51faa633d6244d4dfe8a176fe03c63d20ec8 | srithanrudrangi/PythonCoding | /4_5_averagerainfall.py | 546 | 4.21875 | 4 | numOfYears = int(input('How many years? '))
for i in range(numOfYears):
totalInchesOfrainfall = 0
currentMonth = 1
for currentMonth in range(1, 13):
inchesOfrainfall = int(
input('How many inches of rainfall for the month of ' + format(currentMonth, "d") + ': '))
totalInchesOfrainfall += inchesOfrainfall
print('The total inches of rainfall is: ',
totalInchesOfrainfall, ' inches')
average = totalInchesOfrainfall/12
print('The average amount of rainfall is: ', average, ' inches')
| true |
aa5625505ad49e331dbd94d844f553da327065b2 | dheerajgopi/Algorithmic-Thinking---Coursera | /Week1/project1.py | 1,418 | 4.25 | 4 | """Project 1 of Algorithmic Thinking MOOC"""
EX_GRAPH0 = {0:set([1,2]), 1:set([]), 2:set([])}
EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]),
4:set([1]), 5:set([2]), 6:set([])}
EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set([7]),
4:set([1]), 5:set([2]), 6:set([]), 7:set([3]),
8:set([1,2]), 9:set([0,3,4,5,6,7])}
def make_complete_graph(num_nodes):
"""Returns a complete graph for a given number of nodes"""
graph_out = {}
for node in xrange(num_nodes):
graph_out[node] = set([adj_node for adj_node in \
xrange(num_nodes) if adj_node != node])
return graph_out
def compute_in_degrees(digraph):
"""Returns distribution of in-degrees of nodes in a directed graph"""
in_degrees = {}
for node in digraph.keys(): # initializing the result dict with 0's
in_degrees[node] = 0
for node in digraph.keys():
for adj_node in digraph[node]:
in_degrees[adj_node] = in_degrees.setdefault(adj_node) + 1
return in_degrees
def in_degree_distribution(digraph):
"""Returns unnormalised distribution of in-degrees"""
in_degree_distr = {}
in_degrees = compute_in_degrees(digraph)
for node in in_degrees.keys():
in_degree = in_degrees[node]
in_degree_distr[in_degree] = in_degree_distr.get(in_degree, 0) + 1
return in_degree_distr
| false |
2ee3775ee7145d9f9483874807811f5dc29fb1b5 | david-assouline/personal-projects | /Sudoku Solver.py | 2,848 | 4.28125 | 4 | import time
board = [
[0,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def board_generator():
""" optional function. gives user the option to generate sudoku board through user input, row by
row, left to right. If this function is disabled, sudoku board values must be entered through
list variable 'board' """
global board
board = []
print("Enter all of the board's values going from left to right on a row by row basis, press enter"
" after each entry.\n""")
for _ in range(9):
temprow = []
for j in range(9):
x = (int(input("--> ")))
while x > 9:
print("You must enter a value between 0 and 9")
x = (int(input("--> ")))
else:
temprow.append(x)
board.append(temprow)
def print_board(board):
"""prints a semi-formatted version of the sudoku 3x3 board"""
for i in range(9):
if i % 3 == 0 and i != 0:
print("- " * 14)
for x in range(9):
if x % 3 == 0 and x != 0:
print(" | ", end="")
if x == 8:
print(board[i][x])
else:
print(str(board[i][x]) + " ", end="")
def isvalid(board, number, position):
# checks if row is valid
for i in range(9):
if board[position[0]][i] == number and position[1] != i:
return False
# checks if column is valid
for i in range(9):
if board[i][position[1]] == number and position[0] != i:
return False
# checks if box is valid
xbox = position[1] // 3
ybox = position[0] // 3
for i in range(ybox * 3, ybox * 3 + 3):
for x in range(xbox * 3, xbox * 3 + 3):
if board[i][x] == number and (i, x) != position:
return False
return True
def find_empty(board):
for i in range(9):
for x in range(9):
if board[i][x] == 0:
return i, x # returns row then column
return None
def solve(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if isvalid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
# board_generator()
print_board(board)
start_time = time.time()
solve(board)
print("*" * 30)
print("*" * 30)
print_board(board)
print("Elapse time: {} seconds".format(time.time() - start_time))
| true |
8d6f9acabce91efaf453dbe5210beef138fed0c4 | motasimmakki/Basic-Python-Programming | /EncryptionUsingPython.py | 587 | 4.15625 | 4 | myStr=input("Enter A String To Encrypt :")
i=0
encStr=""
decStr=""
def reverseString(x):
return x[::-1]
#string encryption
while i<len(myStr) :
if i%2==0 :
ch=ord(myStr[i])+3
else :
ch=ord(myStr[i])+5
encStr+=str(chr(ch))
# print(ch,end=" ")
i-=-1
encStr=reverseString(encStr)
print("\nEncrypted String Is : "+encStr)
#string decryption
i=0
encStr=reverseString(encStr)
while i<len(encStr) :
if i%2==0 :
ch=ord(encStr[i])-3
else :
ch=ord(encStr[i])-5
decStr+=str(chr(ch))
i-=-1
print("\nDecrypted String Is : "+decStr)
| false |
8c9a759f3dcb91db4437c531b790033554b5df57 | KlymenkoDenys/lesson | /Tasks_p49.py | 733 | 4.25 | 4 | # Воображаемы благодарности
# Образец применения escape -последовательностей
print("\t\t\tВоображаемые благодарности")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\ \\")
print("\t\t\tРазработчика игры")
print("\t\t\tМайкла Доусона")
print("\t\t\t \\ \\ \\ \\ \\ \\ \\ \\")
print("\nОтдельное спасибо хотелось бы сказать: ")
print("моему парикмахеру Генри по прозвищу \'Великолепный\', который не знает слова \"невозможно\".")
# Звучит системный динамик
print("\a")
input("\n\nНажмите Enter, чтобы выйти.")
| false |
10d9a50c6d91af3a77f1c6fb04d0b3ebf51b525f | Jgoschke86/Jay | /Classes/py3interm/EXAMPLES/specialmethods.py | 1,348 | 4.375 | 4 | #!/usr/bin/python3
class Special(object):
def __init__(self,value):
self._value = str(value) # all Special objects are strings
# define what happens when a Special object is added to another Special object
def __add__(self,other):
return self._value + other._value
# define what happens when a Special object is multiplied by a value
def __mul__(self,num):
return ''.join((self._value for i in range(num)))
# define what happens when str() called on a Special object
def __str__(self):
return self._value.upper()
# define equality between two Special valuess
def __eq__(self,other):
return self._value == other._value
if __name__ == '__main__':
s = Special('spam')
t = Special('eggs')
u = Special('spam')
v = Special(5)
w = Special(22)
print("s + s", s + s)
print("s + t", s + t)
print("t + t", t + t)
print("s * 10", s * 10)
print("t * 3", t * 3)
print("str(s)={0} str(t)={1}".format( str(s), str(t) ))
print("id(s)={0} id(t)={1} id(u)={2}".format( id(s), id(t), id(u) ))
print("s == s", s == s)
print("s == t", s == t)
print("u == s", s == u)
print("v + v", v + v)
print("v + w", v + w)
print("w + w", w + w)
print("v * 10", v * 10)
print("w * 3", w * 3)
| false |
0797d7477b5d70f632c94b42dbc381b6e84b2bd3 | Jgoschke86/Jay | /Classes/py3intro/ANSWERS/calc.py | 588 | 4.1875 | 4 | #!/usr/bin/python3
def add(x,y):
return x + y
def sub(x,y):
return x - y
def mul(x,y):
return x * y
def div(x,y):
return x/y
while True:
expr = input("Enter a math expression: ")
if expr.lower() == 'q':
break
(v1,op,v2) = expr.split()
v1 = float(v1)
v2 = float(v2)
if op == '+':
result = add(v1,v2)
elif op == '-':
result = sub(v1,v2)
elif op == '*':
result = mul(v1,v2)
elif op == '/':
result = div(v1,v2)
else:
print("Bad operator!")
print("{0:.3f}".format(result))
| false |
06e4663d0c88fafcc266ed5bcf7923beb22778b9 | karenseunsom/python102 | /todos.py | 1,312 | 4.15625 | 4 | # want to ask user what they want to add to list.
import json
# todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]
with open('todos.json', 'r') as file_handle:
# contents = file_handle.read()
# print(contents['name'])
todos = json.load(file_handle)
def print_todos():
print('------ Todos ------')
count = 1
for todo in todos:
print(f"{count}: {todo}")
count += 1
print('-------------------')
while True:
print("""
Choose an option: )
1. Print Todos
2. Add Todos
3. Remove Todo
0. Quit
""")
user_choice = input('')
if user_choice == '1':
print_todos()
elif user_choice == '2':
# add new item
new_item = input("What do you want to add? ")
todos.append(new_item)
elif user_choice == '3':
# delete a todo
index = 0
for todo in todos:
print(f"{index}: {todo}")
index += 1
delete_index = int(input("Which item would you like to delete? "))
del todos[delete_index - 1]
elif user_choice == '0':
# exit the program loop
break
with open('todos.json', 'w') as file_handle:
json.dump(todos, file_handle)
| true |
0cab04ced071bd9934491d37203139f2c9e9cbbb | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex028.py | 670 | 4.21875 | 4 | """
Escreva um programa que faça o computador pensar em um número inteiro entre 0 e 5 e peça para o usuário
tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.
"""
from random import randint
from emoji import emojize
print('JOGO DA ADIVINHAÇÃO')
numero_computador = randint(0, 5)
numero_usuario = int(input('Qual seu número de palpite entre 0 e 5? '))
if numero_computador == numero_usuario:
print(emojize('Você venceu! :punch: :clap: ', use_aliases=True))
else:
print(emojize('Palpite errado, o certo seria {}, tenta de novo :exclamation: '.format(numero_computador), use_aliases=True))
| false |
bc701a95028d7c76f519cfde5b862b5b1b9472fa | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex058.py | 1,520 | 4.1875 | 4 | """
Melhore o jogo do desafio 28 onde o computador vai pensar em um número entre 0 e 10.
Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários
para vencer.
"""
from random import randint
from emoji import emojize
print('\033[4;36mJOGO DA ADIVINHAÇÃO 2.0\033[m')
numero_computador = randint(0, 10)
numero_usuario = -1 # outra opção é aceitar Booleano: False e comparar while not numero_usuario...
numero_palpites = 0
while numero_usuario != numero_computador:
#numero_computador = randint(0, 10)
numero_usuario = int(input('\033[31mAdivinhe qual número estou pensando: \033[m'))
if numero_usuario == numero_computador:
print('\033[36mVocê acertou\033[m, eu realmente pensei no \033[1m{}\033[m, '
'e você disse exatamente: \033[1m{}\033[m'.format(numero_computador, numero_usuario))
elif numero_usuario < numero_computador:
numero_palpites += 1
print('\033[33mQuase\033[m, um pouco mais...')
#print('\033[33mQuase\033[m, eu pensei no {}. Vai de novo.'.format(numero_computador))
#print('\033[33mQuase\033[m, vai de novo.'.format())
else:
numero_palpites += 1
print('\033[33mQuase\033[m, um pouco menos...')
# numero_palpites+1, pra incluir mais um após a verificação do número igual.
print(emojize('\nVocê precisou de {} palpites pra acertar meu número, :collision::collision::collision:!'
.format(numero_palpites+1), use_aliases=True))
| false |
8c8441e88e6f5185a9958bfd542e35e6c954818b | MarcosAllysson/python-basico-fundamento-da-linguagem | /prova-mundo-2.py | 1,542 | 4.53125 | 5 | """
Em uma condição composta, qual das cláusulas de estrutura pode se repetir dentro de uma mesma condição?
"""
#print('vários elif em um mesmo if composto')
"""
Qual das opções a seguir vai somar 3 unidades à variável t em Python?
"""
t = 0
t += 3
"""
Qual é o jeito certo de verificar se a primeira letra de uma string n é uma vogal?
"""
nome = 'am nome qualquer'
#print(nome[0].lower() in 'aeiou')
"""
Qual das opções a seguir contém apenas estruturas de repetição (laços) em Python?
"""
#print('for / while')
"""
Se usarmos a estrutura for c in range(0, 10, 3): no Python e colocarmos dentro do bloco um
comando print(c), quais serão os valores impressos na tela do terminal?
"""
#for c in range(0, 10, 3):
# print(c)
"""
Que comando podemos usar para gerar um número inteiro aleatório, entre 10 e 100?
"""
#print('n = randint(0, 100)')
"""
Para podermos gerar números aleatórios em nossos programas em Python,
temos que importar a biblioteca correta, usando o comando:
"""
#print('from random import randint')
"""
Qual é o comando em Python responsável por interromper um laço imediatamente?
"""
#print('break')
"""
Qual dos comandos abaixo seria o mais adequado para ler uma única letra pelo teclado,
transformando-a sempre em maiúsculas? Se por acaso o usuário digitar mais de uma letra, apenas a primeira será considerada.
"""
#resp = str(input('Digite uma letra: ')).strip().upper()[0]
"""
As condições aninhadas em Python são representadas pela estrutura:
"""
#print('if; elif; else') | false |
59906a734f2dcbd536610ef649844341d82510ce | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex059.py | 1,243 | 4.3125 | 4 | """
Crie um programa que leia 2 valores e mostre um menu na tela:
[1]somar
[2]multiplicar
[3]maior
[4]novos números
[5]sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
"""
print('\033[1;36mCRIANDO UM MENU DE OPÇÕES\033[m')
valor1 = int(input('Digite valor 1: '))
valor2 = int(input('Digite valor 2: '))
opcao = 0
while opcao != 5:
opcao = int(input('\n{:=^25} \n[1] Somar \n[2] Multiplicar \n[3] Maior \n[4] Novos números \n[5] Sair \nSua escolha: '
.format('MENU')))
if opcao == 1:
soma = valor1 + valor2
print('Soma de {} + {} = {}.'.format(valor1, valor2, soma))
elif opcao == 2:
multi = valor1 * valor2
print('Soma de {} + {} = {}.'.format(valor1, valor2, multi))
elif opcao == 3:
if valor1 > valor2:
maior = valor1
else:
maior = valor2
print('O maior entre {} e {}, é {}.'.format(valor1, valor2, maior))
elif opcao == 4:
print('Beleza, vamos lá...')
valor1 = int(input('Digite valor 1: '))
valor2 = int(input('Digite valor 2: '))
elif opcao == 5:
print('Finalizando... até mais =D')
else:
print('Opção inválida.')
| false |
68e4b4215a683e0e9522a64b1fab426fd4bfa241 | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex033.py | 367 | 4.21875 | 4 | """
Faça um programa que leia 3 números e mostre qual é o maior e o menor.
"""
print('MAIOR E MENOR VALORES')
num1 = int(input('Digite primeiro número: '))
num2 = int(input('Digite segundo número: '))
num3 = int(input('Digite terceiro número: '))
print('Maior valor digitado {}'.format(max(num1, num2, num3)), ', e o menor {}.'.format(min(num1, num2, num3)))
| false |
b4daa31904d580ad5ca7cc5501625d56b55514f0 | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex051.py | 727 | 4.125 | 4 | """
Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final,
mostre os 10 primeiros termos dessa progressão.
Progressão aritmética (PA) é uma sequência numérica que possui a seguinte definição:
a diferença entre dois termos consecutivos é sempre igual a uma constante, geralmente
chamada de razão da PA. É possível, a partir apenas do primeiro termo e da razão de uma
PA, encontrar o valor de qualquer termo.
"""
print('PROGRESSÃO ARITMÉTICA')
primeiro = int(input('Primeiro elemento: '))
razao = int(input('Razão: '))
elementos = 10
ultimo = primeiro + (elementos-1) * razao # fórmula do enésimo termo de uma PA.
ultimo += 1
for i in range(primeiro, ultimo, razao):
print(i)
| false |
4f1be934e1980c02c9daa348e4da50cabe0f303f | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex062.py | 657 | 4.15625 | 4 | """
Melhore o desafio 61, perguntando para o usuário se ele quer mostrar mais alguns termos.
O programa encerra quando ele disser que quer mostrar 0 termos.
"""
print('SUPER PROGRESSÃO ARITMÉTICA 3.0')
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
termo = primeiro
cont = 1
total = 0
mais = 10 # simulando que o usuário quer mais 10 termos.
while mais != 0:
total += mais
while cont <= total:
print('{} -> '.format(termo), end='')
termo += razao
cont += 1
print('Pausa')
mais = int(input('Quer mostrar quantos termos a mais? '))
print('Fim, com {} termos mostrados.'.format(total))
| false |
73dd0a768454a0b28cb11f503a67e280241394b4 | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex010.py | 571 | 4.1875 | 4 | """
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
Considere = US$ = 1,00 = R$ 3,27
"""
print('DÓLARES NA CARTEIRA')
valor = float(input('Quanto você tem na carteira? R$ '))
if valor < 5.27:
print('Você não pode comprar nenhum dólar, por que 1 dólar custa R$ 5,27.')
if valor < 6.40:
print('Você não pode comprar euro, por que hoje custa R$ 6,40.')
else:
dolares = valor / 5.27
euro = valor / 6.40
print('Com R$ {}, você consegue comprar U${:.2f} e E{:.2f}.'.format(valor, dolares, euro))
| false |
113ab8c6b2245a74fbcce68168c463a8f8550eaf | MarcosAllysson/python-basico-fundamento-da-linguagem | /ex011.py | 548 | 4.21875 | 4 | """
Faça um programa que leia largura e a altura de uma parede em metros, calcula a sua área e a quantidade de tinta
necessário para pintá-la. Sabendo que, cada litro de tinta, pinta uma área de 2m**2 (2 metros quadrados).
"""
print('LITROS DE TINTA')
largura = float(input('Qual largura da parede? '))
altura = float(input('Qual altura da parede? '))
area = largura * altura
quantidade = area / 2
print('Como a área vale \033[1;31;40m{}\033[m metros, você precisa de {:.2f} litros de tinta pra pintar a parede.'.format(area, quantidade))
| false |
60ff157dd08174723fd53794c323a35e61a3cb76 | aly22/cspython | /week1/return_day.py | 208 | 4.1875 | 4 | day1 = int(input("Please enter the starting day number: "))
length_of_stay = int(input("Please enter the length of your stay: "))
leave_day =day1+length_of_stay%7
print("The leaving day will be: ",leave_day)
| true |
77dc3f01c0e6e865de7a863e51fb67dc344c4082 | Ziweili-12/BigData | /Assignment1_MapReduce/babynames.py | 2,087 | 4.21875 | 4 | #!/usr/bin/python
import sys
import re
def extract_names(filename):
"""
Given a file name for baby<year>.html,
returns a list starting with the year string
followed by the name-rank strings in alphabetical order.
['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
If this seems too daunting, return
['2006', (male_name,rank), (female_name,rank), ....]
The names and ranks are pairs rather than strings and they
do not have to be sorted. For example the list might begin
['2006', ('Jacob','1'), ('Emma','1'), ...]
"""
#open file
f = open(filename,mode = "r",encoding = "utf-8",).read()
#search for year in this document
year = re.search(">Popularity\sin\s(\d\d\d\d)<",f)[1]
#print("The year of this file is",year)
#if cannot find year, print something and stop this function
if not year:
print("There is no obvious year in this file")
sys.exit(0)
#search for the name
name2 = re.findall("<td>([0-9]+)</td><td>([a-zA-Z]+)</td><td>([a-zA-Z]+)</td>",f)
#print("There are {} names in this file".format(2*len(name2)))
#if len(name2)==0:
#print("There are no names in this file")
#Extract boy's name and girl's name
name = {}
for i in range(len(name2)):
boy = name2[i][1]
name[boy] = i+1
girl = name2[i][2]
name[girl]=i+1
name_rank = []
name_rank.append(year)
sort_name = sorted(name.keys())
for i in sort_name:
name_rank.append(i+" "+str(name[i]))
return name_rank
def main():
# This command-line parsing code is provided.
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
if len(sys.argv) == 2:
arg = sys.argv[1]
else:
print("usage: ", sys.argv[0], "filename")
sys.exit(1)
# +++your code here+++
# For each filename, get the names, then print the text output
names = extract_names(arg)
text = '\n'.join(names) + '\n'
print(text)
print('Yes, you are running the script correctly!')
if __name__ == '__main__':
main()
| true |
f1d1023de7cdc6db4723f1f44df605b550890639 | anmsuarezma/Astrof-sica-Computacional | /02. Plotting and classes/code/curveplot1.py | 649 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 23 Dec 2018
@author: ashcat
Curve Plotting
"""
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return t**2*np.exp(-t**2)
# range of the independent variable
# 50 points between 0 and 3
t = np.linspace(0, 3, 50)
# values of the function for the numbers in the range of t
y = np.zeros(len(t))
for i in range(len(t)):
y[i] = f(t[i])
# plot and label of the curve
fig, ax = plt.subplots()
ax.plot(t, y, label='f(t) = t^2*exp(-t^2)')
# labels of the plot
ax.set(xlabel="t", ylabel="f(t)",
title="Title of the plot")
ax.legend()
# show the plot
plt.show() | true |
ffa1662468fe13c126535cae3c4a68d6c3dbe9c6 | Harelyac/Python-PROJECTS | /Wikipedia Network/article.py | 2,085 | 4.59375 | 5 | class Article:
"""
The constructor of Article make an Article object that consist of 2 fields
which are title and neighbor - a list that contains more Article objects!
"""
def __init__(self, article_title):
self.__title = article_title
self.__neighbors = []
def get_title(self):
"""
This function gets the title of an Article
:return:
"""
return self.__title
def add_neighbor(self,neighbor):
"""
This function add neighbor to Article neighbor list
:param neighbor:
:return:
"""
# check if new neighbor is already listed under article neighbors!
if neighbor not in self.__neighbors:
self.__neighbors.append(neighbor)
def get_titles(self):
"""
returns the names of all the neighbors
:return:
"""
return [neighbor.get_title() for neighbor in self.get_neighbors()]
def get_neighbors(self):
"""
This functions returns a list of all Article neighbors.
:return:
"""
return self.__neighbors
def __repr__(self):
"""This is a magic method that used to represent the Article object
with the Article title and Article's neighbors"""
names_list = list()
for neighbor in self.__neighbors:
names_list.append(neighbor.get_title())
repr_string = self.get_title(), names_list
return str(repr_string)
def __len__(self):
"""
This function, returns the number of neighbors of an Article
:return:
"""
num_of_neighbors = len(self.__neighbors)
return num_of_neighbors
def __contains__(self, article):
"""
This magic method check whether an article is a neighbor of the
current Article.
:param article:
:return:
"""
if article in self.__neighbors:
return True
else:
return False
| true |
c86f34b28f333c39877855cb0d5555f80e1035e0 | nsm-lab/principles-of-computing | /practice_activity3.py | 2,484 | 4.34375 | 4 | # Practice Activity 3 for Principles of Computing class, by k., 07/04/2014
# Analyzing a simple dice game (see https://class.coursera.org/principlescomputing-001/wiki/dice_game )
# skeleton code: http://www.codeskulptor.org/#poc_dice_game_template.py
# official solution: http://www.codeskulptor.org/#poc_dice_game_solution.py
'''
analyzing a simple dice game
'''
def gen_all_sequences(outcomes, length):
'''
iterative function that enumerates the set of all sequences of
outcomes of given length
'''
ans = set([()])
for dummy_idx in range(length):
temp = set()
for seq in ans:
for item in outcomes:
new_seq = list(seq)
new_seq.append(item)
temp.add(tuple(new_seq))
ans = temp
return ans
# example for digits
#print gen_all_sequences([1, 2, 3, 4, 5, 6], 2)
def max_repeats(seq):
'''
compute the maximum number of times that an outcome is repeated in a sequence
'''
acc = []
# counting number of occurances for each item in a sequence
for item in seq:
acc.append(seq.count(item))
return max(acc)
#print max_repeats((3, 3, 3))
#print max_repeats((6, 6, 2))
def compute_expected_value():
'''
computes expected value of simple dice game, pay the initial $10,
gain for double is $10, gain for triple is $200
'''
doubles = 0
triples = 0
seq = gen_all_sequences([1, 2, 3, 4, 5, 6], 3)
# searching for doubles and triples in generated sequence
for item in seq:
if max_repeats(item) == 2:
doubles += 1
elif max_repeats(item) == 3:
triples += 1
# probability is frequency divided by all possible results
doubles /= float(len(seq))
triples /= float(len(seq))
return doubles * 10 + triples * 200
#print compute_expected_value()
def run_test():
'''
testing code, note that the initial cost of playing the game has been subtracted
'''
outcomes = set([1, 2, 3, 4, 5, 6])
print 'All possible sequences of three dice are'
print gen_all_sequences(outcomes, 3)
print
print 'Test for max repeats'
print 'Max repeat for (3, 1, 2) is', max_repeats((3, 1, 2))
print 'Max repeat for (3, 3, 2) is', max_repeats((3, 3, 2))
print 'Max repeat for (3, 3, 3) is', max_repeats((3, 3, 3))
print
print 'Ignoring the initial $10, the expected value was $', compute_expected_value()
run_test()
| true |
3e840900dee1013038c152b6a6410999b2987e56 | sreit/temp_converter | /temp.py | 2,124 | 4.375 | 4 | while True:
try:
start_degree = float(input('Enter a temperature: '))
break
except ValueError:
print('ERROR. Not a number.')
continue
start_unit_list = ['C', 'F', 'K']
start_unit = input('What unit is this? (C, F, K): ').upper()
while start_unit not in start_unit_list:
print('ERROR. Not a valid unit. Please use "C", "F", or "K".')
start_unit = input('What unit is this? (C, F, K): ').upper()
new_unit_list = ['C', 'F', 'K']
new_unit = input('What unit do you want? (C, F, K): ').upper()
while new_unit not in new_unit_list or start_unit == new_unit:
print('ERROR. Not a valid input. Value either same as starting unit or not "C", "F", or "K". ')
new_unit = input('What unit do you want? (C, F, K): ').upper()
new_degree = 'ERROR'
def c_f(start_degree, new_degree):
new_degree = (9.0 / 5.0) * start_degree + 32
print(start_degree, start_unit, 'is', new_degree, new_unit)
def c_k(start_degree, new_degree):
new_degree = start_degree + 273.15
print(start_degree, start_unit, 'is', new_degree, new_unit)
def f_c(start_degree, new_degree):
new_degree = (start_degree - 32) * (5.0 / 9.0)
print(start_degree, start_unit, 'is', new_degree, new_unit)
def f_k(start_degree, new_degree):
new_degree = ((start_degree - 32) * 5) / 9 + 273.15
print(start_degree, start_unit, 'is', new_degree, new_unit)
def k_c(start_degree, new_degree):
new_degree = start_degree - 273.15
print(start_degree, start_unit, 'is', new_degree, new_unit)
def k_f(start_degree, new_degree):
new_degree = ((start_degree - 273.15) * 1.8) + 32
print(start_degree, start_unit, 'is', new_degree, new_unit)
if start_unit == 'C' and new_unit == 'F': c_f(start_degree, new_degree)
if start_unit == 'C' and new_unit == 'K': c_k(start_degree, new_degree)
if start_unit == 'F' and new_unit == 'C': f_c(start_degree, new_degree)
if start_unit == 'F' and new_unit == 'K': f_k(start_degree, new_degree)
if start_unit == 'K' and new_unit == 'C': k_c(start_degree, new_degree)
if start_unit == 'K' and new_unit == 'F': k_f(start_degree, new_degree)
| true |
62f3131125935949819ec706228572e18949a43a | neelchavan/Python | /Dictionary.py | 325 | 4.34375 | 4 | #here we are using dictionaries to give the meaning of some words to the user
d1 = {'mes':'In english it means \'more\'','que':'In english it means \'Than\'','un':'In english it means \'A\'','club':'In english it means \'Club\''}
#Enter the word to get the meaning of it
Word = input("Enter the word\n",)
print(d1[Word])
| true |
642813fb40fa3b52729d1354b74ccb02e6b5e087 | neelchavan/Python | /get2ndlargest.py | 274 | 4.125 | 4 | #Unsorted list with duplicates
numbers = [3,4,2,4,6,6]
#removing duplicates
numbers = list(dict.fromkeys(numbers))
#sort the list
numbers.sort()
#remove first max number
numbers.remove(max(numbers))
#then print second highest number as the first highest
print(max(numbers))
| true |
d8d8606d1460657f3b2775228ef03a1bc59f3836 | markfj81/Geog565_Assign1 | /Assignment1_Part1_[Johnson].py | 644 | 4.3125 | 4 | # Instructions:
# Create a script that examines the following string for a particular letter.
# "Python in GIS makes work easier".
# If the string does contain your letter, the script should print
# "Yes, the string contains the letter."
# If not, the script should print "No, the string does not contain the letter."
# Name: [Mark Johnson]
# Date: 4/3/2018
# Assignment 1 Part 1
# This script examines a string for a particular letter.
myString = 'Python in GIS makes work easier'
#enter code here
if 'y' in myString:
print "Yes, the string contains the letter."
else:
print "No, the string does not contain the letter." | true |
306c87093bb07bd010f215455f2c13f0312cf161 | ComradYuri/Statistics-LinearRegression | /script.py | 1,790 | 4.125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
# Setting up pandas so that it displays all columns instead of collapsing them
desired_width = 320
pd.set_option('display.width', desired_width)
np.set_printoptions(linewidth=desired_width)
pd.set_option('display.max_columns', 10)
df = pd.read_csv(
"https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv")
# print(df.head())
prod_per_year = df.groupby("year").totalprod.mean().reset_index()
prod_per_year["*_in_tonnes"] = prod_per_year.totalprod.apply(lambda x: round(x/1000))
print("Honey production per year")
print(prod_per_year)
X = prod_per_year.year.reset_index(drop=True)
# convert x to one column containing many rows instead of a dataframe with indexing
# This is used for the scikit learn to create the linear regression model
X = X.values.reshape(-1, 1)
# print(X)
y = prod_per_year.totalprod.reset_index(drop=True)
y = y.values.reshape(-1, 1)
# print(y)
regr = linear_model.LinearRegression()
regr.fit(X, y)
# slope and intercept of linear regression
print("\n\nSlope and intercept of linear regression model")
print(regr.coef_[0], regr.intercept_)
# values of linear regression line
# y = m*x + b
y_predict = [regr.coef_[0] * x + regr.intercept_ for x in X]
plt.scatter(X, y)
plt.plot(X, y_predict)
plt.show()
plt.close('all')
# Future honey production estimations
X_future = np.array(range(2013, 2050))
# print(X_future)
X_future = X_future.reshape(-1, 1)
# print(X_future)
future_predict = regr.predict(X_future)
print("Total honey production in 2050 is predicted to be {} kilo".format(int((regr.coef_*2050 + regr.intercept_)[0][0])))
plt.scatter(X, y)
plt.plot(X_future, future_predict)
plt.show()
| true |
6abd018955ab20d6756c7003351bdb0701f80b01 | AishaE/Python | /hello_world.py | 833 | 4.15625 | 4 | # 1. TASK: print "Hello World"
print("Hello World")
# 2. print "Hello Noelle!" with the name in a variable
name = "Aisha"
print("Hello" , name ) # with a comma
print("hello" + name ) # with a +
# 3. print "Hello 42!" with the number in a variable
name = 7
print("Hello" , name ) # with a comma
# print("Hello" + name ) # with a + -- this one should give us an error!
name = 7
print ("Hello " + str(name)) # ninja challenge ??
# # 4. print "I love to eat sushi and pizza." with the foods in variables
food1 = "sushi"
food2 = "pizza"
print("I love to eat {} and {}.".format(food1, food2)) # with .format()
print(f"My favorite food is {food1} and {food2}") # with an f string
count = 0
while count < 5:
print("looping - ", count)
count += 1
y = 3
while y > 0:
print(y)
y = y - 1
else:
print("Final else statement")
| true |
18c220bfbf8f7bcd14673ebe0ad26271a83975cc | TiagoJLeandro/uri-online-judge | /python/uri_3303.py | 908 | 4.4375 | 4 | """
Recentemente Juquinha aprendeu a falar palavrões. Espantada com a descoberta do garoto, sua mãe o proibiu de falar qualquer palavrão, sobre o risco de o menino perder sua mesada.
Como Juquinha odeia ficar sem mesada, ele te contratou para desenvolver um programa que informe para ele se uma palavra é um palavrão ou não.
Palavrões são palavras que contém dez ou mais caracteres, todas as outras palavras são consideradas palavrinhas.
Entrada
A entrada consiste em vários casos de teste. Cada caso contém uma string que descreve a palavra que Juquinha deseja consultar. Essa string é composta apenas de letras minúsculas e seu tamanho não excede 20 caracteres.
Saída
Para cada caso de teste imprima se a palavra que Juquinha consultou é um palavrão ou uma palavrinha.
"""
palavra_length = len(input())
if palavra_length >= 10:
print("palavrao")
else:
print("palavrinha") | false |
1489ff679d4ee25c2610e4389815f2cf079d7790 | ko28/homework | /cs/cs540/p1/p1_weather.py | 2,785 | 4.21875 | 4 | # Name: Daniel Ko
# Project 1, CS 540
# Email: ko28@wisc.edu
# Some comments were taken from the homework directly
import datetime
# Distance between points in three-dimensional space,
# where those dimensions are the precipitation amount (PRCP),
# maximum temperature (TMAX), and minimum temperature for the day (TMIN)
def manhattan_distance(data_point1, data_point2):
return (abs(data_point1['TMAX'] - data_point2['TMAX']) +
abs(data_point1['PRCP'] - data_point2['PRCP']) +
abs(data_point1['TMIN'] - data_point2['TMIN']))
# Return a list of data point dictionaries read from the specified file.
def read_dataset(filename):
d = []
with open(filename) as f:
for line in f:
words = line.split()
# Generate dictionary from each line and add to list
d.append({'DATE': words[0],
'TMAX': float(words[1]),
'PRCP': float(words[2]),
'TMIN': float(words[3]),
'RAIN': words[4]})
return d
# Return a prediction of whether it is raining or not based on a majority vote of the list of neighbors.
def majority_vote(nearest_neighbors):
numTrue = 0
numFalse = 0
for n in nearest_neighbors:
if n['RAIN'] == 'TRUE':
numTrue+=1
elif n['RAIN'] == 'FALSE':
numFalse +=1
#If a tie occurs, default to 'TRUE' as your answer.
return "TRUE" if numTrue >= numFalse else "FALSE"
def k_nearest_neighbors(filename, test_point, k, year_interval):
data = read_dataset(filename)
# adding all values within year interval from data into this list
within_year = []
test_point_date = getdate(test_point)
years = year_interval * datetime.timedelta(days = 365)
# use date time library to do some simple subtraction on dates to determine if data point
# is in range
for d in data:
time_diff = test_point_date - getdate(d)
if years >= abs(time_diff):
within_year.append(d)
# list of tuples with manhattan_distance as first element, data point as second
man_dis = []
for d in within_year:
man_dis.append((manhattan_distance(test_point,d), d))
# sort this list by manhattan_distance, asending
# source: https://www.geeksforgeeks.org/python-program-to-sort-a-list-of-tuples-alphabetically/
man_dis = sorted(man_dis, key = lambda x : x[0])
# majority_vote of closest k valid neighbors
return majority_vote([x[1] for x in man_dis[:k]])
# Returns datetime object given a dictionary entry of data point
def getdate(point):
datestr = point["DATE"]
return datetime.datetime(year = int(datestr[:4]),
month = int(datestr[5:7]), day = int(datestr[8:10]))
| true |
24712a41292d204f783818546321cdfc0af3b4bd | Douglass-Jeffrey/Unit-3-08-Python | /leap_year_determiner.py | 571 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Oct 2019
# This program determines if a user inputted year is a leap year
def main():
# variables
leap_year = " is not"
# process
# input
useryear = int(input("Enter a year of your choice:"))
print("")
# Output
if useryear % 4 == 0:
if useryear % 100 == 0:
if useryear % 400 == 0:
leap_year = " is"
else:
leap_year = " is"
print(str(useryear) + leap_year + " a leap year.")
if __name__ == "__main__":
main()
| true |
b81601d4963cda59a132282ed2fe2627aeb32de0 | valleyjo/cs0008 | /project-2/activity-4.py | 1,936 | 4.125 | 4 | #Email: amv49@pitt.edu
#Name: Alex Vallejo
#ID: 3578411
#Date: 2/19/2014
#Description: This program is the game of craps!
import random
user_name = input("Enter your name: "); #Get the user's name
print("\nWelcome " + user_name + "!"); #Print a nice welcome message
print("This game of craps was written by Alex Vallejo <amv49@pitt.edu>\n") #Tell 'em who write this!
print("Instructions:"); #Display the instructions!
print("A new shooter (player) begins his roll. This is known as the come out " +
"roll. If the shooter rolls a 7 or 11 you win. If the shooter rolls a 2, " +
"3 or 12, you lose. If the shooter rolls any other number, that number " +
"becomes the point number. The shooter must roll that number again before " +
"a seven is rolled. If that happens, you win. If a seven is rolled before " +
"the point number is rolled again, you lose. ");
game_over = False; # Boolean flag used to keep the game running
shooter_roll = random.randint(1,12) # Roll the dice
print("\nShooter rolls: ", shooter_roll);
# Player wins if the computer rolls 7 or 11
if (shooter_roll == 7 or shooter_roll == 11):
game_over = True;
print("Congrats, you win!");
# Computer wins if it rolls 2, 3 or 12
elif (shooter_roll == 2 or shooter_roll == 3 or shooter_roll == 12):
game_over = True;
print("Sorry, you lose!");
# The point number becomes the roll
else:
point_number = shooter_roll;
print("The point number is: ", point_number);
# While the game is not over, keep rollin'
while (not game_over):
roll = random.randint(1,12)
print("Roll: ", roll);
# If the computer rolls the point number, player wins!
if (roll == point_number):
game_over = True;
print("Congrats, you win!");
# If the computer rolls 7, the computer wins!
if (roll == 7):
game_over = True;
print("Sorry, you lose!");
# Print a nice message to thank the user for playing
print("Thanks for playing", user_name,"!");
| true |
712889dc38bb100d13d8f24e93cd99e9a9a2e19f | Pratik-20/Python-Projects.- | /0038.py | 617 | 4.25 | 4 | """
#PracticeCode: 0038
🎯 FORWARD IF YOU LIKE IT 🎯
Task:
Create a program to input a number and check if it is multiple of 2 than print "Sel" , if multiple of 5 then print "fish" or if multiple of both then print "Selfish".
Sample :-
input - 5
output - fish
input - 10
output - Selfish
_________&____________________________________________________________________________
"""
#print("Enter a Number: ")
n= int(input()) # Take Input Number
if n%2==0 and n%5==0: # This should be first condition & use modules sign
print("Selfish")
elif n%2==0:
print('Sel')
elif n%5==0:
print("fish")
else:
("")
| true |
eb0477cf1ceffeedb167c1dd6ef938210f461e61 | kyletruong/epi | /9_binary_trees/1_height_balanced.py | 1,711 | 4.1875 | 4 | # Check if binary tree is height-balanced
# Difference in height of left sub-tree and right-subtree is at most 1
from binarytree import BinaryTree, Node
from collections import namedtuple
def is_balanced(root):
# namedtuple makes it more expensive but more readable
Node = namedtuple('Node', ['balanced', 'height'])
def check_tuple(root):
if root is None:
return Node(True, -1)
l = check_tuple(root.left)
if not l.balanced:
return Node(False, 0)
r = check_tuple(root.right)
if not r.balanced:
return Node(False, 0)
# Subtrees are balanced
balance = abs(l.height - r.height) <= 1
height = max(l.height, r.height) + 1
return Node(balance, height)
# Realize that I can use negative int to indicate false, but less readable
def check_int(root):
if not root:
return 0
# By checking -1 right after, can avoid looking at every single node
# So if -1, keep throwing that back up and skip recursive calls
l = check_int(root.left)
if l == -1:
return -1
r = check_int(root.right)
if r == -1:
return -1
if abs(l - r) > 1:
return -1
return max(l, r) + 1
return check_int(root) != -1
if __name__ == '__main__':
subroot = Node(2)
subroot.left = Node(3)
subroot.left.left = Node(4)
subroot.left.right = Node(4)
root = Node(1)
root.right = Node(2)
root.left = subroot
print(is_balanced(root))
r = Node(2)
r.left = Node(2)
r.right = Node(2)
r.right.right = Node(3)
r.left.right = Node(4)
print(is_balanced(r))
| true |
1827f2b72badd7a47848e114b18b69076c919d9a | AshrafulH1/Blackjack | /hand.py | 2,967 | 4.40625 | 4 | """
Module with the class definition of Hand.
"""
from card import Card
class Hand(object):
"""A Hand is a list of at most 5 Cards.
Attributes (hidden):
__cards: a list of objects from class Card. Initialized to to an empty
list. The length of __cards is no greater than HANDSIZE.
Class Constants:
HANDSIZE = the maximum size of a hand"""
HANDSIZE= 5
def getCards(self):
"""Returns: list of cards in self.__cards """
cardList = self.__cards
return cardList
def __init__(self):
"""Initialize self.__cards as an empty list"""
self.__cards= []
def isFull(self):
"""Returns: True if self is a full hand; otherwise returns False"""
#TO DO:
#Replace pass with your implementation
if len(self.__cards) >= 5:
return True
else:
return False
def getHandValue(self):
"""Returns: the sum of the values of the Cards in self (this hand)."""
#TO DO:
#Replace pass with your implementation
cardList = self.getCards()
total = 0
for i in cardList:
total = total + i.getCardValue()
return total
def addCard(self, c):
"""Returns: True if self isn't already a full hand; in this case add
Card c to self (this hand). Otherwise return False and do not add
Card c."""
#TO DO:
#Replace pass with your implementation
assert type(c) == Card
if len(self.__cards) < 5:
self.__cards.append(c)
return True
else:
return False
def clearHand(self):
"""Clear out the cards in self (this hand), i.e., set to empty array"""
self.__cards= []
def __str__(self):
"""
Returns: string showing all the Cards in self (this hand).
If self (this hand) is empty, return the string 'Empty hand'.
Example: 'QUEEN-H 9-S JACK-C ACE-H 5-D'
"""
if not self.getCards():
# In Python, bool(x) evaluates to False if x is an empty list and
# evaluates to True if x is non-empty.
# An explicit way to check whether self.cards is empty is
# if len(self.getCards())==0
return 'Empty hand'
#TO DO:
#Write code to return the card names of this hand as a string
else:
# self.getCards() returns a list with a length > 0.
cardList = self.getCards()
name_in_list = []
for i in cardList:
name = i.getCardName()
name_in_list.append(name)
name_in_string = ""
for j in name_in_list:
name_in_string = name_in_string + j + ' '
result = name_in_string.strip()
return result
| true |
a9112fd648eb272506b86824cc1ef86eef57f29e | CREESTL/GrokkingAlgorithms | /selection_sort.py | 1,018 | 4.21875 | 4 | '''
Сортировка выбором - это когда каждый выбранный элемент помещается в новый список
Здесь приведен пример сортировки массива по возрастанию сортировкой выбором.
O(n^2)
'''
import time
import random
def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
# из исходного массива элемент удаляется
new_arr.append(arr.pop(smallest))
return new_arr
my_arr = [random.randint(1, 256) for i in range(100)]
start_time = time.time()
sorted_arr = selection_sort(my_arr)
end_time = time.time()
print(f"Sorting finished in {end_time - start_time:1.10f} seconds")
| false |
d4361f36f8ecabef3d8de25fe870b4ceff073ff4 | piresalexsandro/cursoPython | /stdr-3305-dicionarios.py | 1,720 | 4.28125 | 4 | # Em Python, como vimos anteriormente, as listas são sequências de
# elementos identificados por um índice representado por um número inteiro.
# Às vezes, no entanto, queremos utilizar alguma informação como índice de
# algum dado em vez de um índice numérico. Para isso, usamos os
# dicionários.
# Um dicionário nada mais é do que um tipo de dado usado para armazenar
# informações em pares chave-valor, na qual a chave tem um papel
# semelhante ao do índice numérico e o valor é o dado atribuído àquela
# chave. As chaves, da mesma forma que um índice numérico, devem ser
# únicas.
# Para criar um dicionário, os inputs devem estar entre chaves ({}) e
# separados por vírgula. Cada item do dicionário consiste em uma chave,
# seguido de dois pontos (:) e, por fim, um valor, como pode ser visto
# abaixo:
clientes = {'Boris' : 38, 'Malvo':45, 'Barak':62, 'Michelle':53, 'Cicero':25, "Moniele": 14}
print('{}'.format(clientes))
keys = [key for key in clientes]
# acessando dicionario por chave
print('Birth {} is {}'.format(keys[0],clientes['Boris']))
#alterando um dicionario
#uptdate - adicionando
clientes['Jay'] = 51
print(clientes)
#deletando um item no dicionario
del clientes['Cicero']
clientes.pop('Jay')
print(clientes)
#funçoes
print(len(clientes))
#in e not in
print('Jay' in clientes)
print('Jay' not in clientes)
# deleta um item aleatorio do dicionario
print( 'Deletei aleatoriamente: {}'.format(clientes.popitem()))
print(clientes)
#delta todos os itens do dicionario
# clientes.clear()
#retorna as chaves e valores do dicionario como tuplas
print("chaves do dicionário: {}".format(clientes.keys()))
print("valores do dicionário: {}".format(clientes.values()))
| false |
b2eb6c860482f26f8a2f35a176191681ee5d9a02 | lubchenko05/python-examples | /task_4.py | 657 | 4.125 | 4 | """
Написать функцию, принимающую последовательность словарей, содержащих имена и возвращающую имена через запятую,
кроме последнего, присоединённого через амперсанд.
[{'name': 'John'}, {'name': 'Jack'}, {'name': 'Joe'}] -> 'John, Jack & Joe'
[{'name': 'John'}, {'name': 'Jack'}] -> 'John & Jack'
[{'name': 'John'}] -> 'John'
"""
def string_names(l: list) -> str:
names = [i['name'] for i in l]
if len(names) > 1:
return ', '.join(names[:-1]) + ' & ' + names[-1]
else:
return names[0]
| false |
c56e5fa4fb2acbedd0fc1b58bc94721419fe280e | wanqiangliu/python | /5_9.py | 854 | 4.1875 | 4 | #访问复制的列表、删除原列表
users = ['zhangsan','admin','lisi','wangwu']
for user in users[:]:
if user == 'admin':
print("Hello admin,would you like to see a status report?")
else:
print("Hello " + user + ",thank you for logging in again")
users.remove(user)
if users:
print("remove:" + user)
else:
print("We need to find some users!")
print("-----------------------\n")
#逆序访问 逆序如果用range想访问下标为0的元素则range的第二个参数为-1
users = ['zhangsan','admin','lisi','wangwu']
for i in range(len(users)-1,-1,-1):
user = users[i]
if users[i] == 'admin':
print("Hello admin,would you like to see a status report?")
else:
print("Hello " + users[i] + ",thank you for logging in again")
users.remove(users[i])
if users:
print("remove:" + user)
else:
print("We need to find some users!") | false |
12860a786e3e82f215c8693cf1c8d3a04a88fd6a | Aakash7khadka/Data-Structures-and-algorithm-in-python | /gpa.py | 655 | 4.28125 | 4 | print('This is a gpa calculator')
print('Please enter all your letter grades, one per line. ')
print('Enter a blank line to designate the end. ')
points = { 'A+' :4.0, 'A' :4.0, 'A-':3.67, 'B+':3.33, 'B' :3.0, 'B-' :2.67,'C+' :2.33, 'C' :2.0, 'C' :1.67, 'D+' :1.33, 'D' :1.0, 'F' :0.0}
num_courses=0
total_points=0
done=False
while(not done):
grade=input()
if grade =='':
done=True
elif (grade not in points):
print(f'invalid grade value:{grade}')
else:
num_courses+=1
total_points+=points[grade]
if num_courses>0:
print('Your average GPA is:{}'.format(total_points/num_courses))
print('A+' in points) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.