blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1b788ed26371d117fb008e34947901a28423aebd | leilalu/algorithm | /剑指offer/第二遍/08.二叉树的下一个节点.py | 1,115 | 4.15625 | 4 | """
题目:
给定一棵二叉树和其中的一个节点,如何找【中序遍历】序列的下一个结点?
树中的结点除了有两个分别指向左、右子结点的指针,还有一个指向父结点的指针。
"""
def FindNextNode(pNode):
""""
如果是根结点:如果有右结点,返回右结点
如果没有右结点,是否有父结点:
如果有父结点:
它是左子结点:返回父结点
它是右子结点:返回父结点的父结点,直到某个父结点是左子结点
如果是左结点,返回父结点
如果是
"""
if not pNode:
return None
pNext = None
if pNode.right:
right = pNode.right
while right.left:
right = right.left
pNext = right
elif pNode.next:
parent = pNode.next
current = pNode
while parent and current == parent.right:
current = parent
parent = parent.next
pNext = parent
return pNext
| false |
78e05511a05b0ab901e8772cc04b86aa29a26a40 | leilalu/algorithm | /剑指offer/第五遍/59-2.队列的最大值.py | 1,219 | 4.125 | 4 | """
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
["MaxQueue","pop_front","max_value"]
[[],[],[]]
输出: [null,-1,-1]
"""
class MaxQueue:
def __init__(self):
from collections import deque
self.queue = deque()
self.max_queue = deque()
def max_value(self) -> int:
if self.max_queue:
return self.max_queue[0]
else:
return -1
def push_back(self, value: int) -> None:
self.queue.append(value)
while self.max_queue and value >= self.max_queue[-1]:
self.max_queue.pop()
self.max_queue.append(value)
def pop_front(self) -> int:
if self.queue and self.max_queue:
value = self.queue.popleft()
if value == self.max_queue[0]:
self.max_queue.popleft()
else:
value = -1
return value
| false |
3500394cc1da77913ec3752c8bb2d29b11b1f29b | justien/CourseraPython | /ch6_Test0.py | 1,106 | 4.15625 | 4 | # -*- coding: utf8 -*-
# justine lera 2016
# Python Specialisation - Coursera
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "=================================================="
print "Chapter 6: Strings Assignment"
print
print
# Comment comment
print """
6.5 Write code using find() and string slicing (see section 6.10) to extract
the number at the end of the line below.
Convert the extracted value to a floating point number.
Print it out.
"""
text = "X-DSPAM-spamidence: 0.8475";
dppos = text.find('.')
spamscore = text[dppos-1:] # assumes scores are between 1.0 and 0.0
spamscore = float(spamscore)
print spamscore
# assumes score can be any float >= 0
prefixend = text.find(':')
spamscore = text[prefixend+1:]
spamscore = spamscore.strip()
spamscore = float(spamscore)
print spamscore
# short way of doing above
spamscore = float(text[prefixend+1:].strip())
print spamscore
# float does a .strip() before type conversion
pos = text.find(':')
num = float(text[pos+1:])
print num
print
print
print "==================================================" | true |
ce3c4a0371a029dbd273360dbc52835b11c2cb33 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_9_4_number_served.py | 1,650 | 4.4375 | 4 | # 9-4. Number Served: Start with your program from Exercise 9-1 (page 166).
# Add an attribute called number_served with a default value of 0. Create an
# instance called restaurant from this class. Print the number of customers the
# restaurant has served, and then change this value and print it again.
# Add a method called set_number_served() that lets you set the number
# of customers that have been served. Call this method with a new number and
# print the value again.
# Add a method called increment_number_served() that lets you increment
# the number of customers who’ve been served. Call this method with any number
# you like that could represent how many customers were served in, say, a
# day of business.
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("Restaurant name is: " + self.restaurant_name)
print("Restaurant Cuisine Type is: " + self.cuisine_type)
def open_restaurant(self):
print("Our restaurant " + self.restaurant_name + " now open!")
def set_number_served(self, number_served):
self.number_served = number_served
def increment_number_served(self, increment):
self.number_served += increment
restaurant = Restaurant("KFC", "Fried Chicken")
print(restaurant.number_served)
restaurant.number_served = 10
print(restaurant.number_served)
restaurant.set_number_served(20)
print(restaurant.number_served)
restaurant.increment_number_served(50)
print(restaurant.number_served)
| true |
888a1e66add51623a4a7ca61c432ffaf2e7306ac | shaoda06/python_work | /Part_I_Basics/examples/example_2_3_Strings.py | 1,245 | 4.625 | 5 | # 2.3.1 Changing Case in a String with Methods
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
# 2.3.2 Combining or Concatenating Strings
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
message = "Hello, " + full_name.title() + "!"
print(message)
# 2.3.3 Adding Whitespace to Strings with Tabs or Newlines
# To add a tab to your text, use the character combination \t as shown
print("Python")
print("\tPython")
# To add a newline in a string, use the character combination \n:
print("Languages: \nPython\nC\nJavaScript")
# Combine tabs and newlines in a single string
print("Languages: \n\tPython\n\tC\n\tJavaScript")
# 2.3.4 Stripping Whitespace
favorite_language = "Python "
print(favorite_language)
print(favorite_language.rstrip())
favorite_language = " Python "
print(favorite_language)
favorite_language = favorite_language.rstrip()
favorite_language = favorite_language.lstrip()
print(favorite_language)
# 2.3.5 Avoiding Syntax Errors with Strings
message = "One of Python's strengths is its diverse community."
print(message)
message = 'One of Python\'s strengths is its diverse community.'
print(message)
| true |
05e07093f6d271ffc57bebbf4fd0c857e58be4a1 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_5_10_checking_usernames.py | 1,310 | 4.28125 | 4 | # 5-10. Checking Usernames: Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users.
# • Make another list of five usernames called new_users. Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# • Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted.
current_users = ['Shaoda', 'MrrNonsense', 'jyangjun', 'xiaoming', 'admin']
new_users = ['tony', 'tom', 'MrrNonsense', 'shaoda', 'bestshooter']
current_users_case_insensitive = []
for current_user in current_users:
current_users_case_insensitive.append(current_user.lower())
print(current_users_case_insensitive)
for new_user in new_users:
if new_user.lower() in current_users_case_insensitive:
print(
'Sorry, the username: "' + new_user + '" has been used! Please enter a new username!')
else:
print('The username: "' + new_user + '" is available!')
| true |
1525ef3a80fe96f54fd4fb09b7491abaf15f3118 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_5_7_favorite_fruit.py | 597 | 4.40625 | 4 | # 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of
# independent if statements that check for certain fruits in your list.
# • Make a list of your three favorite fruits and call it favorite_fruits.
# • Write five if statements. Each should check whether a certain kind of fruit
# is in your list. If the fruit is in your list, the if block should print a statement,
# such as You really like bananas!
favorite_fruits = ['pear', 'apple', 'banana']
certain_fruit = "banana"
if certain_fruit in favorite_fruits:
print("You really like " + certain_fruit)
| true |
c90cafde1b6aaa92f509d27efb3e77f47151ad0d | shaoda06/python_work | /Part_I_Basics/exercises/exercise_6_4_glossary_2.py | 668 | 4.5 | 4 | # 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean
# up the code from Exercise 6-3 (page 102) by replacing your series of print
# statements with a loop that runs through the dictionary’s keys and values.
# When you’re sure that your loop works, add five more Python terms to your
# glossary. When you run your program again, these new words and meanings
# should automatically be included in the output.
glossary = {
'append': '.append()',
'insert': '.insert()',
'del': 'del ',
'remove': '.remove',
'pop': '.pop()',
}
for key, value in glossary.items():
print("Key: " + key)
print("Value: " + value + "\n")
| true |
9334659921bff17abfd27f4ee846e4266df22a80 | shaoda06/python_work | /Part_I_Basics/examples/example_7_1_1_greeter.py | 691 | 4.375 | 4 | # Writing Clear Prompts
# Each time you use the input() function, you should include a clear,
# easy-to follow prompt that tells the user exactly what kind of information
# you’re looking for. Any statement that tells the user what to enter should
# work. For example:
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?\n"
name = input(prompt)
print("\nHello," + name + "!")
# The int() function converts a string representation of a number to a
# numerical representation, as shown here:
age = input("How old are you? ")
age = int(age)
if age >= 18:
print("You are an adult!")
else:
print("You are under 18!")
| true |
3896dfec904e99bf3baa8f8bbb62a60a5a5f9fc8 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_3_5_changing_guest_list.py | 930 | 4.15625 | 4 | # 3-5. Changing Guest List: You just heard that one of your guests can’t make the
# dinner, so you need to send out a new set of invitations. You’ll have to think of
# someone else to invite.
# • Start with your program from Exercise 3-4. Add a print statement at the
# end of your program stating the name of the guest who can’t make it.
# • Modify your list, replacing the name of the guest who can’t make it with
# the name of the new person you are inviting.
# • Print a second set of invitation messages, one for each person who is still
# in your list.
names = ['MrrNonsense', 'Tony', 'Tom']
msg = " Would u like to have dinner with me?"
print("Hello, " + names[0] + msg)
print("Hello, " + names[1] + msg)
print("Hello, " + names[2] + msg)
print(names[0] + " can not come to dinner.")
names[0] = "James"
print("Hello, " + names[0] + msg)
print("Hello, " + names[1] + msg)
print("Hello, " + names[2] + msg)
| true |
826d693bb54c1320ddea28370ceb07e0696dc487 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_6_2_favorite_numbers.py | 676 | 4.25 | 4 | # 6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers.
# Think of five names, and use them as keys in your dictionary. Think of a
# favorite number for each person, and store each as a value in your
# dictionary. Print each person’s name and their favorite number. For even
# more fun, poll a few friends and get some actual data for your program.
favorite_numbers = {
'mrrnonsense': 1,
'shaoda': 2,
'xiaoming': 3,
'icehanba': 4,
'jyangjun': 5,
}
print(favorite_numbers['mrrNonsense'])
print(favorite_numbers['shaoda'])
print(favorite_numbers['xiaoming'])
print(favorite_numbers['icehanba'])
print(favorite_numbers['jyangjun'])
| true |
fe792070d524789aa7b9759fbe1be9a394c1e379 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_10_7_addition_Calculator.py | 847 | 4.125 | 4 | # 10-7. Addition Calculator: Wrap your code from Exercise 10-6 in a while loop
# so the user can continue entering numbers even if they make a mistake and
# enter text instead of a number.
prompts = "Please enter two numbers, and I will add them together.\n" \
"Enter 'quit' to stop."
while True:
first_number = input("First number: ")
if first_number == 'quit':
break
second_number = input("Second number: ")
if second_number == 'quit':
break
try:
first_number = int(first_number)
second_number = int(second_number)
except ValueError:
print("You can only enter intergers.")
else:
sum = first_number + second_number
print(
str(first_number) +
" + " +
str(second_number) +
" = " +
str(sum))
| true |
fb894772decf3dd8681a1bb67a4a97514f9a70f4 | shaoda06/python_work | /part_II_projects/exercises/exercise_13_3_raindrops.py | 1,947 | 4.21875 | 4 | # 13-3. Raindrops: Find an image of a raindrop and create a grid of raindrops.
# Make the raindrops fall toward the bottom of the screen until they disappear.
import sys
import pygame
from pygame.sprite import Sprite
class Screen:
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.screen_color = (255, 255, 255)
self.screen = pygame.display.set_mode(
(self.screen_width, self.screen_height))
self.screen_rect = self.screen.get_rect()
self.raindrops = pygame.sprite.Group()
self._create_raindrop()
def run_game(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.screen.fill(self.screen_color)
self.raindrops.draw(self.screen)
pygame.display.flip()
def _create_raindrop(self):
raindrop = Raindrop()
raindrop_width, raindrop_height = raindrop.rect.size
number_x = self.screen_width // raindrop_width
number_y = self.screen_height // raindrop_height
space_x = self.screen_width % raindrop_width // (number_x + 1)
space_y = self.screen_height % raindrop_height // (number_y + 1)
for number_row in range(number_y):
for number_column in range(number_x):
raindrop = Raindrop()
raindrop.rect.x = raindrop_width * \
number_column + space_x * (number_column + 1)
raindrop.rect.y = raindrop_height * \
number_row + space_y * (number_row + 1)
self.raindrops.add(raindrop)
class Raindrop(Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("exercise_13_3_raindrop.bmp")
self.rect = self.image.get_rect()
if __name__ == "__main__":
screen = Screen()
screen.run_game()
| true |
399056e76c322c0401c5e7e41fe7817fd7f20ac3 | shaoda06/python_work | /Part_I_Basics/examples/example_10_3_7_word_count.py | 1,369 | 4.375 | 4 | # 10.3.7 Working with Multiple Files
def count_words(file_name):
"""Count the approximate number of words in a file."""
try:
with open(file_name) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + file_name + " dose not exist."
print(msg)
# 10.3.8 Failing Silently
# In the previous example, we informed our users that one of the
# files was unavailable. But you don’t need to report every exception
# you catch. Sometimes you’ll want the program to fail silently when
# an exception occurs and continue on as if nothing happened. To make
# a program fail silently, you write a try block as usual, but you
# explicitly tell Python to do nothing in the except block. Python
# has a pass statement that tells it to do nothing in a block:
# pass
else:
words = contents.split()
num_words = len(words)
print("The file " + file_name + " has about " + str(num_words)
+ " words.")
file_name = "example_10_3_6_alice.txt"
count_words(file_name)
file_names = ['example_10_3_6_alice.txt', 'example_10_3_7_siddhartha.txt',
'example_10_3_7_moby_dick.txt', 'example_10_3_7_little_women.txt']
for file_name in file_names:
count_words(file_name)
| true |
c6a008188c768f9d5266406123eb5f1c3497b389 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_3_6_more_guests.py | 1,250 | 4.59375 | 5 | # 3-6. More Guests: You just found a bigger dinner table, so now more space is
# available. Think of three more guests to invite to dinner.
# • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print
# statement to the end of your program informing people that you found a
# bigger dinner table.
# • Use insert() to add one new guest to the beginning of your list.
# • Use insert() to add one new guest to the middle of your list.
# • Use append() to add one new guest to the end of your list.
# • Print a new set of invitation messages, one for each person in your list.
names = ['MrrNonsense', 'Tony', 'Tom']
msg = " Would u like to have dinner with me?"
print("Hello, " + names[0] + msg)
print("Hello, " + names[1] + msg)
print("Hello, " + names[2] + msg)
print("I just found a bigger dinner table, so now more space is available")
print("I'm considering that invite 3 more people to have dinner together!")
names.insert(0, "James")
names.insert(2, "Josh")
names.append("Leo")
print("Hello again! " + names[0] + msg)
print("Hello again! " + names[1] + msg)
print("Hello again! " + names[2] + msg)
print("Hello again! " + names[3] + msg)
print("Hello again! " + names[4] + msg)
print("Hello again! " + names[5] + msg)
| true |
13241be97d33f44f265445186c56be2048e9a1e9 | shaoda06/python_work | /Part_I_Basics/examples/example_9_2_1_car.py | 2,058 | 4.6875 | 5 | # 9.2.1 The Car Class
# Let’s write a new class representing a car. Our class will store information
# about the kind of car we’re working with, and it will have a method that
# summarizes this information:
# 9.2.2 Setting default value for an attribute
# Line #24 is to initialize attribute with a default value 0
# Line #31 is to add a method to read each car's odometer
# 9.2.3 Modifying attribute values
# Line #55 is to modifying attribute's value directly
# Line #58 is to modifying attribute's value through a method
# Line #64 is to incrementing an attribute's value through a method
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to represent a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't rol back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
my_new_car.update_odometer(46)
my_new_car.read_odometer()
my_new_car.update_odometer(23)
my_new_car.read_odometer()
my_new_car.increment_odometer(100)
my_new_car.read_odometer()
| true |
691552139e74d957439f164a1315dddced1b9414 | TheVibration/pythonprocedures | /findelement.py | 606 | 4.15625 | 4 | # find_element takes two inputs
# lst and v. lst is a list of
# any type and v is a value of any
# type. find_element will go through
# lst and find the index at which
# v exists. If v isn't in lst, -1
# will be returned.
def find_element(lst,v):
counter = 0
for i in lst:
pos = i.find(v)
if pos == -1:
if counter == len(lst) -1:
return -1
else:
counter = counter + 1
elif pos > -1:
return counter
# another way to do this in one line
def find_element(lst, val):
print lst.index(val)
| true |
db2ef3de811092b4553f42147f277492ec2c3c80 | G0nov4/Programacion | /Python/Algoritmia/Metodo_de_Seleccio.py | 642 | 4.15625 | 4 | '''
Ordenamiento por seleccion
Es un algoritmo que consisite en ordenar los elementos de manera ascendente
o desendente
Funcionamiento:
-Buscar eldato mas pequeño de la lista
- Intercambiarlo por el actual
- Seguir buscando el mas pequeño de la lista
- Intercambiarlo por el actual
- Esto se repite sucesivamente
'''
lista = [6,5,7,7,5,3,5,3,6,7,2,1,3,4,5]
for i in range(len(lista)):
minimo = i
for x in range(i,len(lista)):
if lista[x] < lista[minimo]:
minimo = x
aux = lista[i]
lista[i] = lista[minimo]
lista[minimo]=aux
print('-------------- Lista ya ordenada ---------------')
print(lista) | false |
5b8cf851dff26a603f872f81058b0846e8582fa4 | Dhruvin1/covid19 | /random_walk.py | 1,299 | 4.1875 | 4 | from random import choice
import settings
class Randomwalk():
""" A class to generate random walks."""
def __init__(self, x=0, y=0):
"""Initiate attributes of a walk"""
# All walks start at (x,y)
self.is_infected = False
self.x_values = []
self.y_values = []
self.infected_days = 0
self.infection = False
self.dead = False
self.x_values.append(x)
self.y_values.append(y)
def fill_walk(self):
"""Calculate all the points in the walk."""
# Keep taking steps until the walk reaches the desired length
#while len(self.x_values) < settings.WALK_DAYS:
# Decide which direction to go and how far to go in that direction
x_direction = choice([-1,1])
x_distance = choice([0,1,2,3])
x_step = x_direction*x_distance
y_direction = choice([-1,1])
y_distance = choice([0,1,2,3])
y_step = y_direction*y_distance
# Calculate new position
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
if abs(x) > settings.X_LIMIT:
x = self.x_values[-1]
if abs(y) > settings.Y_LIMIT:
y = self.y_values[-1]
self.x_values.append(x)
self.y_values.append(y) | true |
d22d27eddc509404b4e15a97edee44d2eaac8330 | Shiven004/learnpython | /Numbers/fibonacci_value.py | 585 | 4.46875 | 4 | #!/usr/bin/env python3
# Fibonacci Value
# Have the user enter a number
# and calculate that number's
# fibonacci value.
def fib(x):
"""
Assumes x an integer >= 0
Returns Fibonacci value of x
"""
assert isinstance(x, int) and x >= 0
n_1, n_2, i = 1, 1, 2
while i <= x:
n_new = n_1 + n_2
n_1, n_2 = n_2, n_new
i += 1
return n_2
def main(): # Wrapper function
x = int(input('Enter a number to get its fibonacci value: '))
print('The fibonacci value of', x, 'is:', fib(x))
if __name__ == '__main__':
main()
| true |
04b8789692ce0274401697ceb7a5ecc2a44ce030 | JakeTheLion89/portfolio | /Python/word_scram.py | 2,507 | 4.125 | 4 | # July 23
# Learning python
# Excercise in "random" module
import random
def wordScram():
print """Welcome to Word Scram. Choose a difficulty and unscramble 10 words!
"""
## Game Dictionaies and Variables
game = {
"EASY" : ["night", "quill" ,"book", "wine", "grass", "fill","quilt","kind","public","brain" ],
"MEDIUM" : ["voltage","lighting", "risking","better", "music", "master", "lovely", "carbon", "pursue", "teeth"],
"HARD" : ["glaring","padded", "draped", "clothes","sliders","medicine","systemic","battle", "genius", "blaring"],
}
score= 0
wordBatch= "none"
##Game setup
play = raw_input("Do you want to play? Y/N?: ").upper()
while play != "Y" and play != "YES" and play != "N" and play != "NO":
play = raw_input("Sorry. Didn't get that. Do you want to play? Y/N?: ").upper()
while play == "Y" or play == "YES":
wordBatch = raw_input("What difficulty? Easy, Medium, or Hard?: ").upper()
while wordBatch != "EASY" and wordBatch != "MEDIUM" and wordBatch != "HARD":
wordBatch = raw_input("Sorry. Didn't get that? Easy, Medium, or Hard?: ").upper()
start = raw_input("Press enter to start!")
## Main game operation
for word in game[wordBatch]:
scramble = word.upper()
while scramble == word.upper():
scramble = list(word)
random.shuffle(scramble)
scramble = "".join(scramble)
else:
print scramble.upper()
if raw_input("Answer: ").upper() == word.upper():
print """Correct!
"""
score = score + 1
else:
print """Wrong!
"""
print "Game Over!"
## scoring output
if score < 8:
print "You got " + str(score) + " out of 10 right. You can do better."
elif score < 10:
print "Good Job! You got " + str(score) + " out of 10 right."
elif score == 10:
print "Awesome! You got a 10 out of 10! Perfect score!"
score = 0
play = raw_input("Do you want to play again? Y/N: ").upper()
while play != "Y" and play != "YES" and play != "N" and play != "NO":
play = raw_input("Sorry. Didn't get that. Do you want to play again? Y/N?: ").upper()
if play == "N" or play == "NO":
print "Thanks for playing!"
##End of Game
print "Bye!"
wordScram()
| true |
5d6afa46a2c08a8462aa5f63ad54e2ee53e5e784 | YHGui/CS61ASp18 | /Lab/lab01/falling.py | 331 | 4.15625 | 4 | def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
"""
sum = 1
while k > 0:
sum = sum * n
k = k - 1
n = n - 1
return sum
| false |
ccdebc7b2dc593443b32343663ade9efe2bc5956 | AntonioRoye/Beginner_Python_Projects | /madlibs.py | 1,085 | 4.15625 | 4 | adjective1 = str(input("Enter an adjective: "))
noun1 = str(input("Enter a noun: "))
verb1 = str(input("Enter a verb (past tense): "))
adverb1 = str(input("Enter an adverb: "))
noun2 = str(input("Enter a noun: "))
noun3 = str(input("Enter a noun: "))
adjective2 = str(input("Enter an adjective: "))
verb2 = str(input("Enter a verb: "))
adverb2 = str(input("Enter an adverb: "))
verb3 = str(input("Enter a verb (past tense): "))
adjective3 = str(input("Enter an adjective: "))
madLib = "Today I went to the zoo. I saw a(n) " + adjective1 + " " + noun1 + " jumping up and down in its tree. He " + verb1 + " " + adverb1 + " through the large tunnel that led to its " + adjective1 + " " + noun2 + ". I got some peanuts and passed them through the cage to a gigantic gray " + noun3 + " towering above my head. Feeding that animal made me hungry. I went to get a " + adjective2 + " scoop of ice cream. It filled my stomach. Afterwaards I had to " + verb2 + " " + adverb2 + " to catch our bus. When I got home I " + verb3 + " my mom for a " + adjective3 + " day at the zoo."
print(madLib)
| true |
c235ad0774ff10ece5f1f7e0c90f3c03a89a0d66 | JessicaReay/compound_interest_app | /calc.py | 541 | 4.25 | 4 | # App: compound interest calculator
# Fuction: calculates monthly compound interest for custom user inputs
# Author: Dan & Jess
def monthly_compounding(initial, monthly, years, annual_rate):
sum = initial
months = years *12
#iterate through months
for month in range(int(months)):
# apply annual rate to current balance
sum = sum * (1+ annual_rate/ 1200)
#ass monthly contribution
sum = sum + monthly
return sum
#return initial + (monthly * 12 * years * (1+ annual_rate/100)) | true |
95ba9c78de1f6d7be74bba0ece2ec0d2710d70da | stellakaniaru/bootcamp | /day_3/data_types.py | 765 | 4.3125 | 4 | def data_type(x):
'''
takes in an argument, x:
-for an integer, return x ** 2
-for a float, return x/2
-for a string, return "hello" + x
-for a boolean, return "boolean"
-for a long, return squareroot(x)
'''
#cheking for integers
if type(x) == int:
return x ** 2
#checking for float
elif type(x) == float:
return x / 2
#checking for string
elif type(x) == str:
return "Hello {}".format(x)
#checking for boolean
elif type(x) == bool:
return "boolean"
#checking for long
elif type(x) == long:
return "long"
#output for non_data types
else:
return "Invalid input:not a data type"
#test
print data_type(50)
print data_type(23.456123456)
print data_type("dad")
print data_type(False)
print data_type(20 ** 20)
print data_type([23,45,50])
| true |
82c3aafc7d1790b02b4f3dd7bbabce51df708820 | MesutCevik/adventcalendarPython | /impl/CompetitorsList.py | 1,334 | 4.15625 | 4 | from typing import List
from impl import Competitor
class CompetitorsList:
competitors: List['Competitor'] = []
def add_competitor(self, competitor: Competitor):
self.competitors.append(competitor)
def __str__(self) -> str:
competitors_in_string: str = ""
for competitor in self.competitors:
competitors_in_string += f"Competitor: {competitor}; "
return competitors_in_string
"""
### Exercise 13 - Racing game competitors
Generate a CompetitorsList which holds a Competitor with a Driver and Vehicle.
1. Create class `CompetitorsGenerator`, which randomly generates drivers and related vehicles as a `Competitor`.
2. Create class `Competitor` storing the assigment of the derived classes of `Vehicle` and `Driver` with:
* _getPoints()_ => returns the actual points as int
* _addPoints(int)_ => add's points from a race
3. Create class `CompetitorsList` storing `Competitor`:
* _addCompetitor(Competitor competitors)_
* _getCompetitors()_ => which returns a list of `Competitor`
* _toString()_ => method, which concatenate the contained toString() methods. This will generate a String like '[Points] [Driver] [Vehicle]'
4. Add useful unit tests
5. Visualize created classes with plantuml as class diagram, inclusive associations.
""" | true |
ab0a9bc482e0034a83e008318732b818c757aa0b | smreferee/Lame-Game | /Lab2_Richard_Nolan.py | 823 | 4.34375 | 4 | ################################################
#This is Lab 2 for COSC 1336 by Richard Nolan #
#The program will display program information, #
#ask and display the user name, display a menu,#
#and finally confirm the menu choice. #
################################################
#Introduction to the program
print('Hi! Welcome to the Lame Game!')
print("This is the introduction, where you'll be asked your name.")
print('Finally, you will select a menu option, and that choice will be confirmed.')
#Username query
name = input('What is your name? ')
print (name)
#Game Menu
print("GAME MENU")
choice = int(input('1.Make Change\
2.High Card\
3.Quit\
Choice:'))
#Menu Choice Response
print(name,', you chose menu option ',choice,".", sep='');
| true |
16c862609f2b52921d214facaba3e87ef050dae7 | Nextc3/aulas-de-mainart | /Listas/Lista 6/q2.py | 1,682 | 4.15625 | 4 | '''
Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em
metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro
para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que
custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
• Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços
em 3 situações:
• comprar apenas latas de 18 litros;
• comprar apenas galões de 3,6 litros;
• misturar latas e galões, de forma que o preço seja o menor. Acrescente 10% de folga e
sempre arredonde os valores para cima, isto é, considere latas cheias.
'''
areaPintada = int(input("Escreva a área pintada"))
tintasAComprar = {"latas":0, "galoes":0}
# 1 litro pra 6 metros
#lata 18 litros . 80 reais a lata
#galoes 3,6. 25
litros = areaPintada / 6
litros = litros + (litros * 0.1) #folga
tintasAComprar["latas"] = litros // 18
resto = litros % 18
if (litros % 18) != 0:
tintasAComprar["latas"] = tintasAComprar["latas"] + 1
aviso = True
print("Só em latas {}. Total {}".format(tintasAComprar["latas"], tintasAComprar["latas"] * 80))
tintasAComprar["galoes"] = litros // 3.6
resto = litros % 3.6
if (litros % 3.6) != 0:
tintasAComprar["galoes"] = tintasAComprar["galoes"] + 1
print("Só galões {}. Total {}".format(tintasAComprar["galoes"], tintasAComprar["galoes"] * 25))
if aviso:
tintasAComprar["latas"] = tintasAComprar["latas"] - 1
resto = litros % 18
if (resto % 3.6) != 0:
tintasAComprar["galoes"] = (resto // 3.6) + 1
else:
tintasAComprar["galoes"] = 0
print("Misto {}".format(tintasAComprar))
| false |
deac9d6024ce82f36c08b88799eafbf4173ba236 | Nextc3/aulas-de-mainart | /Listas/Lista 5/q4.py | 202 | 4.125 | 4 | numero1 = int(input("Entre com o numero1: "))
numero2 = int(input("Entre com o numero2: "))
dict_decisao = {True:numero1, False:numero2}
print("Maior numero: {}".format(dict_decisao[numero1 > numero2])) | false |
86ca90fd31a09060144e0a06bf68b5423967344f | rootrUW/Python210-W19 | /students/KevinCavanaugh/session3/list_lab.py | 1,668 | 4.1875 | 4 | #!/usr/bin/env python3
# ----------------------------------------------------------------------- #
# Title: List_Lab
# Author: Kevin Cavanaugh
# Change Log: (Who,What,When)
# kcavanau, created document & completed assignment, 01/29/2019
# ----------------------------------------------------------------------- #
import sys
# --- Series 1 --- #
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
print('\n'.join(fruits))
new_fruit = input('add fruit to list: ').title()
fruits.append(new_fruit)
print('\n'.join(fruits))
n = int(input('Index number of fruit you would like to view: '))
print(fruits[n - 1])
new_fruit = input('add fruit to list: ').title()
fruits = [new_fruit] + fruits
print('\n'.join(fruits))
new_fruit = input('add fruit to list: ').title()
fruits.insert(0, new_fruit)
print('\n'.join(fruits))
for i in fruits:
if i[0] == "P":
print(i)
# # # --- Series 2 --- #
print('\n'.join(fruits))
del fruits[-1]
print('\n'.join(fruits))
remove_fruit = input('fruit to remove from list: ')
fruits.remove(remove_fruit.title())
print('\n'.join(fruits))
# # --- Series 3 --- #
for fruit in fruits:
do_i_like = input('Do you like {}?'.format(fruit.lower()))
do_i_like = do_i_like.lower()
while True:
if do_i_like == 'yes':
pass
elif do_i_like == 'no':
fruits.remove(fruit.title())
else:
do_i_like = input('Please input "yes" or "no".')
break
print('\n'.join(fruits))
# --- Series 4 --- #
fruits_reversed = list()
for fruit in fruits:
fruit_reversed = fruit[::-1]
fruits_reversed.append(fruit_reversed.title())
print(fruits_reversed)
print(fruits)
| false |
aed4d6aa3e9256d4f0e43b879b23bc36a4dcab4a | JBW1997/hello-world | /数字类型.py | 640 | 4.625 | 5 | """
#分类:整数、浮点数、复数
#整数:python可以处理任意大小的整数
"""
#交互式复赋值定义变量
num1, num2 =1, 2
print(num1,num2)
#连续定义多个变量
num3 =1
num5 =num4 =num3
print(num3, num4, num5)
"""
浮点数:由整数和小数组成,浮点数可能会有四舍五入的误差
"""
f1 = 1.1
f2 = 2.2
print(f1 + f2)
"""
复数:由实部和虚部组成,a+bj
"""
#数字类型转换
print(int(1.11))
print(float(1))
print(int("123"))
print(float("12.3"))
print(int("+123")) #加减号是做为正负号
#print(int("12+3")) 报错
#如果有其他无用字符会报错 | false |
ce619542d41fd7f2465eea7f4974e3c9d3c050d6 | wilfort/python | /example/typles.py | 717 | 4.375 | 4 | #
thistuple = ("apple", "banana", "cherry")
print(thistuple)
#
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
#
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
# the value is stille the same:
print(thistuple)
###################################################
###############
# Constructor #
###############
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
#######
# len #
#######
thistuple = tuple(("apple", "banana", "cherry"))
print(len(thistuple))
#######################################
# #
# You cannot remove items in a tuple. #
# #
####################################### | false |
9bf185e97b1c81a0ac4fe3dd7166db777cb7a032 | MatthewKosloski/starting-out-with-python | /chapters/07/03.py | 371 | 4.59375 | 5 | # Program 7-3
# Demonstrates how the append
# method can be used to add
# items to a list.
def main():
name_list = []
again = 'y'
while again.lower() == 'y':
name = input('Enter a name: ')
name_list.append(name)
again = input('Add another name? (y/n): ')
print()
print('Here are the names you entered:')
for name in name_list:
print(name)
main() | true |
3ae72ab5b4b40599ca663c2e1c1eadbdc34904dc | MatthewKosloski/starting-out-with-python | /chapters/03/06.py | 539 | 4.34375 | 4 | # Program 3-6
# This program gets a numeric test score from the
# user and displays the corresponding letter grade.
# Variables to represent the grade thresholds
A_score = 90
B_score = 80
C_score = 70
D_score = 60
# Get a test score from the user.
score = int(input('Enter your test score: '))
# Determine the grade.
if score >= A_score:
print('Grade A')
else:
if score >= B_score:
print('Grade B')
else:
if score >= C_score:
print('Grade C')
else:
if score >= D_score:
print('Grade D')
else:
print('Grade F') | true |
ef3fca65a2e5701628ad968b9be7c358dbb95325 | MatthewKosloski/starting-out-with-python | /chapters/06/13.py | 710 | 4.125 | 4 | # Program 6-13
# Gets employee data from the user and
# saves it as records in the employee.txt file.
def main():
number_of_employees = int(input('How many employee records' +
'do you want to create? '))
employee_file = open('employees.txt', 'w')
# Get each employee's data and
# write it to employees.txt
for count in range(1, number_of_employees + 1):
print('Enter data for employee #', count, sep='')
name = input('Name: ')
id_num = input('ID number: ')
dept = input('Department: ')
employee_file.write(name + '\n')
employee_file.write(id_num + '\n')
employee_file.write(dept + '\n')
print()
employee_file.close()
print('Employee records written to employees.txt')
main() | true |
519ce83fed6f9df3bc17c810db2c6ffacd79d397 | MatthewKosloski/starting-out-with-python | /homework/factorial.py | 415 | 4.1875 | 4 | # Matthew Kosloski
# Exercise 4-11
# CPSC 3310-01 SP2018
num = int(input('Enter a number >= 0 for factorial: '))
while num != -1:
# Calculate and display factorial if number is >= 0
if num >= 0:
factorial = 1
for i in range(1, num + 1):
factorial *= i
print('Factorial of', num, 'is', factorial)
print()
# Go again?
print('Enter a number >= 0 for factorial ')
num = int(input('or enter -1 to exit: ')) | true |
5bee66cb2090e4b9dba3669b3aae497b9a42227d | MatthewKosloski/starting-out-with-python | /chapters/06/23.py | 375 | 4.125 | 4 | # Program 6-23
# Handles a ValueError exception.
def main():
try:
hours = int(input('How many hours did you work? '))
pay_rate = float(input('Enter your hourly pay rate: '))
gross_pay = hours * pay_rate
print(f"Gross pay: ${format(gross_pay, ',.2f')}")
except ValueError:
print('ERROR: Hours worked and hourly pay rate must' +
' be valid numbers.')
main() | true |
d43e8b23538cf42f944943865fa14593c29b8071 | MatthewKosloski/starting-out-with-python | /chapters/04/12.py | 446 | 4.4375 | 4 | # Program 4-12
# This program calculates the sum of a series
# of numbers entered by the user.
# The maximum number
max = 5
# Initialize the accumulator
total = 0
# Explain the purpose of the program
print('This program calculates the\nsum of',
max, 'numbers you will enter.\n')
# Get the numbers and accumulate them.
for counter in range(max):
number = int(input('Enter a number: '))
total += number
# Display total
print('Total:', total) | true |
30bd227c3394fc4f470e851c54f9a2740e4068ed | MatthewKosloski/starting-out-with-python | /chapters/07/07.py | 508 | 4.15625 | 4 | # Program 7-7
# Calculates the gross pay for each
# barista.
NUM_EMPLOYEES = 6
def main():
hours = [0] * NUM_EMPLOYEES
for index in range(NUM_EMPLOYEES):
print('Enter the hours worked by employee ', \
index + 1, ': ', sep='', end='')
hours[index] = float(input())
pay_rate = float(input('Enter the hourly pay rate: '))
for index in range(NUM_EMPLOYEES):
gross_pay = hours[index] * pay_rate
print('Gross pay for employee ', index + 1, ': $', \
format(gross_pay, ',.2f'), sep='')
main() | true |
441bee12976cb345a05b93a4d6f7e212352e9217 | MatthewKosloski/starting-out-with-python | /chapters/04/01.py | 632 | 4.15625 | 4 | # Program 4-1
# This program calculates sales commissions.
# Create a variable to control the loop
keep_going = 'y'
# Calculate a series of commissions
while keep_going == 'y':
# Get a salesperson's sales and commission rate.
sales = float(input('Enter the amount of sales: '))
comm_rate = float(input('Enter the commission rate: '))
# Calculate commission
commission = sales * comm_rate
# Display commission
print('This commission is $', format(commission, ',.2f'), sep='')
# See if the user wants to do another calculation
keep_going = input('Do you want to calculate another ' +
'commission? (Enter y for yes): ') | true |
623305636b6eabf818bdc6e4ad67cf45d15d2208 | AnthonySDi/python-fizzbuzz | /main.py | 758 | 4.34375 | 4 | def fizzBuzz(num):
'''
Receives num from main and determines if it is divisable by 3, 5, or both and prints the int with fizz, buzz, or fizzbuzz respectfully.
helper function to main()
keyword arguments:
num: int
'''
if(num % 3 == 0 and num % 5 == 0):
#num is divisable by both 3 and 5
print(str(num) + ' fizzbuzz')
elif(num % 3 == 0):
#num is divisable by 3 only
print(str(num) + ' fizz')
elif(num % 5 == 0):
#num is divisable by 5 only
print(str(num) + ' buzz')
else:
#num was not divisable by 3 or 5
print(num)
def main():
'''
loops through a range of 1 through 100 and passes each number onto helper function fizzBuzz(num) as an argument
'''
for i in range(1,101):
fizzBuzz(i)
main() | true |
05f0578d150f7fc9eb4ce6ae57fe85694657b098 | SahilBastola/lab_exercise | /question no 8.py | 242 | 4.375 | 4 |
#write a python program which accepts the radius of a circle from the user and compute the area (area of circle = pier**2
radius=float(input("Enter the value of radius:"))
pie= 22/7
area = pie*radius**2
print(f"the area of circle is {area}") | true |
307e4ca82c543e16d29d03cf9631961218c409ab | johnkirch123/python | /udemy-mega-course/exercises/forIteration.py | 303 | 4.21875 | 4 | def celsius_to_farenheit(c):
if c > -273.15:
return c * 9/5 + 32
else:
return "Impossible temperature."
#print(celsius_to_farenheit(float(input("Enter Celsius for conversion: "))))
temperatures=[10, -20, -289, 100]
for temp in temperatures:
print(celsius_to_farenheit(temp))
| false |
be1bcbb2118d393a7d7a6cfc86fe2562dc1db529 | dfds/python-for-absolute-beginners | /doc_examples.py | 1,123 | 4.3125 | 4 | #!/usr/bin/env python3
class Person:
"""
This class defines a person ;)
"""
def __init__(self, name: str, age: int) -> None:
"""
This is the class constructur.
:param name: The person's name.
:param age: The person's age.
:type name: str
:type age: int
"""
self.name = name
self.age = age
def _is_over_age(self) -> bool:
"""
Check if the person is of legal age.
:return: bool
"""
if self.age >= 18:
return True
else:
return False
def get_person(self) -> str:
"""
Print details about the person.
If the person is 18 years old or older, then the name and age
will be printed. Otherwise only print the name.
:return: str
"""
if self._is_over_age():
return f'{self.name} is {self.age} years old'
else:
return f'{self.name}'
if __name__ == '__main__':
# Print the documentation using help().
# Or using: python -m pydoc ./doc-example.py
help(Person)
| true |
7e776d80ade377fa2bbf3ee0236be71e35966043 | MarceloDL-A/Python | /10-Introduction_to_Pandas/Select_Rows_with_Logic_I_equal.py | 704 | 4.375 | 4 | import codecademylib
import pandas as pd
df = pd.DataFrame([
['January', 100, 100, 23, 100],
['February', 51, 45, 145, 45],
['March', 81, 96, 65, 96],
['April', 80, 80, 54, 180],
['May', 51, 54, 54, 154],
['June', 112, 109, 79, 129]],
columns=['month', 'clinic_east',
'clinic_north', 'clinic_south',
'clinic_west'])
#Youre going to staff the clinic for January of this year. You want to know how many visits took place in January of last year, to help you prepare.
#Create variable january using a logical statement that selects the row of df where the 'month' column is 'January'.
january = df[df.month == 'January']
#Inspect january using print.
print(january) | true |
3b74a5f0b532198a85d79480fbc2fc06a4fbd896 | MarceloDL-A/Python | /15-Statistics_with_NumPy/Statistics_in_NumPy/Mean_and_Logical_Operations.py | 2,192 | 4.5 | 4 | """
INTRODUCTION TO STATISTICS WITH NUMPY
Mean and Logical Operations
We can also use np.mean to calculate the percent of array elements that have a certain property.
As we know, a logical operator will evaluate each item in an array to see if it matches the specified condition. If the item matches the given condition, the item will evaluate as True and equal 1. If it does not match, it will be False and equal 0.
When np.mean calculates a logical statement, the resulting mean value will be equivalent to the total number of True items divided by the total array length.
In our produce survey example, we can use this calculation to find out the percentage of people who bought more than 8 pounds of produce each week:
>>> np.mean(survey_array > 8)
0.2
The logical statement survey_array > 8 evaluates which survey answers were greater than 8, and assigns them a value of 1. np.mean adds all of the 1s up and divides them by the length of survey_array. The resulting output tells us that 20% of responders purchased more than 8 pounds of produce.
"""
import numpy as np
class_year = np.array([1967, 1949, 2004, 1997, 1953, 1950, 1958, 1974, 1987, 2006, 2013, 1978, 1951, 1998, 1996, 1952, 2005, 2007, 2003, 1955, 1963, 1978, 2001, 2012, 2014, 1948, 1970, 2011, 1962, 1966, 1978, 1988, 2006, 1971, 1994, 1978, 1977, 1960, 2008, 1965, 1990, 2011, 1962, 1995, 2004, 1991, 1952, 2013, 1983, 1955, 1957, 1947, 1994, 1978, 1957, 2016, 1969, 1996, 1958, 1994, 1958, 2008, 1988, 1977, 1991, 1997, 2009, 1976, 1999, 1975, 1949, 1985, 2001, 1952, 1953, 1949, 2015, 2006, 1996, 2015, 2009, 1949, 2004, 2010, 2011, 2001, 1998, 1967, 1994, 1966, 1994, 1986, 1963, 1954, 1963, 1987, 1992, 2008, 1979, 1987])
"""
You're running an alumni reunion at your local college. You have a list of the names of each person in attendance and the year that they graduated.
We've saved this list as a NumPy array to the variable class_year. Calculate the percent of attending alumni who graduated on and after 2005 and save your result to the variable millennials.
"""
millennials = np.mean(class_year > 2005)
"""
Print the value of millennials to the terminal
"""
print("millennials: " + str(millennials))
| true |
db96f54eb8dab41492a4e9fbb4d3072e96eec934 | MarceloDL-A/Python | /13-Data_Visualization/Introduction_to_Seaborn/Understanding_Aggregates.py | 943 | 4.28125 | 4 | import codecademylib3_seaborn
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
gradebook = pd.read_csv("gradebook.csv")
#Next, take a minute to understand the data youll analyze. The DataFrame gradebook contains the complete gradebook for a hypothetical classroom. Use print to examine gradebook.
print(gradebook)
#Select all rows from the gradebook DataFrame where assignment_name is equal to Assignment 1. Save the result to the variable assignment1.
assignment1 = gradebook[gradebook.assignment_name == "Assignment 1"]
#Check out the DataFrame you just created. Print assignment1.
print(assignment1)
#Now use Numpy to calculate the median grade in assignment1.
#Use np.median() to calculate the median of the column grade from assignment1 and save it to asn1_median.
asn1_median = np.median(assignment1.grade)
#Display asn1_median using print. What is the median grade on Assignment 1?
print(asn1_median ) | true |
801604eed56381f44cf18f885ac7f3a9ea8eba39 | MarceloDL-A/Python | /14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quartiles_Interquartile.py | 1,597 | 4.71875 | 5 | """
Quartiles
The interquartile range is the difference between the third quartile (Q3) and the first quartile (Q1).
For now, all you need to know is that the first quartile is the value that separates the first 25% of the data from the remaining 75%.
The third quartile is the opposite it separates the first 75% of the data from the remaining 25%.
The interquartile range of the dataset is shown to be between Q3 and Q1.
The interquartile range is the difference between these two values.
"""
from song_data import songs
import numpy as np
"""
Weve calculated the first quartile of songs and stored it in the variable q1.
Calculate the third quartile and store it in a variable named q3.
To calculate the third quartile, call the same function, but change the second parameter to 0.75.
"""
q1 = np.quantile(songs, 0.25)
#Create the variables q3 and interquartile_range here:
q3 = np.quantile(songs, 0.75)
"""
Now that we have both the first quartile and the third quartile, lets calculate the IQR.
Create a variable named interquartile_range and set it equal to the difference between q3 and q1.
"""
interquartile_range = q3 - q1
# Ignore the code below here
try:
print("The first quartile of the dataset is " + str(q1) + "\n")
except NameError:
print("You haven't defined q1 yet\n")
try:
print("The third quartile of the dataset is " + str(q3) + "\n")
except NameError:
print("You haven't defined q3 yet\n")
try:
print("The IQR of the dataset is " + str(interquartile_range) + "\n")
except NameError:
print("You haven't defined interquartile_range yet\n") | true |
cf2293fa6dc26162ce73a2c33cbc8bdd6c580d22 | MarceloDL-A/Python | /14-Statistics_with_Python/Histograms/Bins_and_Count I.py | 2,238 | 4.28125 | 4 | """
Bins and Count I
In the previous exercise, you found that the earliest transaction time is close to 0, and the latest transaction is close to 24, making your range nearly 24 hours.
Now, we have the information we need to start building our histogram. The two key features of a histogram are bins and counts.
Bins
A bin is a sub-range of values that falls within the range of a dataset. In the grocery store example, a valid bin may be from 0 hours to 6 hours. This bin includes all times from just after midnight (0) until 6 am (6).
Additionally, all bins in a histogram must be the same width.
If the range of values in our dataset is from 0 to 24, and the first bin in our grocery store example is from 0 to 6, can you figure out the minimums and maximums of the other bins?
The grocery store bins are:
0 to 6 hours
6 to 12 hours
12 to 18 hours
18 to 24 hours
"""
# Import packages
import numpy as np
import pandas as pd
# Array of days old bread
days_old_bread = np.array([0, 8, 7, 8, 0, 2, 3, 5, 6, 2])
"""
In script.py, there is an array called days_old_bread that contains values for the age of different loaves of bread in the grocery store.
Find the minimum value of the array and save it to min_days_old.
Find the maximum value of the array and save it to max_days_old.
"""
# Set the minimum and maximums of the array below
min_days_old = np.amin(days_old_bread)
max_days_old = np.amax(days_old_bread)
print("min_days_old: " + str(min_days_old))
print("max_days_old: " + str(max_days_old))
# Set the number of bins to 3
bins = 3
# Calculate the bin range
try:
bin_range = (max_days_old - min_days_old + 1) / bins
print("Bins: " + str(bins))
print("Bin Width: " + str(bin_range))
# Printing the values
except:
print("You have not set the min, max, or bins values yet.")
"""
Set the variable bins equal to 3.
When you run the code, it will output the number of bins for this histogram, and the width of these bins. In the next exercise, well figure out which values fall into each bin.
At the bottom of script.py, we calculate the bin width by subtracting min_days_old from max_days_old, adding one, then dividing by three. We must add one because there are nine possible answers from zero to eight.
"""
| true |
04c97880d4fee65117627e674f1323fd109c2854 | MarceloDL-A/Python | /14-Statistics_with_Python/Histograms/Range.py | 2,173 | 4.59375 | 5 | """
HISTOGRAMS
Range
Histograms are helpful for understanding how your data is distributed. While the average time a customer may arrive at the grocery store is 3 pm, the manager knows 3 pm is not the busiest time of day.
Before identifying the busiest times of the day, its important to understand the extremes of your data: the minimum and maximum values in your dataset. With the minimums and maximums, you can calculate the range.
The range of your data is the difference between the maximum value and the minimum value in your dataset.
range = max(data)\ -\ min(data)range=max(data) - min(data)
Exercise Class Example
In the example below, we have a NumPy array with the ages of people in an exercise class. Before looking at the data, lets think about what minimum, maximum, and range values are reasonable for a group of people in an exercise class:
The minimum cannot be below 0, because people dont have negative ages
The maximum is probably lower than 122 (the oldest person ever).
Now, lets take a look at our data.
exercise_ages = np.array([22, 27, 45, 62, 34, 52, 42, 22, 34, 26])
The minimum age in exercise_ages is 22, the maximum age is 62, and the range is 40.
You can use the following Python commands to verify this result:
min_age = np.amin(exercise_ages) # Answer is 22
max_age = np.amax(exercise_ages) # Answer is 62
age_range = max_age - min_age
"""
# Import packages
import numpy as np
import pandas as pd
# Read in transactions data
transactions = pd.read_csv("transactions.csv")
# Save transaction data to numpy arrays
times = transactions["Transaction Time"].values
cost = transactions["Cost"].values
"""
Find the minimum transaction time and save it to min_time.
Find the maximum transaction time and save it to max_time.
Find the range, and save it to range_time.
"""
# Find the minimum time, maximum time, and range
min_time = np.amin(times) # <-- Replace with min calc
max_time = np.amax(times) # <-- Replace with max calc
range_time = max_time - min_time # <-- Replace max - min
# Printing the values
print("Earliest Time: " + str(min_time))
print("Latest Time: " + str(max_time))
print("Time Range: " + str(range_time)) | true |
80b1669509b72ce5219a27ab27d7af53c0887503 | MarceloDL-A/Python | /13-Data_Visualization/Introduction_to_Matplotlib/Modify_Ticks.py | 870 | 4.125 | 4 | import codecademylib
from matplotlib import pyplot as plt
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"]
months = range(12)
conversion = [0.05, 0.08, 0.18, 0.28, 0.4, 0.66, 0.74, 0.78, 0.8, 0.81, 0.85, 0.85]
plt.xlabel("Months")
plt.ylabel("Conversion")
plt.plot(months, conversion)
#We will use ax to set the x- and y-ticks and labels to make this graph easier to read.
ax = plt.subplot()
#Using ax, set the x-ticks to be the months list.
ax.set_xticks(months)
#Set the x-tick labels to be the month_names list.
ax.set_xticklabels(month_names)
#Set the y-ticks to be [0.10, 0.25, 0.5, 0.75].
ax.set_yticks([0.10, 0.25, 0.5, 0.75])
#Label the y-ticks to be the percentages that correspond to the values [0.10, 0.25, 0.5, 0.75], instead of decimals.
ax.set_yticklabels(["10%", "25%", "50%", "75%"])
plt.show() | true |
d6c07151daabf0c745ea0b53d3309a2a5408d995 | MarceloDL-A/Python | /19-Beautiful_Soup/10_of_11_Reading_Text.py | 2,953 | 4.53125 | 5 | """
WEB SCRAPING WITH BEAUTIFUL SOUP
Reading Text
When we use BeautifulSoup to select HTML elements, we often want to grab the text inside of the element, so that we can analyze it. We can use .get_text() to retrieve the text inside of whatever tag we want to call it on.
<h1 class="results">Search Results for: <span class='searchTerm'>Funfetti</span></h1>
If this is the HTML that has been used to create the soup object, we can make the call:
soup.get_text()
Which will return:
'Search Results for: Funfetti'
Notice that this combined the text inside of the outer h1 tag with the text contained in the span tag inside of it! Using get_text(), it looks like both of these strings are part of just one longer string. If we wanted to separate out the texts from different tags, we could specify a separator character. This command would use a . character to separate:
soup.get_text('|')
Now, the command returns:
'Search Results for: |Funfetti'
"""
import requests
from bs4 import BeautifulSoup
prefix = "https://content.codecademy.com/courses/beautifulsoup/"
webpage_response = requests.get('https://content.codecademy.com/courses/beautifulsoup/shellter.html')
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
turtle_links = soup.find_all("a")
links = []
#go through all of the a tags and get the links associated with them:
for a in turtle_links:
links.append(prefix+a["href"])
#Define turtle_data:
turtle_data = {}
#follow each link:
for link in links:
webpage = requests.get(link)
turtle = BeautifulSoup(webpage.content, "html.parser")
turtle_name = turtle.select(".name")[0].get_text()
turtle_data[turtle_name] = [turtle.find("ul").get_text("|").split("|")]
print(turtle_data)
"""
After the loop, print out turtle_data. We have been storing the names as the whole p tag containing the name.
Instead, lets call get_text() on the turtle_name element and store the result as the key of our dictionary instead.
hint:
turtle_name should now be equal to something like:
turtle.select(".name")[0].get_text()
"""
"""
Instead of associating each turtle with an empty list, lets have each turtle associated with a list of the stats that are available on their page.
It looks like each piece of information is in a li element on the turtles page.
Get the ul element on the page, and get all of the text in it, separated by a '|' character so that we can easily split out each attribute later.
Store the resulting string in turtle_data[turtle_name] instead of storing an empty list there.
Hint:
At this point, the value of each turtle_data[turtle_name] should look something like:
turtle.find("ul").get_text("|")
"""
"""
When we store the list of info in each turtle_data[turtle_name], separate out each list element again by splitting on '|'.
Hint
At this point, the value of each turtle_data[turtle_name] should look something like:
turtle.find("ul").get_text("|").split("|")
"""
| true |
8e8c22f5ae1f42fafdeea4aaa32af32a85fc434e | MarceloDL-A/Python | /20-Machine_Learning_-_Supervised_Learning/5-K_Nearest_Neighbor_Regression/01_of_04_Regression.py | 2,121 | 4.46875 | 4 | from movies import movie_dataset, movie_ratings
def distance(movie1, movie2):
squared_difference = 0
for i in range(len(movie1)):
squared_difference += (movie1[i] - movie2[i]) ** 2
final_distance = squared_difference ** 0.5
return final_distance
def predict(unknown, dataset, movie_ratings, k):
distances = []
#Looping through all points in the dataset
for title in dataset:
movie = dataset[title]
distance_to_point = distance(movie, unknown)
#Adding the distance and point associated with that distance
distances.append([distance_to_point, title])
distances.sort()
#Taking only the k closest points
neighbors = distances[0:k]
total = 0
for neighbor in neighbors:
title = neighbor[1]
total += movie_ratings[title]
return total/len(neighbors)
"""
1.
Weve imported most of the K-Nearest Neighbor algorithm. Before we dive into finishing the regressor, lets refresh ourselves with the data.
At the bottom of your code, print movie_dataset["Life of Pi"]. You should see a list of three values. These values are the normalized values for the movies budget, runtime, and release year.
"""
print(movie_dataset["Life of Pi"])
"""
Print the rating for "Life of Pi". This can be found in movie_ratings.
"""
print(movie_ratings["Life of Pi"])
"""
3.
Weve included the majority of the K-Nearest Neighbor algorithm in the predict() function. Right now, the variable neighbors stores a list of [distance, title] pairs.
Loop through every neighbor and find its rating in movie_ratings. Add those ratings together and return that sum divided by the total number of neighbors.
"""
"""
4.
Call predict with the following parameters:
[0.016, 0.300, 1.022]
movie_dataset
movie_ratings
5
Print the result.
Note that the list [0.016, 0.300, 1.022] is the normalized budget, runtime, and year of the movie Incredibles 2! The normalized year is larger than 1 because our training set only had movies that were released between 1927 and 2016 Incredibles 2 was released in 2018.
"""
print(predict([0.016, 0.300, 1.022], movie_dataset, movie_ratings, 5))
| true |
1118eca63a9f6b4d06db8d7abef1851fc16bde02 | MarceloDL-A/Python | /19-Beautiful_Soup/05_of_11_Object_Types.py | 1,433 | 4.28125 | 4 | """
WEB SCRAPING WITH BEAUTIFUL SOUP
Object Types
BeautifulSoup breaks the HTML page into several types of objects.
Tags
A Tag corresponds to an HTML Tag in the original document. These lines of code:
soup = BeautifulSoup('<div id="example">An example div</div><p>An example p tag</p>')
print(soup.div)
Would produce output that looks like:
<div id="example">An example div</div>
Accessing a tag from the BeautifulSoup object in this way will get the first tag of that type on the page.
You can get the name of the tag using .name and a dictionary representing the attributes of the tag using .attrs:
print(soup.div.name)
print(soup.div.attrs)
div
{'id': 'example'}
NavigableStrings
NavigableStrings are the pieces of text that are in the HTML tags on the page. You can get the string inside of the tag by calling .string:
print(soup.div.string)
An example div
"""
import requests
from bs4 import BeautifulSoup
webpage_response = requests.get('https://content.codecademy.com/courses/beautifulsoup/shellter.html')
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
"""
Print out the first p tag on the shellter.html page.
"""
print("The first \"p tag\" on the shellter.html page: \n" + str(soup.p))
"""
Print out the string associated with the first p tag on the shellter.html page.
"""
print("The string associated with the first p tag on the shellter.html page: \n" + str(soup.p.string))
| true |
2be072ab38c419634143e9f2cc8bba6513b1368d | MarceloDL-A/Python | /14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Q1_and_Q3.py | 2,292 | 4.71875 | 5 | """
QUARTILES
Q1 and Q3
Now that weve found Q2, we can use that value to help us find Q1 and Q3. Recall our demo dataset:
[-108, 4, 8, 15, 16, 23, 42][-108,4,8,15,16,23,42]
In this example, Q2 is 15. To find Q1, we take all of the data points smaller than Q2 and find the median of those points. In this case, the points smaller than Q2 are:
[-108, 4, 8][-108,4,8]
The median of that smaller dataset is 4. Thats Q1!
To find Q3, do the same process using the points that are larger than Q2. We have the following points:
[16, 23, 42][16,23,42]
The median of those points is 23. Thats Q3! We now have three points that split the original dataset into groups of four equal sizes.
"""
dataset_one = [50, 10, 4, -3, 4, -20, 2]
#Sorted dataset_one: [-20, -3, 2, 4, 4, 10, 50]
dataset_two = [24, 20, 1, 45, -15, 40]
dataset_two.sort()
print(dataset_two)
dataset_one_q2 = 4
dataset_two_q2 = 22
"""
Find the first quartile of dataset_one and store it in a variable named dataset_one_q1.
Find the third quartile of dataset_one and store it in a variable named dataset_one_q3.
Find Q1 and Q3 of dataset_two. Store the values in variables named dataset_two_q1 and dataset_two_q3.
Hint:
Q1 will be the median of [-15, 1, 20] and Q3 will be the median of [24, 40, 45].
"""
#Define the first and third quartile of both datasets here:
dataset_one_q1 = -3
dataset_one_q3 = 10
dataset_two_q1 = 1
dataset_two_q3 = 40
#Ignore the code below here:
try:
print("The first quartile of dataset one is " + str(dataset_one_q1))
except NameError:
print("You haven't defined dataset_one_q1")
try:
print("The second quartile of dataset one is " + str(dataset_one_q2))
except NameError:
print("You haven't defined dataset_one_q2")
try:
print("The third quartile of dataset one is " + str(dataset_one_q3) + "\n")
except NameError:
print("You haven't defined dataset_one_q3\n")
try:
print("The first quartile of dataset two is " + str(dataset_two_q1))
except NameError:
print("You haven't defined dataset_two_q1")
try:
print("The second quartile of dataset two is " + str(dataset_two_q2))
except NameError:
print("You haven't defined dataset_two_q2")
try:
print("The third quartile of dataset two is " + str(dataset_two_q3))
except NameError:
print("You haven't defined dataset_two_q3")
| true |
a4181a44e4275296d819894ef81abec72d61ac10 | MarceloDL-A/Python | /14-Statistics_with_Python/Quatiles,_Quantiles,_and_Interquartile_Range/Quantiles.py | 2,260 | 4.5 | 4 | """
QUANTILES
Quantiles
Quantiles are points that split a dataset into groups of equal size. For example, lets say you just took a test and wanted to know whether youre in the top 10% of the class. One way to determine this would be to split the data into ten groups with an equal number of datapoints in each group and see which group you fall into.
Thirty students grades split into ten groups of three.
There are nine values that split the dataset into ten groups of equal size each group has 3 different test scores in it.
Those nine values that split the data are quantiles! Specifically, they are the 10-quantiles, or deciles.
You can find any number of quantiles. For example, if you split the dataset into 100 groups of equal size, the 99 values that split the data are the 100-quantiles, or percentiles.
The quartiles are some of the most commonly used quantiles. The quartiles split the data into four groups of equal size.
In this lesson, well show you how to calculate quantiles using NumPy and discuss some of the most commonly used quantiles.
Instructions
Weve imported a dataset of song lengths (measured in seconds). Weve drawn a few histograms showing different quantiles.
What do you think a histogram that shows the 100-quantiles would look like?
"""
import codecademylib3_seaborn
from song_data import songs
import matplotlib.pyplot as plt
import numpy as np
q1 = np.quantile(songs, 0.25)
q2 = np.quantile(songs, 0.5)
q3 = np.quantile(songs, 0.75)
plt.subplot(3,1,1)
plt.hist(songs, bins = 200)
plt.axvline(x=q1, c = 'r')
plt.axvline(x=q2, c = 'r')
plt.axvline(x=q3, c = 'r')
plt.xlabel("Song Length (Seconds)")
plt.ylabel("Count")
plt.title("4-Quantiles")
plt.subplot(3,1,2)
plt.hist(songs, bins = 200)
plt.axvline(x=np.quantile(songs, 0.2), c = 'r')
plt.axvline(x=np.quantile(songs, 0.4), c = 'r')
plt.axvline(x=np.quantile(songs, 0.6), c = 'r')
plt.axvline(x=np.quantile(songs, 0.8), c = 'r')
plt.xlabel("Song Length (Seconds)")
plt.ylabel("Count")
plt.title("5-Quantiles")
plt.subplot(3,1,3)
plt.hist(songs, bins = 200)
for i in range(1, 10):
plt.axvline(x=np.quantile(songs, i/10), c = 'r')
plt.xlabel("Song Length (Seconds)")
plt.ylabel("Count")
plt.title("10-Quantiles")
plt.tight_layout()
plt.show() | true |
ec29f3e59f81646bf22b6fefb780636964429175 | MarceloDL-A/Python | /14-Statistics_with_Python/Histograms/Histograms.py | 2,291 | 4.34375 | 4 | """
Histograms
While counting the number of values in a bin is straightforward, it is also time-consuming. How long do you think it would take you to count the number of values in each bin for:
an exercise class of 50 people?
a grocery store with 300 loaves of bread?
Most of the data you will analyze with histograms includes far more than ten values.
For these situations, we can use the numpy.histogram() function. In the example below, we use this function to find the counts for a twenty-person exercise class.
exercise_ages = np.array([22, 27, 45, 62, 34, 52, 42, 22, 34, 26, 24, 65, 34, 25, 45, 23, 45, 33, 52, 55])
np.histogram(exercise_ages, range = (20, 70), bins = 5)
Below, we explain each of the functions inputs:
exercise_ages is the input array
range = (20, 70) is the range of values we expect in our array. Range includes everything from 20, up until but not including 70.
bins = 5 is the number of bins. Python will automatically calculate equally-sized bins based on the range and number of bins.
Below, you can see the output of the numpy.histogram() function:
(array([7, 4, 4, 3, 2]), array([20., 30., 40., 50., 60., 70.]))
The first array, array([7, 4, 4, 3, 2]), is the counts for each bin. The second array, array([20., 30., 40., 50., 60., 70.]), includes the minimum and maximum values for each bin:
Bin 1: 20 to <30
Bin 2: 30 to <40
Bin 3: 40 to <50
Bin 4: 50 to <60
Bin 5: 60 to <70
"""
# Import packages
import numpy as np
import pandas as pd
# Read in transactions data
transactions = pd.read_csv("transactions.csv")
# Save transaction times to a separate numpy array
times = transactions["Transaction Time"].values
"""
Use the np.histogram() function to determine the busiest six hours of the day. Save the result to times_hist on line 12.
Use the following range and number of bins.
Range: 0 to 24
Bins: 4
Can you determine which six-hour period is the busiest?
Check the hint if you need help, or want to see the correct answer.
"""
# Use numpy.histogram() below
times_hist = np.histogram(times, range = (0, 24), bins = 4)
print(times_hist)
"""
Hint:
Use the np.histogram() function with times, a range 0 to 24, and 4 bins.
You should see that the store is the busiest between the hours of 18 and 24. This is between 6pm and midnight.
"""
| true |
44774e0e6115992fe42608c6da39b77fbeb94f58 | MarceloDL-A/Python | /17-Data_Cleaning_with_Pandas/Part II/08_de_12_-_Looking_at_Types.py | 1,679 | 4.375 | 4 | """
DATA CLEANING WITH PANDAS
Looking at Types
Each column of a DataFrame can hold items of the same data type or dtype. The dtypes that pandas uses are: float, int, bool, datetime, timedelta, category and object. Often, we want to convert between types so that we can do better analysis. If a numerical category like "num_users" is stored as a Series of objects instead of ints, for example, it makes it more difficult to do something like make a line graph of users over time.
To see the types of each column of a DataFrame, we can use:
print(df.dtypes)
For a DataFrame like this:
item price calories
banana $1 105
apple $0.75 95
peach $3 55
clementine $2.5 35
the .dtypes attribute would be:
item object
price object
calories int64
dtype: object
We can see that the dtype of the dtypes attribute itself is an object! It is a Series object, which you have already worked with. Series objects compose all DataFrames.
We can see that the price column is made up of objects, which will probably make our analysis of price more difficult. Well look at how to convert columns into numeric values in the next few exercises.
"""
import codecademylib3_seaborn
import pandas as pd
from students import students
print(students.head())
"""
Lets inspect the dtypes in the students table.
Print out the .dtypes attribute.
"""
print("students.dtypes: \n" + str(students.dtypes))
"""
If we wanted to make a scatterplot of age vs average exam score, would we be able to do it with this type of data?
Try to print out the mean of the score column of students.
Ans.: Return error
"""
#print(students.score.mean()) | true |
557043185e919883ce22896537949df1cb4552e5 | MarceloDL-A/Python | /15-Statistics_with_NumPy/Statistics_in_NumPy/Percentiles,_Part_II.py | 1,940 | 4.5625 | 5 | """
INTRODUCTION TO STATISTICS WITH NUMPY
Percentiles, Part II
Some percentiles have specific names:
The 25th percentile is called the first quartile
The 50th percentile is called the median
The 75th percentile is called the third quartile
The minimum, first quartile, median, third quartile, and maximum of a dataset are called a five-number summary. This set of numbers is a great thing to compute when we get a new dataset.
The difference between the first and third quartile is a value called the interquartile range. For example, say we have the following array:
d = [1, 2, 3, 4, 4, 4, 6, 6, 7, 8, 8]
We can calculate the 25th and 75th percentiles using np.percentile:
np.percentile(d, 25)
>>> 3.5
np.percentile(d, 75)
>>> 6.5
Then to find the interquartile range, we subtract the value of the 25th percentile from the value of the 75th:
6.5 - 3.5 = 3
50% of the dataset will lie within the interquartile range. The interquartile range gives us an idea of how spread out our data is. The smaller the interquartile range value, the less variance in our dataset. The greater the value, the larger the variance.
"""
import numpy as np
movies_watched = np.array([2, 3, 8, 0, 2, 4, 3, 1, 1, 0, 5, 1, 1, 7, 2])
"""
An online movie streaming company wants to know how many movies users watch in one week. At the top of the script.py, we have included sample data from 15 users in an array.
Find the 25th and 75th percentiles, and save them to the corresponding variables: first_quarter and third_quarter.
"""
first_quarter = np.percentile(movies_watched, 25)
print("first_quarter: " + str(first_quarter))
third_quarter = np.percentile(movies_watched, 75)
print("third_quarter: " + str(third_quarter))
"""
Create a variable named interquartile_range. Calculate the interquartile range and save it to this variable.
"""
interquartile_range = third_quarter - first_quarter
print("interquartile_range: " + str(interquartile_range))
| true |
1d7378dc2e5fadcb2bbc7149bd3f92c1d5f0028c | MarceloDL-A/Python | /20-Machine_Learning_-_Supervised_Learning/7-Logistic_Regression/Logistic_Regression/10_of_11_-_Feature Importance.py | 1,542 | 4.25 | 4 | import codecademylib3_seaborn
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from exam import exam_features_scaled, passed_exam_2
# Train a sklearn logistic regression model on the normalized exam data
model_2 = LogisticRegression()
model_2.fit(exam_features_scaled,passed_exam_2)
"""
Lets revisit the sklearn Logistic Regression model we fit to our exam data in the last exercise. Remember, the two features in the new model are the number of hours studied and the number of previous math courses taken.
Using the model, given to you as model_2 in the code editor, save the feature coefficients to the variable coefficients.
"""
# Assign and update coefficients
coefficients = model_2.coef_
"""
In order to visualize the coefficients, lets pull them out of the numpy array in which they are currently stored. With numpys tolist() method we can convert the array into a list and grab the values we want to visualize.
Below your original assignment of coefficients, update coefficients to equal coefficients.tolist()[0].
"""
coefficients = coefficients.tolist()[0]
"""
Create a bar graph comparing the feature coefficients with matplotlibs plt.bar() method. Which feature appears to be more important in determining whether or not a student will pass the Introductory Machine Learning final exam?
"""
# Plot bar graph
plt.bar([1,2],coefficients)
plt.xticks([1,2],['hours studied','math courses taken'])
plt.xlabel('feature')
plt.ylabel('coefficient')
plt.show()
| true |
07097ec4eebec7c04984fe26835e8c868976f17c | manika1511/interview_prep | /linked_list/palindrome.py | 2,717 | 4.40625 | 4 | """Implement a function to check if a linked list is a palindrome."""
# Node class to define linked list nodes
class Node(object):
# constructor to initialise node
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# Linkedlist class
class LinkedList(object):
#method to initialise head
def __init__(self, head=None):
self.head=head
#method to add data into the list
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head=new_node
#method to print the list nodes
def print_list(self):
start=self.head
while start != None:
print (start.data)
start=start.next
#method to find size of the linked list
def size(self):
start=self.head
size=0
while start!=None:
size=size+1
start=start.next
return size
# method to detect if a linked list is a palindrome
def palindrome(self):
slow=self.head
fast=self.head
stack = [] #stack to fill with first half of the elements
size=self.size()
while fast.next and fast.next.next:
stack.append(slow.data) #append to the list
slow = slow.next
fast = fast.next.next
stack.append(slow.data) #append the middle element
if size%2 != 0: #if odd size, middle element need not be compared, so remove it from stack
stack.pop()
slow=slow.next
while slow != None: #check the elements in stack to the end elements of the list
check=stack.pop()
if check == slow.data:
slow=slow.next
else:
return False
if len(stack) != 0:
return False
return True
def palindrome_reverse_list(self):
if self.head is None:
return True
# find mid node
fast = slow = self.head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# reverse second half
p, last = slow.next, None
while p:
next = p.next
p.next = last
last, p = p, next
# check palindrome
p1, p2 = last, self.head
while p1 and p1.data == p2.data:
p1, p2 = p1.next, p2.next
return p1 is None
def main():
l1= LinkedList()
l1.push("m")
l1.push("a")
l1.push("d")
l1.push("a")
l1.push("m")
print (l1.palindrome_reverse_list())
if __name__ == "__main__":
main()
| true |
336f51c6456087da98c1e508fec295c019f2484c | manika1511/interview_prep | /array_and_strings/is_unique.py | 1,703 | 4.34375 | 4 | """The complexity of converting a string to a set is O(n) as time to traverse a string of 'n' characters is O(n) and the time
to add it to the hash map is O(1) and the is else loop is again O(1).
Assumption: the lowercase and uppercase letters are considered same"""
def all_unique(s):
s = s.lower() #converting string to lower case
l = set(s) #converting string to set
if len(s) == len(l): #checking the length of the string and set
return "Unique"
else:
return "Not Unique"
"""Solving using no other data structure. In this bitwise operators are used to check a bit if it is present and
if the checked bit is accessed again then the string doesn't have unique letters"""
def all_unique_nods(s):
s = s.lower()
checker = 0 #taking 0 as a checker
for ch in s:
val = ord (ch) - ord ('a') #subtracting the ascii values
x = (1 << val)
y = checker & (1 << val)
if (checker & (1 << val)) > 0: #checking if the bit is already 1
return "Not Unique"
z = checker | (1 << val)
checker = checker|(1 << val) #if not already 1, then set to 1
return "Unique"
def is_unique(s):
d = dict()
for char in s:
if char in d.keys():
return "Not Unique"
else:
d[char] = 1
return "Unique"
def main():
# s = input("Enter a string: ")
# print("Result using set: " + all_unique(s))
# print("Result using no other data structure: " + all_unique_nods(s))
# print("Result using dict: " + is_unique(s))
print("Result using no other data structure: " + all_unique_nods("Manika"))
if __name__ == "__main__":
main()
| true |
f5fe31c9f62de93f9a22a16080f37fb8d37e9e8b | manika1511/interview_prep | /linked_list/partition.py | 2,083 | 4.1875 | 4 | """Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes
greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements
less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to
appear between the left and right partitions."""
# Node class to define linked list nodes
class Node(object):
# constructor to initialise node
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# Linkedlist class
class LinkedList(object):
#method to initialise head
def __init__(self, head=None):
self.head=head
#method to add data into the list
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head=new_node
#method to print the list nodes
def print_list(self):
start=self.head
while start != None:
print (start.data)
start=start.next
#method to partition list
def partition(self, k):
head= self.head #head of new list
tail=self.head #tail of new list
start = self.head #iterator for the given list
while start != None:
temp=start.next #store the address of the next node
if start.data < k: #insert at head if smaller than k
start.next=head
head=start
else:
tail.next=start #insert at tail if larger than k
tail=start
start = temp
tail.next=None #last node points to Null
new_list = LinkedList()
new_list.head=head
return new_list #return new list
def main():
l= LinkedList()
result=LinkedList()
l.push(15)
l.push(14)
l.push(16)
l.push(15)
l.push(15)
l.push(14)
l.push(18)
l.print_list()
print("--------")
result=l.partition(15)
result.print_list()
if __name__ == "__main__":
main()
| true |
901a0be5cbea7c9f0ee6294e5950ab2550e392d5 | nathan5280/ndl-tools | /src/ndl_tools/list_sorter.py | 2,910 | 4.21875 | 4 | """
ListSorters used to control if and how Lists are sorted. Really there are only two
choices. Sort or don't sort. The sorter can be applied to the List elements by
the Selector that is associated with the sorter.
"""
from abc import abstractmethod
from pathlib import Path
from typing import List, Optional, Union
from .selector import BaseSelector, SELECTORS
class NotSortedError(Exception):
"""The sorter was not applied to the list."""
class BaseListSorter:
"""
Base list sorter implements the chaining logic.
"""
def __init__(
self, selectors: SELECTORS = None,
):
"""
Initialize the sorter with optional parent sorter and selector.
:param selectors: Optional selectors to use to select which
elements this sort runs.
"""
if selectors:
self._selectors = selectors if isinstance(selectors, list) else [selectors]
else:
# No selectors specified
self._selectors = None
@staticmethod
def sorted(
list_: List, path: Path, sorters: Optional[List["BaseListSorter"]] = None
) -> List:
"""
Run all the sorters until one applied to sort or not sort the list.
:param list_: List to sort.
:param path: Path to the element.
:param sorters: List of sorters to use to sort the lists.
:return: Sorted list.
"""
if not sorters:
return sorted(list_)
for sorter in sorters:
if BaseSelector.match(path, sorter._selectors):
try:
return sorter._sorted(list_)
except NotSortedError:
continue
return sorted(list_)
@abstractmethod
def _sorted(self, list_: List) -> List:
"""
Prototype for the core sorting logic implemented in the subclass.
:param list_: List to sort.
:return: Sorted list.
"""
pass # pragma: no cover
LIST_SORTERS = Optional[Union[BaseListSorter, List[BaseListSorter]]]
class DefaultListSorter(BaseListSorter):
def __init__(
self, *, selectors: SELECTORS = None,
):
"""
Standard Python sorted() sorter.
:param selectors: Optional list of selectors to use to select which
elements this sort runs.
"""
super().__init__(selectors)
def _sorted(self, list_: List) -> List:
"""Default Python sorted()."""
return sorted(list_)
class NoSortListSorter(BaseListSorter):
def __init__(
self, *, selectors: SELECTORS = None,
):
"""
No Op sorter.
:param selectors: Optional list of selectors to use to select which
elements this sort runs.
"""
super().__init__(selectors)
def _sorted(self, list_: List) -> List:
"""No Op sort."""
return list_
| true |
c472563f3f05f70fa12cbf772f3d8deacf2f2424 | Fiinall/UdemyPythonCourse | /Embaded Functions/zipFunction.py | 997 | 4.21875 | 4 | """
Combining lists into one list.
"""
liste1 = [1, 2, 3, 4, 5]
liste2 = [6, 7, 8, 9, 10, 11]
liste3 = ["Python","Php","Java"]
# sonucu [(1,6),(2,7),(3,8),(4,9),(5,10)] yapmaya çalışalım.
#-------without zip funciton-----
i = 0
sonuç = list()
while (i < len(liste1) and i < len(liste2)):
sonuç.append((liste1[i], liste2[i]))
i += 1
print(sonuç)
#-------------------------------
#---- with zip function---------
list3 = zip(liste1,liste2)
print(list(list3))
print(list(zip(liste1,liste2,liste3)))
#--------------------------------------------#
## Aynı anda iki liste üzerinde gezinmek
liste1 = [1,2,3,4]
liste2 = ["Python","Php","Java","Javascript"]
for i,j in zip(liste1,liste2):
print("i:",i,"j:",j)
# Sözlükleri zipleyelim.
sözlük1 = {"Elma":1,"Armut":2,"Kiraz":3}
sözlük2 = {"Sıfır":0,"Bir":1,"İki":2}
print(list(zip(sözlük1,sözlük2))) # Anahtarlar eşleşti
print(list(zip(sözlük1.values(),sözlük2.values()))) # Değerler eşleşti
| false |
b14de33186c8d3f6d2f3b07602d41e34d40633cd | Fiinall/UdemyPythonCourse | /Conditional Statement/Hesap Makinesi.py | 1,023 | 4.3125 | 4 | print("""Welcome to Calculator
Here are the operations that you can do
1. Summation
2. Extraction
3. Multiplication
4. Division
Please Selecet the Operatiıon with + , - , * or /
""")
First_Number = float(input("What is your first number"))
Operation = input("What is your Operator")
Second_Number = float(input("What is the second number"))
if (Operation == "+"):
Conclusion = First_Number + Second_Number
print(
Conclusion
)
elif (Operation == "-"):
Conclusion = First_Number - Second_Number
print("{} ile {}'nın farkı {}'dır".format(
First_Number, Second_Number, Conclusion
)
)
elif (Operation == "*"):
Conclusion = First_Number * Second_Number
print(
Conclusion
)
elif (Operation == "/"):
Conclusion = First_Number / Second_Number
print(
Conclusion
)
else:
print("Düzdün gir lan işlemi")
print("For Now: You can calculate for once. For better apps please wait :) ") | false |
c2aa28ef1639e050fe92756f1a7c6834d69b75f5 | Fiinall/UdemyPythonCourse | /Advanced Data Structures and Object/AdvancedListsAndItsMethods.py | 2,397 | 4.625 | 5 | # extend() method is like append method but this help you for add whole list into another list;
print("extend method; \n")
list1 = [1,2,3,4]
list2 = [45,6893,245,667,"asd"]
list1.extend(list2)
print(list1)
print("---------")
# insert(index,element) method inserts an element into specified index
print("insert method; \n")
list3 = [1,3,6,"sdf",425,35]
print(list3)
list3.insert(0,"Zeroth index")
list3.insert(3,"3rd index")
print(list3)
print("------------")
# pop() method does two work
# 1. subtract index
# 1.1 if not specified it subtracts last index
# 1.2 if specified, it subtracts specified index
# 2. returns substracted index
list4 = [1,2,3,4,5,6,"asd",7,8]
print("pop method; \n")
list4.pop() # last index 8 is gone
print(list4.pop(4)) # 4. index 5 is gone and printed
list4.pop(2) # 2nd index 3 is gone
print(list4)
print("------------")
# remove method removes specified element of list with it string
# remove method required just element, not index
print("remove method;\n")
list5 = [1,2,4,"final",5]
print(list5)
list5.remove(2) # it removes element 2 , not 2nd index. As you can see 2nd index 4 is still in list
list5.remove("final")
print(list5)
print("---------")
print("index method;\n")
#index method search for whatever you want to find and returns its index.
#If you specified the method starts from an index to search
list6 = [23,56,23,100,78,225,8,100,235,9,34,3675,1,45,36,100,575,233]
print(list6.index(100)) # Start search from beginning for 100 and stop when first encounter.
print(list6.index(100,5)) # Start search from 5. index for 100 and stop when first encounter.
# in list6 100 element first comes up 3rd index and second time comes up on 7th index
print("----------")
#count method counts an element for how mant times exist in list // Bu ne biçim ingiliççe
print("count method; \n")
list7 = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]
print("list7 has {} times 1".format(list7.count(1)))
print("------------")
# sort() metodu
# sort() metodu bir listenin elemanlarını sayıysa küçükten büyüğe , string ise alfabetik olarak sıralar.
# Eğer özellikle içine reverse = True değeri verilirse elemanları büyükten küçüğe sıralar.
print("sort method; \n")
list6.sort()
print(list6)
list6.sort(reverse=True)
print(list6)
list8 = ["Aston Martin","BWM","Mercedes","Lamborghini",]
list8.sort()
print(list8)
list8.sort(reverse=True)
print(list8)
# --- The End --- | true |
3ae1a7a089d9054ca47a6412d6834d35be1448de | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter1/1.9.py | 582 | 4.4375 | 4 |
#String Rotation; Assume you have a method i s S u b s t r i n g which checks if one word is a substring of another.
#Given two strings, si and s2, write code to check if s2 is a rotation of si using only one call to isSubstring
# [e.g., "waterbottle" is a rotation oP'erbottlewat"),
def string_rotation(s1, s2):
if len(s1) != len(s2):
return False
else:
return s1 in (s2 + s2) #lets say we are calling substring like substring(s1,s2+s2)
def main():
print(string_rotation('waterbottle','erbottlewat'))
if __name__ == "__main__":
main()
| false |
037c3372719b206f9694da97f36e528b366a037a | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter5/5.1.py | 881 | 4.28125 | 4 | #5.1
#Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and j.
#Write a method to insert M into N such that M starts at bit j and ends at bit i.
#You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011,
# you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.
def Insertion(N,M,i,j):
if i>j or i<0 or j>=32:
return False
#First of all I need to clear bits through i to j to insert M into N
mask1 = 1<<i
mask2 = 1<<j+1
mask = (mask2 - mask1)
N_cleared = N & ~(mask)
M_shifted = M << i
return N_cleared | M_shifted
def main():
N = 0b10000000000
M = 0b10011
i =2
j = 6
print(Insertion(N,M,i,j))
if __name__ == "__main__":
main()
| true |
cf3fb2b8852de85b47b3aa67a3ae8e48b2607e76 | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter4/4.3.py | 2,560 | 4.125 | 4 | #List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth
#(e.g., if you have a tree with depth 0, you'll have 0 linked lists).
from SinglyLinkedList import SinglyLinkedList
class Node():
def __init__(self,value):
self.right = None
self.left = None
self.value = value
self.lists = []
class BinaryTree():
def __init__(self):
self.binary_tree = []
self.root = None
def add(self,value):
new_node = Node(value)
if(len(self.binary_tree) == 0):
self.binary_tree.append(new_node)
self.root = new_node
else:
current = self.root
while(current != None):
if(value > current.value):
if(current.right == None):
current.right = new_node
break
else:
current = current.right
else:
if(current.left == None):
current.left = new_node
break
else:
current = current.left
def make_it_array(self,node):
if(node != None):
self.binary_tree.append(node.value)
self.make_it_array(node.left)
self.make_it_array(node.right)
def print_my_tree(self):
for i in range(len(self.binary_tree)):
print(self.binary_tree[i])
def create_level_ll(self,root):
result = [] #lis of linkedlists
current = SinglyLinkedList()
if(root != None):
current.insert_node(root)
while(current.get_size()>0):
result.append(current)
parents = SinglyLinkedList()
parents = current
current = SinglyLinkedList()
parent = parents.head
while(parent is not None):
if parent.left != None:
current.insert_node(parent.left)
if parent.right != None:
current.insert_node(parent.right)
parent = parent.next
return result
def main():
my_binary_tree = BinaryTree()
my_binary_tree.add(1)
my_binary_tree.add(3)
my_binary_tree.add(0)
my_binary_tree.add(6)
my_binary_tree.add(4)
#my_binary_tree.make_it_array(my_binary_tree.root)
#my_binary_tree.print_my_tree()
my_binary_tree.create_level_ll(my_binary_tree.root)
if __name__ == '__main__':
main()
| true |
16c9d17f9c4cfd8f8002434d9b810182f4128b1f | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter1/1.4.py | 1,477 | 4.34375 | 4 | #Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
#A palindrome is a word or phrase that is the same forwards and backwards.
#A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
#First I need to preprocess the strings to eliminate things like case and spaces so we can just focus on the letters that
#are present in the string
def is_perm_plindrome(string):
#Deal with case
input_string = string.lower()
#Deal with spaces
input_string = input_string.replace(" ", "")
my_dict = dict() #the syntax is: mydict[key] = "value" --> mydict[t] = 2
for char in input_string: #Adding values as how many time that key is occured
if char in my_dict:
my_dict[char] +=1
else:
my_dict[char] = 1
#Algorithm works like this : If we have ANNA OR TACT COA --> HER harften iki tane veya toplam bir hafrten 1 tane var eger boyle olursa perm of palindrome
even_ctr = 0
one_ctr = 0
odd_ctr = 0
for key, value in my_dict.items():
if value%2 == 0:
even_ctr+=1
elif value == 1:
one_ctr+=1
else:
odd_ctr+=1
if(one_ctr>1 or odd_ctr>0):
return False
else:
return True
def main():
my_string = 'This is not a palindrome permutation'
print(is_perm_plindrome(my_string ))
if __name__ == '__main__':
main()
| true |
6fd6268052ce61de5d97fcf138e7ff611fadc1ad | mattfisc/python | /quicksort.py | 1,383 | 4.125 | 4 | # This function takes first element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
import random
def partition(lst, a ,b):
random_index = random.randint(a,b) # pick random index, its value will be our # pivot val
lst[b], lst[random_index] = lst[random_index], lst[b] # swap the value with # lst[b]
pivot = a # run the rest of the partition code as it was in the original # version
for i in range(a,b):
if lst[i] < lst[b]:
lst[i],lst[pivot] = lst[pivot],lst[i]
pivot += 1
lst[pivot],lst[b] = lst[b],lst[pivot]
return pivot
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr,low,high):
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr,low,high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
# code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
print (arr)
| true |
99d7bceef1cd86093a076d4eba62beb240b06c6b | mihawkeyes/practice-pro | /python/sieveofsundaram.py | 1,101 | 4.625 | 5 | # Python3 program to print
# primes smaller than n using
# Sieve of Sundaram.
# Prints all prime numbers smaller
def SieveOfSundaram(n):
# In general Sieve of Sundaram,
# produces primes smaller
# than (2*x + 2) for a number
# given number x. Since we want
# primes smaller than n, we
# reduce n to half
nNew = int((n - 1) / 2);
# This array is used to separate
# numbers of the form i+j+2ij
# from others where 1 <= i <= j
# Initialize all elements as not marked
marked = [0] * (nNew + 1);
# Main logic of Sundaram. Mark all
# numbers of the form i + j + 2ij
# as true where 1 <= i <= j
for i in range(1, nNew + 1):
j = i;
while((i + j + 2 * i * j) <= nNew):
marked[i + j + 2 * i * j] = 1;
j += 1;
# Since 2 is a prime number
if (n > 2):
print(2, end = " ");
# Print other primes. Remaining
# primes are of the form 2*i + 1
# such that marked[i] is false.
for i in range(1, nNew + 1):
if (marked[i] == 0):
print((2 * i + 1), end = " ");
# Driver Code
n = 50;
SieveOfSundaram(n);
# This code is contributed by mits
| true |
826550ee62029fff7f61bf987598ee0125413a49 | tsamridh86/RSA | /decryptor.py | 1,387 | 4.375 | 4 | # this code converts cipher text into msg & displays it to the user
# this functions converts the cipherText into number format plainText
def decrypt( cipherText, publicKey, divisorKey , blockSize):
i = 0
lenCipherText = len(cipherText)
plainText = []
while i < lenCipherText:
copyBlockSize = blockSize
numArr = []
numBuff = pow(cipherText[i],publicKey,divisorKey)
while copyBlockSize > 0:
numArr.append(numBuff%96)
copyBlockSize = copyBlockSize - 1
numBuff = numBuff // 96
for j in range(blockSize):
plainText.append(numArr[j])
i = i + 1
return plainText
# this is the reverse of the text to number converter that is used in the encryptor
def convertIntoText( numericText ):
string = []
for number in numericText:
string.append(chr(number+32))
string = ''.join(string)
return string
#take input from the cipherText.txt
cipherTextFile = open("cipherText.txt","r")
cipherText = [int(x.strip("\n")) for x in cipherTextFile.readlines()]
cipherTextFile.close()
publicKey = int(input("Enter public key : "))
divisorKey = int(input("Enter divisor key : "))
blockSize = int(input("Enter preffered blockSize : "))
plainText = decrypt(cipherText,publicKey,divisorKey,blockSize)
plainText = convertIntoText(plainText)
print ("Your PlainText : ")
print (plainText)
plainTextFile = open("plainText.txt","w")
plainTextFile.write(plainText)
plainTextFile.close() | true |
b733170325793d63b2db089bb0a4a31dd5d36c55 | dimaape/GeekBrains_Python_Course | /Lesson_1/GB_Py_HW_1_1.py | 1,252 | 4.34375 | 4 | # Задание 1.1
# Поработайте с переменными, создайте несколько, выведите на экран
print("Поработайте с переменными, создайте несколько, выведите на экран.\n")
var_a = 0
var_b = "some text"
var_c = 10
var_d = "some text again"
print(var_a, var_b, var_c, var_d, sep='\n')
# Запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
print("\nЗапросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.\n" +
"Нет обработчика ошибок. Но это и не в данном уроке.\n")
user_input_int_a = int(input("Please provide any integer:\n--> "))
user_input_float_a = float(input("Please provide any float number:\n--> "))
user_input_str_a = str(input("Please provide any string:\n--> "))
user_input_str_b = str(input("Please provide another string:\n--> "))
print(user_input_int_a, user_input_float_a, user_input_str_a, user_input_str_b, sep='\n')
| false |
e6fd95ce117cb9035049aac5bc970dbf7a08f9e3 | icadev/Python-Projects | /ex2.py | 691 | 4.46875 | 4 | print "I will now count my chickens:"
print "Hens", 2.5 + 3.0 / 6.0 #make the operation
print "Roosters", 10.0 - 2.5 * 3.0 % 4.0 #make the operation
print "Now I will count the eggs:"
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0 #make the operation
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?"
print 3.0 + 2.0 < 5.0 - 7.0 #respond on line 10 with true or false
print "What is 3.0 + 2.0?", 3.0 + 2.0
print "What is 5.0 - 7.0?", 5.0 -7.0
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5.0 > -2.0 #turns true or false
print "Is it greater or equal?", 5.0 >= -2.0
print "Is it less or equal?", 5.0 <= -2.0 | true |
b1437f271f59cca4f92fb6e111a96f2579bdb93a | icadev/Python-Projects | /my_game.py | 1,628 | 4.40625 | 4 | class Person:
"""Represents a robot, with a name."""
# A class variable, counting the number of robots
population = 0
def __init__(self, name, age, job):
"""Initializes the data."""
self.name = name
self.age = age
self.job = job
print("(Presenting yourself {})".format(self.name))
# When this person is created, the person
# adds to the population
Person.population += 1
def die(self):
"""I am dying."""
print("{} is dying!".format(self.name))
Person.population -= 1
if Person.population == 0:
print("{} was the last one.".format(self.name))
else:
print("There are still {:d} persons working.".format(
Person.population))
def say_hi(self):
"""Greeting by the person.
Yeah, they can do that."""
print("Greetings, my name is {}, I'm {} years old and I'm working as {}.".format(self.name, self.age, self.job))
@classmethod
def how_many(cls):
"""Prints the current population."""
print("We have {:d} persons.".format(cls.population))
person1 = Person("John", 37, "freelancer")
person1.say_hi()
Person.how_many()
person2 = Person("Eve", 27, "economist")
person2.say_hi()
Person.how_many()
person3 = Person("Michael", 32, "professor")
person3.say_hi()
person3.how_many()
print("\nPersons can do some work here.\n")
print("Persons have finished their work. So let's wait them to die.")
person1.die()
person2.die()
person3.die()
Person.how_many() | true |
47b5e7d992beeeae927c07f8ddfcdbdbefa6d345 | SudheshSolomon1992/Hackerrank_30_days_Coding_Challenge | /Day_7_Arrays.py | 360 | 4.34375 | 4 | #!/bin/python3
def main():
number_of_elements = int(input())
element = [int(n) for n in input().split()[:number_of_elements]]
reverse(element)
def reverse(array):
# reversed function is used to reverse an array in python3
for element in reversed(array):
print (element, end=" ")
if __name__ == "__main__":
main()
| true |
0b5051386fd85a67cf88c88cabb2d63d1f954bbe | Tbeck202/PythonCourse | /VariablesAndStrings/converter.py | 207 | 4.34375 | 4 | print("Enter a distance in Kilometers, and I'll convert it to miles!")
kms = input()
miles = float(kms)/1.60934
round_miles = round(miles, 2)
print(f"Ok, {kms} kilometers are equal to {round_miles} miles!")
| true |
22c960b54ebe64b8083645821782ad6852c4436c | Tbeck202/PythonCourse | /Tuples_and_sets/sets.py | 1,202 | 4.15625 | 4 | # cities = ['Los Angeles', 'Boulder', 'Kyoto', 'Florence', 'Santiago',
# 'Los Angeles', 'Shanghai', 'Boulder', 'San Francisco', 'Oslo', 'Tokyo']
# no_duplicates = set(cities)
# # print(no_duplicates)
# no_duplicates.add('Portland')
# print(no_duplicates)
# no_duplicates.remove('Shanghai')
# print(no_duplicates)
# ============================
# math_students = {"Matt", "Helen", "Prashant", "James", "Aparna"}
# biology_students = {"Jane", "Matt", "Charlotte", "Mesut", "Oliver", "James"}
# all_students = math_students | biology_students
# print(all_students)
# dual_students = math_students & biology_students
# print(dual_students)
# =======================
# COMPREHENSION
# print({x**2 for x in range(10)})
# print({x: x**2 for x in range(10)})
user_string = input("Type a word, homie!\n")
vowel_check = len({char for char in user_string if char in 'aeiou'})
if vowel_check == 5:
print(f"{user_string} has all five vowels in it!")
elif vowel_check > 1:
print(f"{user_string} has {vowel_check} unique vowels in it.")
elif vowel_check == 1:
print(f"{user_string} has {vowel_check} unique vowel in it.")
else:
print(f"{user_string} has no unique vowels in it.")
| false |
cc0cc27653fcbe55bc65ecca72da02037956b473 | DharmilShahJBSPL/DharmilShah | /python/dictionary_ex.py | 620 | 4.5 | 4 | print('using Dictionary example')
print('')
di={'abc':'1','x':'2','jkl':'3'}
print (di)
print(di.keys())
print(di.values())
print('to print particaular value of key then use this ')
print(di['abc'])
print(di['jkl'])
print('')
print('')
print('to print more than 1 key value then use this ')
print((di['abc']),(di['jkl']))
print('')
print(di.get('abc'))
print('')
print('to print whole dictionary use this ')
print(di.items())
print('')
di2=(di.copy())
print('use of the copy function')
print(di2)
print('')
print('setting new value to key temporary ')
print(di.fromkeys('x','demo'))
print('')
print(di.values())
| true |
a8674b4146e7fb058d70e0e1900a14d2b4f0042e | DiegoC386/Algoritmos_Diego | /Taller Estructuras de Control Selectivas/Ejercicio_9.py | 2,123 | 4.3125 | 4 | """
En una tienda efectúan un descuento a los clientes dependiendo del monto de la compra.
El descuento se efectúa con base en el siguiente criterio:
a. Si el monto es inferior a $50.000 COP, no hay descuento.
b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive,
se hace un descuento del 5%.
c. Si está comprendido entre $100.000 COP y $700.000 COP inclusive,
se hace un descuento del 11%.
d. Si está comprendido entre $700.000 COP y $1.500.000 COP inclusive,
el descuento es del 18.
e. Si el monto es mayor a $15000, hay un 25% de descuento.
Calcule y muestre el nombre del cliente, el monto de la compra, monto a pagar
y descuento recibido.
"""
Nombre=input("Ingrese su nombre: ")
Compra=int(input("Ingrese Precio de la Compra: "))
if(Compra>0 and Compra<50000):
print("Nombre del cliente: "+ str(Nombre))
print("Monto de la compra: $ {:.0f}".format(Compra))
print("No hay descuento")
print("Monto a Pagar: $ {:.0f}".format(Compra))
elif(Compra>=50000 and Compra<100000):
Desc=(Compra*0.05)
MontoPagar=(Compra-Desc)
print("Nombre del cliente: "+ str(Nombre))
print("Monto de la compra: $ {:.0f}".format(Compra))
print("Descuento Recibido: $ {:.0f}".format(Desc))
print("Monto a Pagar: $ {:.0f}".format(MontoPagar))
elif(Compra>=100000 and Compra<700000):
Desc=(Compra*0.11)
MontoPagar=(Compra-Desc)
print("Nombre del cliente: "+ str(Nombre))
print("Monto de la compra: $ {:.0f}".format(Compra))
print("Descuento Recibido: $ {:.0f}".format(Desc))
print("Monto a Pagar: $ {:.0f}".format(MontoPagar))
elif(Compra>=700000 and Compra<1500000):
Desc=(Compra*0.18)
MontoPagar=(Compra-Desc)
print("Nombre del cliente: "+ str(Nombre))
print("Monto de la compra: $ {:.0f}".format(Compra))
print("Descuento Recibido: $ {:.0f}".format(Desc))
print("Monto a Pagar: $ {:.0f}".format(MontoPagar))
elif(Compra>=1500000):
Desc=(Compra*0.25)
MontoPagar=(Compra-Desc)
print("Nombre del cliente: "+ str(Nombre))
print("Monto de la compra: $ {:.0f}".format(Compra))
print("Descuento Recibido: $ {:.0f}".format(Desc))
print("Monto a Pagar: $ {:.0f}".format(MontoPagar))
else:
print("ERROR")
| false |
5b4841a57f777204f1a4a2235901b6c0ce723858 | tlofreso/adventofcode2020 | /01/expense_report.py | 1,284 | 4.1875 | 4 |
def values():
"""Reads input, and returns all values as a sorted list of integers"""
with open('input.txt') as f:
lines = f.read().splitlines()
my_input = [int(i) for i in lines]
my_input.sort()
return my_input
def computer():
result = 2020
n1_possible = []
n2_possible = []
# Get possible first and second operators
for num in values():
if num <= result / 2:
n1_possible.append(num)
else:
n2_possible.append(num)
# Crunch result
for n1 in n1_possible:
for n2 in n2_possible:
if n1 + n2 == result:
solution1 = n1 * n2
return solution1, n1_possible, n2_possible
def computer2():
result = 2020
n1_n2 = computer()[1]
n3 = computer()[2]
possible = []
for n1 in n1_n2:
for n2 in n1_n2:
if n1 + n2 <= result / 2:
possible_operators = [n1, n2]
possible.append(possible_operators)
for n1 in possible:
for n2 in n3:
if sum(n1) + n2 == result:
solution2 = n1[0] * n1[1] * n2
return solution2
if __name__ == "__main__":
answer1 = computer()[0]
print(answer1)
answer2 = computer2()
print(answer2)
| true |
00f75399b13208b8b2c648c978fb08065306f427 | OffensiveCyber/Learn_Python_the_practical_way | /T2_List.py | 1,063 | 4.5625 | 5 | cars = ['nissan', 'ford', 'honda','tesla', 'Volkswagen']
#print all cars name from the list
print cars[0]
print cars[1]
print cars[2]
print (cars[3].title()) #title() method displays word with first letter in caps
print "Hello " + cars[0] + ", What is your milage?" #concetation demonstrated
print "Hello " + cars[1] + ", What is your milage?"
print "Hello " + (cars[2].title()) + ", What is your milage?"
cars.append('Ferrari') #append to list
print "1"
print cars
cars[2] = "suzuki" #3rd element from list is replaced
print "2"
print cars
cars.insert(2, 'honda') #Add new element in between the list
print "3"
print cars
del cars[3] #delete item from list by its index number
print "4"
print cars
popped = cars.pop() #removed last item from list but lets you work with it. 'popped' is just a variable here.
print "5"
print cars
print "Item removed from list is: " + popped
honda_comes_before = cars.pop(3) #popped middle item from list
print "6"
print cars
print "honda used to come before: " + honda_comes_before + " in list"
| true |
36d59d8a1a2efc18dba383797d90efbbf4bed1ee | thecoderarnav/C-98 | /counting.py | 340 | 4.28125 | 4 | def countingwords():
fileName = input("ENTER FILE NAME")
numberofcharacters = 0
file= open(fileName,"r")
for line in file:
data = file.read()
#words = line.split()
numberofcharacters = len(data)
print ("Number of Characters")
print(numberofcharacters)
countingwords()
| true |
bcd2e33743c0415435f74f87b1c32ba9f3450e72 | chyidl/leetcode | /0098-validate-binary-search-tree/validate-binary-search-tree.py | 1,442 | 4.21875 | 4 | # Given the root of a binary tree, determine if it is a valid binary search tree (BST).
#
# A valid BST is defined as follows:
#
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
#
#
#
# Example 1:
#
#
# Input: root = [2,1,3]
# Output: true
#
#
# Example 2:
#
#
# Input: root = [5,1,4,null,null,3,6]
# Output: false
# Explanation: The root node's value is 5 but its right child's value is 4.
#
#
#
# Constraints:
#
#
# The number of nodes in the tree is in the range [1, 104].
# -231 <= Node.val <= 231 - 1
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# Solution: In-order 中序遍历 -- 升序
inorder = self.inorder(root)
return inorder == list(sorted(set(inorder)))
def inorder(self, root):
if root is None:
return []
# 左 根 右
return self.inorder(root.left) + [root.val] + self.inorder(root.right)
# Solution: Recurision: 递归函数
# 左子树取最大值 max 右子树取最小值 min
# 判断 max < root; root > min
| true |
e7df3aa457b5bdcfa8b0e8c35b431f31313c886e | septos/learnpython | /sets.py | 705 | 4.21875 | 4 | '''
Sets
1.Unordered
2.Unindexed
3.newset = {orange,banana,fig}
'''
new_fruits = {"lemon","fig","cherry"}
print(new_fruits)
print("-------------------------------------------------------------------------------")
#for loop
for x in new_fruits:
print(x)
print("-------------------------------------------------------------------------------")
#add value
new_fruits.add("orange")
print(new_fruits)
new_fruits.update(["mango","grape"])
print(new_fruits)
print(len(new_fruits))
print("-------------------------------------------------------------------------------")
#remove
new_fruits.remove("fig")
print(new_fruits)
#remove = pop
x = new_fruits.pop()
print(x)
new_fruits.clear()
print(new_fruits)
| true |
81a03cfdb9a4d88e8ad179c7b7d357a34a08e02d | learning-laboratory/cursos | /python/open-source-it/pratice/exercise_03.py | 370 | 4.125 | 4 | age = int(input('Age: '))
gender = input('Genger[M/F]: ')
gender = gender.upper()
if age < 18:
if gender == 'M':
print('son')
else:
print('daughter')
elif 18 <= age < 65:
if gender == 'M':
print('father')
else:
print('mother')
else:
if gender == 'M':
print('grandfather')
else:
print('grandmother') | false |
e926d5b9a9f8e73cf5e0277853d7414fee12a5dc | navaneeth2324/256637_DailyCommits | /secondsmallest.py | 245 | 4.1875 | 4 | # Write a Python program to find the second smallest number in a list
list=[]
n=int(input("Size of list : "))
for i in range(0,n):
item=int(input())
list.append(item)
print("List : ",list)
list.sort()
print("Second Smallest :",list[1]) | true |
2c7f55a161747f33675e72d3d60d4464640521a2 | Michal-Kok/WAR2021 | /python tasks/chris.py | 813 | 4.25 | 4 | def name_in_str(sentence, name):
return
"""
Simple as that, your task is to find name within given sentence, like in the example:
Across the rivers. --- chris
c h ri s
Make it case sensitive.
Letters must appear in the right order.
"""
assert name_in_str("Across the rivers", "chris") is True
assert name_in_str("Next to a lake", "chris") is False
assert name_in_str("Under a sea", "chris") is False
assert name_in_str("A crew that boards the ship", "chris") is False
assert name_in_str("A live son", "Allison") is False
assert name_in_str("Just enough nice friends", "Jennifer") is False
assert name_in_str("thomas", "Thomas") is True
assert name_in_str("pippippi", "Pippi") is True
assert name_in_str("pipipp", "Pippi") is False
assert name_in_str("ppipip", "Pippi") is False
print('noice')
| true |
b237e9da29896ffa0fee894b8d81d2cbb20bbec9 | AndresNunezG/ejercicios_python_udemy | /ejercicio_16.py | 570 | 4.34375 | 4 | """
Ejericio 16.
- Solicitar al usuario un texto o cadena de caracteres
- Devolver en pantalla el texto de entrada al revés:
Ej:
Entrada: 'hola'
Salida: 'aloh'
"""
#Solicitar texto al usuario
print('Ingrese el texto a ser invertido!')
texto = input('')
#Invertir el texto
#Método 1.
texto_inv = texto[::-1]
print('El texto invertido mediante el método 1 es: ', texto_inv)
print('\n')
#Método 2.
texto_inv = ''
for letra in texto:
texto_inv = letra + texto_inv
print('El texto invertido mediante el método 2 es: ', texto_inv)
print('\n') | false |
cf37e6f4fd508e8ff33efd07e80e64fcf84af3ee | shaheryarshaikh1011/tcs_prep | /prime.py | 565 | 4.125 | 4 | lower = int(input("Enter Lower bound of the range"))
upper = int(input("enter Upperbound of the range"))
print("Prime numbers between", lower, "and", upper, "are:")
#initialize variable to store sum of prime numbers
sum=0;
for num in range(lower + 1, upper ):
# all prime numbers are greater than 1
if num == 1:
break;
else:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
sum=sum+num;
print("Sum of prime numbers between ",lower," and ",upper," is ",sum) | true |
d557718e840f2b0e9e3e7dd7fe350649122e02a3 | leosantosx/exercicios-em-python | /exercicios/ex87.py | 1,057 | 4.1875 | 4 | """
EXERCÍCIO 087: Mais Sobre Matriz em Python
Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
0 [_][_][_]
1 [_][_][_]
2 [_][_][_]
0 1 2
"""
line = int(input('Quantas linhas tem a Matriz? '))
column = int(input('Quantas colunas tem a matriz? '))
matriz = [[] for x in range(0,line)]
for i in range(0, line):
for j in range(0, column):
matriz[i].append(int(input(f'Digite [ a{i+1}{j+1} ]: ')))
print('\nMatriz: ')
soma_pares = soma_column3 = maior = 0
for a in matriz:
for pos,num in enumerate(a):
if num % 2 == 0:
soma_pares += num
if pos == 2:
soma_column3 += num
print(f'[ {num:^5} ]', end=' ')
print()
print(f'A soma dos pares é: {soma_pares}')
if column >= 3:
print(f'A soma da terceira coluna é {soma_column3}')
if line >= 2:
maior = max(matriz[1])
print(f'O maior valor da segunda linha é {maior}')
| false |
8fa3df7a5aea16aaf2b22007b378947ca0868977 | leosantosx/exercicios-em-python | /exercicios/ex77.py | 562 | 4.125 | 4 | """
EXERCÍCIO 077: Contando Vogais em Tupla
Crie um programa que tenha uma tupla com várias palavras (não usar acentos).
Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.
"""
palavras = ('Mercado','morango', 'banana',
'Notebook', 'carro', 'celular')
for palavra in palavras:
palavra = palavra.upper()
print(f'Na palavra {palavra} temos:',end='')
for letra in palavra:
if letra in 'AEIOU':
print(letra, end='')
print('\n')
| false |
e0b2da770c4f6765119b599ea4812323b8598f00 | leosantosx/exercicios-em-python | /exercicios/ex74.py | 532 | 4.1875 | 4 | """
EXERCÍCIO 074: Maior e Menor Valores em Tupla
Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla.
Depois disso, mostre a listagem de números gerados e também indique o menor e o
maior valor que estão na tupla.
"""
from random import randint
numeros = (randint(0,9),randint(0,9),randint(0,9),
randint(0,9),randint(0,9))
print(f'Números gerados: ', end=' ')
for n in numeros:
print(n, end=' ')
print(f'\nO número maior é {max(numeros)} e o menor é {min(numeros)}')
| false |
1ff8f127e7d8de6397cfab3db966ec1967b8f6f2 | leosantosx/exercicios-em-python | /exercicios/ex36.py | 699 | 4.15625 | 4 | """
DESAFIO 036: Aprovando Empréstimo
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
A prestação mensal não pode exceder 30% do salário, ou então o empréstimo será negado.
"""
casa = float(input('Qual o valor da casa: R$'))
salario = float(input('Qual o seu salário: R$'))
anos = int(input('Quantos anos irá pagar: '))
minimo = (salario * 30) / 100
parcelas = casa / (anos * 12)
if parcelas <= minimo:
print('Empréstimo concedido!')
print('Em {} anos você irá pagar R${:.2f} por mês'.format(anos, parcelas))
else:
print('Empréstimo negado!!')
| false |
a65b1ff98ba3df1b73a3c854fb04278ac804ff2f | chrishendrick/Python-Bible | /cinema.py | 1,113 | 4.25 | 4 | # cinema ticketing
# working with dictionaries, while loops, if/elif/else
# "name":[age,tickets]
films = {
"The Big Lebowski":[17,5],
"Bourne Identity":[18,5],
"Tarzan":[15,3],
"Ghost Busters":[12,5]
}
while True:
choice = input("Which film would you like to watch?: ").strip().title()
if choice in films:
#check number of tickets left
num_seats = films[choice][1]
if num_seats > 1:
print("Great, there are {} seats left!".format(films[choice][1]))
elif num_seats == 1:
print("Great, there is {} seat left!".format(films[choice][1]))
else:
print("Sorry, we are sold out!")
continue #moves to the next iteration in the while loop
#check user age
age = int(input("How old are you?: ").strip())
if age >= films[choice][0]:
print("Enjoy the film!")
films[choice][1] = films[choice][1] - 1
else:
print("You're not old enough!")
elif choice == "Exit":
break
else:
print("We don't have that film...")
| true |
bf44413ec101466043c14961e255cd0dc1ab5af7 | dimitrisgiannak/Python-Private_School-Part_B | /files/PV_methods2.py | 1,081 | 4.1875 | 4 | from datetime import date
'''
For details check README
'''
error_message3 = 'You must input an integer'
def getdate(datetime_ , statement , empty):
while True:
date1 = 0
try:
print_message = f'Please write the {datetime_} of the {statement} '
date = input(print_message + '\n')
if not date:
date1 = int(empty)
break
else:
date1 = int(date)
break
except ValueError:
print(error_message3.center(75) , '\n')
return date1
#-----------------------------------------------------------------------------------------------------------------------------------------------------------
def getmarks(value):
while True:
mark1 = 0
try:
mark = input(value)
if not mark:
mark = -1
break
else:
mark1 = int(mark)
break
except ValueError:
print(error_message3 , '\n')
return mark1 | true |
f2dc16e373f8c6e18f30bb0f7ffa3c0985b16355 | modukurusrikanth/python-inventateq | /dictinory_ex1.py | 286 | 4.3125 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
d = {'KA':'BLR','MH':'mum','AP':'AMR','noodles':['yippeee','maggi']}
for k,v in d.items():
print(" the capital of {} is: {}".format(k,v))
for k in d.values():
print("All the values of dictionary is:{}".format(k)) | false |
a5b2fdd0a9f78f160f40d7975cab2c57cea2590f | modukurusrikanth/python-inventateq | /biggest_and_smallest_number_from_list.py | 405 | 4.15625 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6
list_1 = [9, 8, 1, 6, 3, 2, 10, 12, 11, 201, 209, 99, 203,4,-5]
max_num = list_1[0]
min_num = list_1[0]
print("The list is:", list_1)
for i in xrange(len(list_1)):
if list_1[i] > max_num:
max_num = list_1[i]
elif list_1[i] < min_num:
min_num = list_1[i]
print("max_num is :", max_num)
print("min_num is :", min_num) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.