blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3b007e9ed267ca8ad1c22e0e34284734daf84d90 | Ernjivi/bedu_python01 | /Curso-de-Python/Clase-02/listas-de-enteros-funciones.py | 1,734 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
El script deberá de crear e imprimir la lista de números enteros con N
elementos, el valor de N será proporcionado por el usuario, por lo que
se sugiere hacer uso de dos funciones.
"""
# No inicies a escribir el script desde aquí, ve al final del script e
# inicia donde dice COMENZAR AQUÍ
def lee_entero(msg):
"""
Lee un entero desde la entrada estándar mostrando el mensaje en msg y
regresando el valor de tipo int.
"""
# Hacemos un ciclo infinito hasta que se leea un entero
while True:
resp = input(msg + " ")
if resp.isdigit():
# Tenemos un entero
return int(resp)
else:
# Tenemos cualquier cosa, menos un entero
print()
print("Error: lo que has escrito no es un entero, intenta de nuevo!")
print()
def crea_lista(n):
"""
Crea la lista con n números y la regresa.
Adicionalmente imprime el avance al ir creando la lista cada 10%
"""
# Primero se genera la lista
lista = []
# Iniciamos nuestro contador
i = 0
# Realizamos un ciclo mientras no hayamos llegado a n
while i < n:
# Agreganos un número más a la lista
lista.append(i)
# Imprimimos avance cada que se ha creado un 10% de la lista
if i % int(n * 0.1) == 0:
print("Generando lista al {:2.0f}%".format(i / n * 100))
# Incrementamos i para pasar al siguiente número
i += 1
print()
# Regresamos la lista completa
return lista
# COMENZAR AQUÍ: Escribe estás líneas primero
n = lee_entero("Cantidad de números enteros a generar?")
lista = crea_lista(n)
print(lista)
| false |
e15850165397b66795497cfa10d2495139998de0 | Davenport70/python-basics- | /practice strings.py | 1,351 | 4.5625 | 5 | # practice string
# welcome to Sparta - excercise
# Version 1 specs
# define a variable name, and assign a string with a name
welcome = 'Hello and welcome!'
print(welcome)
# prompt the user for input and ask the user for his/her name
user_input = input('What is your name?')
print(user_input)
# use concatenation to print a welcome method and use method to format the name/input
print(f'Hello and welcome {user_input} thanks for the name!')
# version 2
# ask the user for a first name and save it as a variable
user_input_first_name = input('What is your first name?')
print(user_input_first_name)
# ask the user for a last name and save it as a variable
user_input_last_name = input('What is your last name?')
print(user_input_last_name)
# do the same but use a different message andza
# use interpolation to print the message
user_input_full_name = input('What is your first name') + ' ' + input('What is your last name')
print(user_input_full_name)
# Calculate year of Birth
# gather details on age and name
user_input_full_name = input('What is your first name') + ' ' + input('What is your last name')
age = input(f'Hello {user_input_full_name} can I take your age?')
birthday = 2020 - int(age)
input('Can I have your name please?')
print(f'OMG {user_input_full_name}, you are {age} years old so you were born in {birthday} year')
| true |
47f5e052808e5a77df1a15980e1ea37fad4756e4 | raghavgr/Leetcode | /reverse_string344.py | 862 | 4.3125 | 4 | """
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
"""
class Solution:
""" 2 solutions """
def reverseString(self, s):
"""
in-place reverse string algorithm
i.e. another string is not used to store the result
:type s: str
:rtype: str
"""
chars = list(s)
for i in range(len(s) // 2):
temp = chars[i]
chars[i] = chars[len(s) - i - 1]
chars[len(s) - i - 1] = temp
return ''.join(chars)
def reverseString_pythonic(self, s):
"""
Reverse string using slicing
:type s: str
:rtype: str
"""
return s[::-1]
obj = Solution()
print(obj.reverseString("hello")) # 'olleh'
print(obj.reverseString_pythonic("clara")) # 'aralc' | true |
c834fd40f3a86542a2d81ea0297c71d1cf1853fd | JoshMez/Python_Intro | /Dictionary/Empty_Dict.py | 245 | 4.21875 | 4 | #Aim: To learn about empty dictionaries
#
#Creating an empty dictionary.
dict = {} #Put two curly braces. #No space between them.
#
#Adding values to the empty dictionay.
#
dict['Jason'] = 'Blue'
dict['Belle'] = 'Red'
dict['John'] = 'Black'
#
#
| true |
c7136ec6647afc0f3044059082e63a55d80506d5 | JoshMez/Python_Intro | /Programming_Flow/List_Comprehension.py | 298 | 4.25 | 4 | #Basic demonstration of list comprehension.
#Variable was declared.
#List was create with the square brackets.
#value ** 2 was created.
#The a for loop was created ; NOTICE : THere was not the semi:colon as the end.
squares = [ value ** 2 for value in range(1,11) ]
print(squares)
| true |
bfd57f6ad775a8c6cd91ba2db417421d9716a415 | JoshMez/Python_Intro | /Functions/Exercies_8.py | 1,645 | 4.75 | 5 | #8-1. Message: Write a function called display_message() that prints one sentence
#telling everyone what you are learning about in this chapter. Call the
#function, and make sure the message displays correctly.
#Creating a function.
def display_message():
"""Displaying the chapter focuses on"""
print("In this lesson, the focus is on functions.")
#Calling the functions
display_message()
#8-2. Favorite Book: Write a function called favorite_book() that accepts one
#parameter, title. The function should print a message, such as One of my
#favorite books is Alice in Wonderland. Call the function, making sure to
#include a book title as an argument in the function call.
#
#Supplying one parameter
def favorite_book(book):
"""Showing my favorite book"""
print(f"My fav book is {book.title()}")
#Calling the function along with an argument.
favorite_book("alice in wonderland\n\n")
#8.3
#Defining a function called make_shirt()
def make_shirt(size, message):
"""This is the size of the t-shit"""
print(f"Size {size}")
print(f'{message}\n')
make_shirt('M', "Being successful means SECOND BY SECOND")
######
#####
#8.4
def make_shirt(size='large', message='I love Python'):
"""New print """
print(f"Size: {size}")
print(f"{message}\n")
#Calling the function
make_shirt(size='M', message='One second at a time is how you build success.')
######
#8.5
#Creating a function.
def describe_city(city, country="Iceland"):
"""Tells you where you statement is """
print(f"Josh is currently in {city} which is in the {country}")
#Using the definition.
describe_city('Gaborone', country='Botswana')
| true |
f77853c57409d16a7d23731165daa4fb70a2bf20 | JoshMez/Python_Intro | /While_Input/Dict_User_Input.py | 714 | 4.25 | 4 | #Creating an empty dictionary.
#
#Creating an empty dictionary.
responses = {}
#
#Creating a flag.
polling_active = True
####
#
while polling_active:
#Prompting the user for input.
naming = input("Whats your name: ")
response = input("Which mountain do you want to visit: ")
#Store the responses in the dictionary
responses[naming] = response
#Seeing if anyone else want to add.
repeat = input("Do you want to add another person as well, Yes or No: ")
#
if repeat == 'no' or repeat == 'N' or repeat == "No":
print("Ending the program ")
polling_active = False
#
for name,r in responses.items():
print(f"Hi {name}, it looks like you want to visit {r}") | true |
a0f6073ebcf2f8159b91f630968acb177b9b561b | JoshMez/Python_Intro | /Dictionary/Loop_Dict.py | 1,293 | 4.90625 | 5 | #Aim: Explain Loop and Dictionaries.
#
#
#There are several ways to loop through a dictionary.
#Loop through all of Key-pair values.
#Loop through keys only.
#Loop though values only.
#
#
############Example of looping through all dictionary key-pair values####################
#
#Creating a dictionary of a User information.
User_0 = {'username': 'jmez',
'first name' : 'Josh',
'Last name' : 'Mezieres'
}
#Loop through all key-value pair info
#The for loop will contain 2 variable.
#One variable --- The one which comes first represent the Key
#after 1st varaible stated, a comma comes in straight afterwards.
#Then a second variable will be used to define the key.
#Seeing as loop is going through 2 variables. - Add .items(), after the dictionary.
#
for user_cat, info in User_0.items():
print(f"Key: {user_cat.title()}")
print(f"Info: {info}\n\n")
#
#
#
#Think about dictionaries working well for working well with pairs.
#Creating a dictionary with peoples name and programming languages.
Names_Lang = {'jane': 'c',
'arkus': 'python',
'allistair': 'ruby'
}
#
for Name, lang in Names_Lang.items():
print(f"{Name.title()}'s favourite programming language is {lang.title()}\n")
###############
| true |
f95e10517f70584b947de934b5fa33dee7d149bc | JoshMez/Python_Intro | /Dictionary/Nesting_2.py | 601 | 4.1875 | 4 | aliens = []
#Basically creating the variable 30 times over.
#
#The range just tells Python how many times we want to loop and repeat.
#Each time loop occurs, we create a new alien and append it to the new alien list.
for alien in range(30):
new_alien = {'color': 'green',
'points': 5,
'speed': 'slow'
}
aliens.append(new_alien)
#Using slicing to get the the 1st liness of the list.
for alien in aliens[:5] :
print(alien)
########
#How many aliens are there in the list.
print(f"The amout of alients in the list are {len(aliens)}" )
#
#
| true |
1068634872d3d4acb23453519b7f6e3b9069bcae | JoshMez/Python_Intro | /Programming_Flow/Number_Lists.py | 1,243 | 4.53125 | 5 | #Creating lists that contain number in Python is very important.
#Making a list with even numbers in it.
even_numbers = list(range(0,11,2)) #The list function has been used to say that a lists is being created. #Passing the range arguments in that , stating arugments in that.
print(even_numbers)
#Creating a list , with a range of number in them.
#Creating a list of numbers.
numbers = list(range(1, 20+1))
#Printing the list that was created.
print(numbers)
lists = [] #Do not give you variable key definitions.
#Want to create a list of all square numbers, in the given range.
for number in numbers:
lists.append(number ** 2 ) #Number is our temporary variable.
print(list)
print( "*" * 100)
print()
print("This part will focus on functions that are useful when working with lists.")
#Using the min function in A LIST OF numbers.
numbers2 = list(range(1 ,30 + 1 ))
print(numbers2)
min_numbers = min(numbers2)
print(min_numbers)
#Using the max function to find the maximum amount of numbers in a lists.
numbers3 = list(range(1,21))
print(numbers3)
print(max(numbers3))
#Calculating the sum of number in a lists.
numbers4 = list(range(1, 25))
print(numbers4)
print(sum(numbers4))
| true |
170b81c95440d3e3b418d2ae47a5fd74a654dd88 | AnmolKhullar/training-2019 | /Day10A.py | 984 | 4.1875 | 4 | """This module is for calculate Employee salary"""
class Employee:
"""This is class Employee
Hello world"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, "Salary:", self.salary)
if __name__ == '__main__':
emp1 = Employee("Nikhil", 9999)
emp1.displayEmployee()
print("Is salary an attribute:", hasattr(emp1, 'salary'))
print(getattr(emp1, 'salary'))
setattr(emp1, 'salary', 7000)
print("Modified salary", getattr(emp1, 'salary'))
print(hasattr(emp1, 'desg'))
setattr(emp1, 'desg', 'manager')
print(hasattr(emp1, 'desg'))
print("Added Attribute", getattr(emp1, 'desg'))
delattr(emp1, 'salary')
print("Is salary an attribute:", hasattr(emp1, 'salary'))
| false |
38936a50b1ef5570cef7a9cd19e1774ddc7e21ce | shekhar270779/Learn_Python | /prg_OOP-05.py | 2,388 | 4.5625 | 5 | '''
Class Inheritance: Inheritance allows a class to inherit attributes and methods from parent class.
This is useful as we can create subclass which inherits all functionality of parent class, also if required
we can override, or add new functionality to sub class without affecting parent class
'''
class Employee:
sal_hike_per = 4
def __init__(self, fname, lname, sal):
self.fname = fname
self.lname = lname
self.sal = sal
def fullname(self):
return self.fname + ' ' + self.lname
@classmethod
def set_sal_hike_per(cls, per):
cls.sal_hike_per = per
def apply_sal_hike(self):
self.sal = int(self.sal * (1 + self.sal_hike_per/100))
# Create Sub Class engineer which inherits Employee
class Engineer(Employee):
pass
e1 = Engineer('Tom', 'Walter', 30000)
print(e1.fullname())
e1.apply_sal_hike()
print(e1.sal)
class Manager(Employee):
sal_hike_per = 10 # overriding class variable
e2 = Manager("Kim", "Jones", 30000)
e2.apply_sal_hike()
print(f"{e2.fullname()} after salary hike has salary {e2.sal}")
class Developer(Employee):
def __init__(self, fname, lname, sal, main_skill):
super().__init__(fname, lname, sal)
self.main_skill = main_skill
e3 = Developer("Ash", "Watson", 30000, "Python")
print(f"{e3.fullname()} has key skill as {e3.main_skill}")
class Lead(Employee):
def __init__(self, fname, lname, sal, employees=None):
super().__init__(fname, lname, sal)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_employee(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_employee(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_employees(self):
print(f"Team of {self.fullname()}")
for emp in self.employees:
print('--->' + emp.fullname())
e4 = Lead("Ashley", "King", 30000, [e1])
print(f"{e4.fullname()} ")
e4.print_employees()
print(f"Adding employees to team of {e4.fullname()}")
e4.add_employee(e2)
e4.add_employee(e1)
e4.print_employees()
print(f"Removing {e1.fullname()} from team of {e4.fullname()}")
e4.remove_employee(e1)
e4.print_employees()
| true |
8bdc82cc4590b320da4b8f2e8462b3db0960ea59 | andu1989anand/vtu-1sem-cpl-lab-in-python | /palindrome1.py | 450 | 4.34375 | 4 | print "\n Python program to reverse a given integer number and check whether it is a"
print "PALINDROME or not. Output the given number with suitable message\n\n"
num=input("Enter a valid integer number:")
temp = num
rev=0
while(num != 0):
digit=num % 10
rev=rev * 10 + digit
num=num / 10
print "\n\n The reversed number",rev
if(temp == rev):
print "\n The number is PALINDROME\n"
else:
print "\n The number is not PALINDROME\n"
| true |
eaa8e5da435544cd8e07457a6e90e79c5a59591c | pilifengmo/Electrical-Consumption-Prediction-System | /PROJECT/website/model.py | 1,776 | 4.125 | 4 | import sqlite3 as sql
class Database(object):
""" Create database if not exist """
def __init__(self):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("create table if not exists users (id integer primary key autoincrement, username text not null UNIQUE, email text not null UNIQUE, password text not null)")
con.close()
""" Insert new user into the database """
def insertUser(self, username, email, password):
con = sql.connect("database.db")
try:
cur = con.cursor()
cur.execute("INSERT INTO users (username,email,password) VALUES (?,?,?)", (username,email,password))
con.commit()
except sql.IntegrityError as err:
con.close()
return 0
finally:
con.close()
""" Get records of all the users in the database """
def retrieveUsers(self):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("SELECT username,email, password FROM users")
users = cur.fetchall()
con.close()
return users
""" Get an active user """
def activeUser(self, email, password):
con = sql.connect("database.db")
try:
cur = con.cursor()
cur.execute("SELECT email, password FROM users WHERE email = '" + email + "' AND password = '" + password + "'")
users = cur.fetchall()
return users
except sql.Error as err:
con.close()
return 0
finally:
con.close()
""" Is user valid """
def isUserValid(self, email, password):
if len(self.activeUser(email,password)) > 0:
return True
return False
| true |
e9d5619d853a46cfe7f3e26f693d56ae14768567 | hashncrash/IS211_Assignment1 | /assignment1_part2.py | 559 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"IS 211 Assignment 1, part 2. Dave Soto"
class Book(object):
author = " "
title = " "
"Book Class information"
def __init__(self, author, title):
self.author = author
self.title = title
"Function to dsiplay the book author and title"
def display(self):
bookinfo = '"{}, written by {}"'.format(self.title, self.author)
print bookinfo
BOOK_1 = Book('John Steinbeck', 'Of Mice and Men')
BOOK_2 = Book('Harper Lee', 'To Kill a Mockingbird')
BOOK_1.display()
BOOK_2.display()
| true |
aeea6c0d9e8763f11c32f28d6456a8782483af28 | sysulj/leetcode | /easy/string/563. 二叉树的坡度.py | 2,342 | 4.15625 | 4 | """
给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入:
1
/ \
2 3
输出: 1
解释:
结点的坡度 2 : 0
结点的坡度 3 : 0
结点的坡度 1 : |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1
注意:
任何子树的结点的和不会超过32位整数的范围。
坡度的值不会超过32位整数的范围。
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.sumTilt(root)[0]
def sumTilt(self, root):
"""
"""
if root:
lt, ls = self.sumTilt(root.left)
rt, rs = self.sumTilt(root.right)
return abs(ls - rs) + lt + rt, ls + rs + root.val
else:
return 0, 0
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
def _sum_tilt(root):
if not root:
return 0
else:
left = _sum_tilt(root.left)
right = _sum_tilt(root.right)
self.ans += abs(left - right)
return root.val + left + right
_sum_tilt(root)
return self.ans
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
if not root:
return [0, 0]
else:
l1, l2 = dfs(root.left)
r1, r2 = dfs(root.right)
return [l1 + r1 + abs(l2 - r2), root.val + l2 + r2]
return dfs(root)[0] | false |
3db6fbcb14c16503f5c6dbddcba388cf25db73d1 | Alilujian/Election_Analysis | /Python_Practice.py | 2,825 | 4.3125 | 4 | counties = ["Arapahoe", "Denver","Jefferson"]
if counties[1] == 'Denver':
print(counties[1])
counties_tuple = ("Arapahoe", "Denver", "Jefferson")
counties_dict ={}
counties_dict["Arapahoe"] = 422829
counties_dict["Denver"] = 463353
counties_dict["Jefferson"] = 432438
counties_dict.items()
counties_dict.keys()
counties_dict.values()
counties_dict.get("Denver")
voting_data = []
voting_data.append({"county": "Arapahoe", "registered_voters":422829})
voting_data.append({"county": "Denver", "registered_voters": 463353})
voting_data.append({"county": "Jefferson", "registered_voters": 432438})
print(voting_data)
# How many votes did you get?
my_votes = int(input("How many votes did you get in the election? "))
# Total votes in the election
total_votes = int(input("What is the total votes in the election? "))
# Calculate the percentage of votes you received.
percentage_votes = (my_votes / total_votes) * 100
print(f"I received " + str(percentage_votes)+"% of the total votes.")
counties = ["Arapahoe","Denver","Jefferson"]
if "El Paso" in counties:
print("El Paso is in the list of counties.")
else:
print("El Paso is not in the list of counties.")
if "Arapahoe" in counties and "El Paso" in counties:
print("Araphoe and El paso are in the list of counties.")
else:
print("Araphoe or El Paso is not in the list of counties.")
if "Arapahoe" in counties or "El Paso" in counties:
print("Araphoe or El Paso is in the list of counties.")
else:
print("Araphoe and El Paso are not in the list of counties.")
for county in counties:
print(county)
for i in range(len(counties)):
print(counties[i])
for county in counties_dict:
print(county)
for county in counties_dict.keys():
print(county)
for voters in counties_dict.values():
print(voters)
for county in counties_dict:
print(counties_dict[county])
for county in counties_dict:
print(counties_dict.get(county))
for county, voters in counties_dict.items():
print(county + " county has " + str(voters)+ " registered voters.")
for county, voters in counties_dict.items():
print(f"{county} county has {voters} registered voters.")
candidate_votes = int(input("How many votes did the candidate get in the election? "))
total_votes = int(input("What is the total number of votes in the election? "))
message_to_candidate = (
f"You received {candidate_votes:,} number of votes. "
f"The total number of votes in the election was {total_votes:,}. "
f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.")
print(message_to_candidate)
# Import the datatime class from the datetime module
import datetime as dt
# Use the now() attribute on the datetime class to get the present time
now = dt.datetime.now()
# print the present time
print("The time right now is ", now) | false |
d5ed2a5b8c599a693c41178f7096995589fa4dc0 | s290717997/Python-100-Days | /day1-15/day7/day7_5.py | 657 | 4.25 | 4 | #练习5:计算指定的年月日是这一年的第几天
days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def if_leap_year(year):
if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:
return True
else:
return False
def which_day(year, month, day):
sum = 0
for i in range(1, month):
sum += days_of_month[i-1]
if i == 2 and if_leap_year(year):
sum += 1
pass
return sum + day
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == '__main__':
main() | true |
e2defc1b4568b4f52e7c4ac3249d6a67e17275b6 | Krashex/pl | /Chapter5/DaddyChooseGame.py | 2,264 | 4.53125 | 5 | pairs = {'Oleg': 'Petr',
'Artur': 'Denis',
'Ivan': 'Petr'}
choice = None
print("""
Type 1 - if you want to know smb's father's name
Type 2 - if you want to add new pairs
Type 3 - if you want to remove sm pair
Type 4 - if you want to change sm pair
Type 5 - if you want to show all pairs
Type 6 - if you want to see the table
Type 7 - if you want to quit.
P.S. Be careful and don't give same names to sons!""")
while choice != 7:
choice = int(input('Type number: '))
if choice == 1:
answer = input("Type son's name: ")
if answer not in pairs:
print('There is no such a name, if you want to add pair press 2')
else:
print(pairs[answer], 'is the', answer + "'s", 'father')
elif choice == 2:
new_son = input("Type new son's name: ")
new_father = input("Type new father's name: ")
pairs[new_son] = new_father
elif choice == 3:
print("Type son's name and you'll delete pair with this son")
removed = input('Enter name: ')
if removed in pairs:
del pairs[removed]
else:
print("There is no such a name...")
elif choice == 4:
change = input("Type son's name in pair that you want to change: ")
if change in pairs:
new_name = input("Now type new father's name: ")
pairs[change] = new_name
else:
print("There is no such a name...")
elif choice == 5:
for item in pairs.items():
print(item[0] + " " + item[1])
elif choice == 6:
print("""
Type 1 - if you want to know smb's father's name
Type 2 - if you want to add new pairs
Type 3 - if you want to remove sm pair
Type 4 - if you want to change sm pair
Type 5 - if you want to show all pairs
Type 6 - if you want to see the table
Type 7 - if you want to quit.
P.S. Be careful and don't give same names to sons!""")
elif choice == 7:
break
else:
print("There is no such a number...")
| true |
632144ea0c2dc95a6a87d20d642528339be71a52 | wilcerowii/mtec2002_assignments | /class10/labs/exceptions.py | 1,367 | 4.21875 | 4 | """
exceptions.py
=====
To handle errors, use a try/catch block:
-----
try:
# do your stuff
except SomeError:
# deal with some error
-----
optionally... you can continue catching more than one exception:
-----
.
.
except AnotherError:
# deal with another error
-----
Substitute SomeError with the kind of error you want to handle - for example:
KeyError
ValueError
TypeError
IndexError
ZeroDivisionError
"""
#KeyError
d = {"shape":"circle"}
print d =['shape']
print d['color']
except keyError: 'color'
print "that key doesn't exist!!!!"
print "done"
#ValueError (conversion errors)
try:
print int("this is not a number")
except ValueError:
print "it dont thats a number"
#TypeError
type:
print "foo" * "bar"
except TypeError:
print "you cant multiply by that"
#IndexError
my_list = ["same", "stuff"]
try:
print my_list[2]
except IndexError:
print "that index is out of range"
#ZeroDivisionError
try:
5 / 0
except ZeroDivisionError
print "that's a no-no"
#catching multiple possible exceptions - try possible KeyError AND TypeError
like dictionary value divided by another value
#ex... which player do you want to add a score to, and add that score
d = {"score":10}
k = "score"
divisor = 2
try:
print d[k] / divisor
except:KeyError:
print "thatkey doesnt exist"
except:ZeroDivisionError:
print "you cant divide by zero"
| true |
90952d5c964ca74bb1c221b4cf93395799f1f564 | jbrownxf/mycode | /wk1proj/gotime2 | 1,544 | 4.1875 | 4 | #!/usr/bin/env python3
#imports
import random
#This is a board game. Every player rolls a dice from 1-12 first to 100 wins
#By Josh Brown
from random import randint
#ask for number of players, creates a dic for every player
num_player = input("How many will be playing Dicequest?(2-6 players) ")
num_players =int(num_player) + 1 #allows me to start numbering players at 1 instead of 0
#takes the input value from user and turns it into an append list
list_players = []
for x in range(1, num_players):
list_players.append('Player ' + str(x))
print(list_players)
mylist = []
## creating dictionaries with proper strcutures
for x in range(len(list_players)):
dic = {'name': list_players[x], 'score' : 0}
mylist.append(dic)
print(mylist)
##dice roll code
min = 1
max = 6
## while loop that will increase the players score with a dice roll function until score 100 is met
##I need a way to call the name value first and then roll the dice
## use a for loop with a +1 to cycle through values of 'name'
win=False
while win != True:
for turn in range(len(list_players)):
roll= (random.randint(min, max))
print(mylist[turn]['name'] + ' rolled ' + str(roll))
mylist[turn]['score'] += roll #(random.randint(min, max))
print(mylist[turn]['name'] + ' is at ' + str(mylist[turn]['score']))
if mylist[turn]['score'] >= 15:
print('The winner is ' + mylist[turn]['name'] + ' with a score of ' + str(mylist[turn]['score']) + '!')
win = True
break
| true |
f745f56706575fc6f3e565b026029103c51cca4a | adnanhanif793/Python-Codes | /Basic/com/Anagram.py | 448 | 4.1875 | 4 | '''
Created on 18-Mar-2019
@author: adnan.hanif
'''
def check(s1, s2):
# the sorted strings are checked
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
# driver code
n=int(input("Enter the number of terms"))
i=0
while(i<n):
s1 =input("enter first")
s2 =input("enter second")
check(s1, s2) | true |
3043d49c09e87ff59adc9386745996dbfeccf057 | jonalynnA-cs29/Intro-Python-I | /src/05_lists.py | 2,269 | 4.53125 | 5 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
'''
Python List append()
Add a single element to the end of the list
Python List extend()
Add Elements of a List to Another List
Python List insert()
Inserts Element to The List
Python List remove()
Removes item from the list
Python List index()
returns smallest index of element in list
Python List count()
returns occurrences of element in a list
Python List pop()
Removes element at the given index
Python List reverse()
Reverses a List
Python List sort()
sorts elements of a list
Python List copy()
Returns Shallow Copy of a List
Python List clear()
Removes all Items from the List
Python any()
Checks if any Element of an Iterable is True
Python all()
returns true when all elements in iterable is true
Python ascii()
Returns String Containing Printable Representation
Python bool()
Converts a Value to Boolean
Python enumerate()
Returns an Enumerate Object
Python filter()
constructs iterator from elements which are true
Python iter()
returns an iterator
Python list()
creates a list in Python
Python len()
Returns Length of an Object
Python max()
returns the largest item
Python min()
returns the smallest value
Python map()
Applies Function and Returns a List
Python reversed()
returns the reversed iterator of a sequence
Python slice()
returns a slice object
Python sorted()
returns a sorted list from the given iterable
Python sum()
Adds items of an Iterable
Python zip()
Returns an iterator of tuples
'''
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
x.insert(5, 99)
print(x)
# Print the length of list x
print(len(x))
# Print all the values in x multiplied by 1000
for num in x:
print(num * 1000) # This is the preferred method for something this simple
# List Comprehension is better (less code) for things that are more complicated
x1000 = [n * 1000 for n in x]
# ^^^^^^^^^ ^^^^^ ^^^^
# output input filter
print(x1000)
| true |
698c957da6315ef6124c57ca3b22aa7a6776df0b | nshattuck20/Data_Structures_Algorithms1 | /ch9/9-1.py | 630 | 4.59375 | 5 | '''
Section 9-1:
Recursive Functions
'''
#Example of recursive function
#I used the code from the animation example in the course material
def count_down(count):
if count == 0:
print('Go!')
else:
print(count)
count_down(count -1)
count_down(2) # recursively call count_down 3 times.
#Another example is a program that prints alphabet backward
def backward_aplhabet(current_letter):
if current_letter == 'a':
print(current_letter)
else:
print(current_letter)
prev_letter = chr(ord(current_letter) - 1)
backward_aplhabet(prev_letter)
starting | true |
efcb7864f7ec7260c361402910aea5a5b9cbb091 | nshattuck20/Data_Structures_Algorithms1 | /ch8/8-6.py | 347 | 4.46875 | 4 | '''
8-6 List Comprehensions:
Form:
new_list = [expression for name in iterable]
3 components:
1. The expression to evaluate each iterable component
2. A loop variable to bind to the components
3. An iterable object
'''
#Example
my_list = [5, 10, 15]
my_list_plus5 = [(i + 5) for i in my_list]
print('New list contains' , my_list_plus5) | true |
17786b5a311cfbb8e4c2e56f7bf0e9ce35e9269a | nshattuck20/Data_Structures_Algorithms1 | /ch9/9-5-1.py | 874 | 4.40625 | 4 | '''
9-5-1
Write a program that outputs the nth Fibonacci number, where n is a
user-entered number. So if the user enters 4, the program should
output 3 (without outputting the intermediate steps).
Use a recursive function compute_nth_fib that takes n as
a parameter and returns the Fibonacci number.
The function has two base cases: input 0 returns 0, and input 1 returns 1.
'''
def compute_nth_fib(num):
# if base case ...
if num == 0 or num == 1:
return num
else:
return compute_nth_fib(num-1) + compute_nth_fib(num-2)
# return print(compute_nth_fib(num))
print('This program will find the nth Fibonacci \n'
'number. Example: entering 4 returns 3, because\n'
'3 is the 4th number in the Fibonacci sequence.\n')
nth_number = int(input('Which number would you like to find?'))
print(compute_nth_fib(nth_number)) | true |
148c9c7ffecb1938db146f2c7e263e82bdfb741e | nshattuck20/Data_Structures_Algorithms1 | /Chapter4/4.9/dictionary_basics.py | 451 | 4.34375 | 4 | '''
Simple program demonstrating the basics of Dictionaries.
'''
players = {'Lionel Messi' : 10,
'Cristiano Ronaldo' : 7
}
print(players)
#Accessing an entry uses brackets [] with the specified key
print('The value of this player is :' + str(players['Cristiano Ronaldo']))
#Editing the value of an entry
players['Lionel Messi'] = 11
print(players)
#Adding an entry
players['Cristian Pulisic'] = 22
print(players)
#Deleting an entry
del players['Lionel Messi']
print(players) | true |
1fa915224e3880af57d0012bd843a6d76dc184ad | nshattuck20/Data_Structures_Algorithms1 | /ch7/7-7.py | 1,097 | 4.71875 | 5 | '''Class customization
* Referes to how classes can be altered by rhe
programmer to suit her needs.
* _str_() changes how to print the output of an object
'''
class Toy:
def __init__(self, name, price, min_age):
self.name = name
self.price = price
self.min_age = min_age
truck = Toy('Monster Truck X', 14.99, 5)
print(truck) # print the memory address of truck
class Toy:
'''
Using the __str__() special method name to change
the output of the Toy object.
'''
def __init__(self, name, price, min_age):
self.name = name
self.price = price
self.min_age = min_age
def __str__(self):
return ('%s costs only $%.2f. Not for children under %d!' %
(self.name, self.price, self.min_age))
truck = Toy('Monster Truck X', 14.99, 5)
print(truck)
'''
Operator overloading using rich comparison methods:
__lt__(self, other) less-than(<)
__gt__(self, other) greater-than(>)
__le__(self, other) less-than or equal-to(<=)
__ge__(self, other) greater-than or equal-to(>=)
__eq__(self, other) equal to (==)
__ne__(self, other) not-equal to (!=
)
''' | true |
cdddcec194bbb01b91d42d936b6cf97bd6edc182 | nshattuck20/Data_Structures_Algorithms1 | /ch8/8-10.py | 1,792 | 4.78125 | 5 | '''
8-10: Nested dictionaries
(Dictionaries within dictionaries)
'''
# To declare a nested dictionary, do the following:
students = {} # empty dictionary
'''
#Create indexing operation with key 'John and value of another dictionary'
print('John:')
###EXAMPLE####
'''
# students['John'] = {'Grade' : 'A+' , 'StudentID' : 22321}
# print('Grade: %s' % students['John'] ['Grade']) # obtain the value of key 'John' from students. Yields nested dictionary.
# print('StudentID: % s' % students['John']['StudentID'])
music = {
'Artists': {
'Pink Floyd': {
'Albums': {
'The Dark Side of The Moon': {
'Songs': ['Speak To Me', 'Breathe', 'On the Run', 'Money'],
'Year': 1974,
'Platinum': True
}
}
}
}
}
user_input = input('Enter artist name: ')
while user_input != 'exit':
if user_input in music:
#Get the values from the dict
artists = music[user_input]['Artists']
albums = music[user_input]['Albums']
songs = music[user_input]['Songs']
#print values in the list
for val, songs in enumerate(songs):
print('Songs: %s %s ' % (val,songs))
print('Albums: %s' %s albums)
print('Artist: %s' %s artists)
#####Simple music program######
'''
The following program uses nested dictionaries to store a small music library.
Extend the program such that a user can add artists, albums, and songs to the library.
'''
# 1. Add a command that adds an artist name to the music dictionary
# 2. Add commands for adding albums and songs
# 3. Take care to check that an artist exists in the dictionary before adding an album,
# and that an album exists before adding a song
########################EXERCISE#############################
| false |
749979c042cf6df3dd7c34f16dd0a506fd4147f8 | bsfraga/prog-web | /pessoa.py | 963 | 4.25 | 4 | class Pessoa:
'''
Objeto pessoa e seus atributos.
Objeto pessoa projetado para guardar em apenas um instância uma lista de ocorrencias do objeto
Exemplo:
list_pessoa:
[
{
'nome':'ABCDE',
'idade':33,
}, ...
]
'''
def __init__(self):
'''
Construtor do Objeto pessoa.
Inicializa os atributos do objeto.
'''
self.nome = ''
self.idade = ''
self.list_pessoas = []
def add_pessoa_list(self, nome, idade):
'''
Para usar apenas uma instância do objeto este método tem como função
servir de "setter", setando os valores dos parâmetros do objeto e atribuindo os mesmos a uma lista
no formato de dicionário.
Exemplo: [{'nome':'ABC', 'idade':32},...]
'''
self.nome = nome
self.idade = idade
self.list_pessoas.append({'nome': self.nome, 'idade': self.idade})
| false |
906a5fdf384a4825b3cfa126777f35b9d1cb0b4c | mattprodani/letter-box | /Dictionary.py | 1,049 | 4.15625 | 4 | class Dictionary():
def __init__(self, dictionary, gameboard):
""" Builds a dictionary object containing a list of words as well as groups them into a Dictionary
separated by starting letter, where starting letters are in gameboard.
"""
wordList = []
self.wordGroups = {}
# Converts text file to list
# Populates a dictionary with word groups based on length
for line in dictionary:
word = line.strip().upper()
if word[0] in gameboard.getGameboard():
if word[0] in self.wordGroups.keys():
self.wordGroups[word[0]].append(word)
else:
self.wordGroups[word[0]] = [word]
def getKeys(self):
""" Returns a list of valid keys corresponding to groups by starting letter """
return sorted(list(self.wordGroups.keys()), reverse = True)
def getWords(self, key):
""" Gets words from dictionary starting with a given letter """
return self.wordGroups[key]
| true |
e0638d35fea87b4176d06cc0e33f136a805b7554 | CB987/dchomework | /Python/Python104/blastoff3.py | 237 | 4.1875 | 4 | # countdown that asks user where to start
n = int(input("From what number should start our countdown?")) #getting user input
while n >= 0: #setting end condition
print(n) #instructing to print number
n -=1 #incrementing downwards | true |
59c6d6de128a455c43a756ff527d25ce053e15ca | CB987/dchomework | /Python/Python104/blastoff2.py | 365 | 4.4375 | 4 | # create a countdown from 10 to 0, then prints a message
n = 10 #start point of countdown
while n >= 0: # set duration of countdown
print(n) #printing the number
n -=1 #Incrementing down, sends back up to print. loops until condition is false
if n < 0: #instructing when to print the message
print("May the Force Be With You") #print the message | true |
f675d32ecf2cf6d0afef4b975674d4adfdfd0bb2 | alisheryuldashev/playground | /Python/classes.py | 780 | 4.4375 | 4 | #this snippet shows how to create a class in Python.
#this program will prompt for information, append same into a class, and output a message.
#create a class called Student
class Student:
def __init__(self,name,dorm):
self.name = name
self.dorm = dorm
#import custom functions from CS50 library used in Harvard Introduction to Computer Science course.
from cs50 import get_string
#import class Student
from test14class import Student
students = []
dorms = []
#prompt user for information and append it to the class called Student
for i in range(3):
name = get_string("Name: ")
dorm = get_string("Dorm: ")
s = Student(name, dorm)
students.append(s)
for student in students:
print(f"{student.name} lives in {student.dorm}")
| true |
d56bdfbf76c0cbbce6c42a98844db12474e9c51b | Sandhie177/CS5690-Python-deep-learning | /ICP3/symmetric_difference.py | 610 | 4.28125 | 4 | # -*- coding: utf-8 -*-
#A={1,2,3,4}
#B={1,2}
def list1():
n=eval(input("How many numbers do you have in the list?")) #takes number of elements in the list
i=0
list1={0} #creating an empty set
list1.remove(0)
for i in range(n):
x=int(input("enter a number\n"))
list1.add(x) #adding new numbers to the list
print("the list is",list1) #prints the list
return list1 #returns the list
A=list1() #calls the function list1 to take input list A
B=list1() #calls the function list1 to take input list B
print ("the symmetric difference between set A and B is:", A^B)
| true |
015efad385e902e83ba1d21e2e4e7bf86d29a5a2 | Sandhie177/CS5690-Python-deep-learning | /Assignment_1/Assignment_1c_list_of_students.py | 1,271 | 4.4375 | 4 | #Consider the following scenario. You have a list of students who are attending class "Python"
#and another list of students who are attending class "Web Application".
#Find the list of students who are attending “python” classes but not “Web Application”
#function to create list
def list1():
n=eval(input("Student number:")) #takes number of elements in the list
i=0
list1=[] #creating an empty set
#list1.remove(0)
for i in range(n):
x=str(input("enter name\n"))
list1.append(x) #adding new members to the list
print("the list of student is",list1) #prints the list
return list1 #returns the list
#creating function to find out the difference
def Diff(li1, li2):
#converting the list into set and substracting
return (list(set(li1) - set(li2)))
#creating python database
print ("For python class,") #mentioning the name of class
python=list1() #calls the function list1 to take input for python class
#creating web_application database
print ("\n For web application class,") #mentioning the name of class
web_app=list1() #calls the function list1 to take input for web application class
d = (Diff(python, web_app))
print ("the list of students who are taking python but not web application is:", d) | true |
5c267a5620aa7a658ccdb79e677f3998207756a3 | sciencefixion/HelloPython | /Hello - Basics of Python/sliceback.py | 857 | 4.28125 | 4 | letters = "abcdefghijklmnopqrstuvwxyz"
backwards = letters[25:0:-1]
print(backwards)
backwards2 = letters[25::-1]
print(backwards2)
# with a negative step the start and stop defaults are reversed
backwards3 = letters[::-1]
print(backwards3)
# Challenge: Using the letters string add some code to create the following slices
# create a slice that produces the characters "qpo"
# slice the string to produce "edcba"
# slice the string to produce the last 8 characters in reverse order
slice1 = letters[-10:-13:-1]
slice2 = letters[-22::-1]
slice3 = letters[-1:-9:-1]
print(slice1)
print(slice2)
print(slice3)
# alternate solution
print(letters[16:13:-1])
print(letters[4::-1])
print(letters[:-9:-1])
# defaults for the stop and step values
print(letters[-4:])
print(letters[-1:])
# defaults for the start and step
print(letters[:1])
print(letters[0])
| true |
3d3108c007d9a67e5c257a28329b4effe701d322 | ngssss/xuewei | /utils/getAngel.py | 1,145 | 4.28125 | 4 | import math
class Point:
"""
2D坐标点
"""
def __init__(self, x, y):
self.X = x
self.Y = y
class Line:
def __init__(self, point1, point2):
"""
初始化包含两个端点
:param point1:
:param point2:
"""
self.Point1 = point1
self.Point2 = point2
def GetAngle(line1, line2):
"""
计算两条线段之间的夹角
:param line1:
:param line2:
:return:
"""
dx1 = line1.Point1.X - line1.Point2.X
dy1 = line1.Point1.Y - line1.Point2.Y
dx2 = line2.Point1.X - line2.Point2.X
dy2 = line2.Point1.Y - line2.Point2.Y
angle1 = math.atan2(dy1, dx1)
angle1 = int(angle1 * 180 / math.pi)
# print(angle1)
angle2 = math.atan2(dy2, dx2)
angle2 = int(angle2 * 180 / math.pi)
# print(angle2)
if angle1 * angle2 >= 0:
insideAngle = abs(angle1 - angle2)
else:
insideAngle = abs(angle1) + abs(angle2)
if insideAngle > 180:
insideAngle = 360 - insideAngle
insideAngle = insideAngle % 180
return insideAngle
| false |
4b1b47754908d1408d23be833869d656231ec113 | casanova98/Project-201501 | /Practical one/q1_fahrenheit_to_celsius.py | 232 | 4.21875 | 4 |
#q1_fahrenheit_to_celsius.py
answer = input("Enter the temperature you want in Celsius!")
x = float(answer)
celsius = round((5/9) * (x - 32), 1)
print("The temperature from Fahrenheit to Celsius to 1 decimal place is", celsius)
| true |
9d2ef8e3764b1709b9dfcbf68bb4af5bd4b64eae | casanova98/Project-201501 | /Practical two/q08_top2_scores.py | 552 | 4.125 | 4 |
students = int(input("Enter number of students: "))
names = []
score = []
while students != 0:
names.append(str(input("Enter your name: ")))
score.append(int(input("Enter your score: ")))
students -= 1
highest = max(score)
print("Student with highest score is:", names[score.index(highest)], "with a score of:", highest)
names.pop(score.index(highest))
score.pop(score.index(highest))
highest2 = max(score)
print("Student with second highest score is:", names[score.index(highest2)], "with a score of:", highest2)
| true |
783d04424384829bec20a0b6d4dddca93f46e3ae | Smily-Pirate/100DaysOfCode | /Day1.py | 971 | 4.125 | 4 | # Day1 of 100 days of coding.
# Starting from list.
# Accessing Values in Lists.
list1 = ['hi', 'there', 18, 1]
list2 = [1, 2, 3, 4, 5, 6, 7, 8]
print(list1[0])
print(list2[2])
# Updating list
list1[0] = 'ghanshyam'
list1[1] = 'joshi'
list2[7] = 'hi'
print(list1)
print(list2)
list1.append('10')
print(list1)
# Deleting List element
del list1[3]
del list2[7]
print(list1)
print(list2)
# Basic List Operations
# length
value = [1, 2, 'hi']
print(len(value))
print(len([1, 8, 'ji']))
# Concatenation
notvalue = [5, 'no']
new_value = value + notvalue
print(new_value)
# Repetition
hi = ['hi']
print("Value: " +str(hi )* 4 )
# Membership
values = 3
if values in value:
print("Yes")
else:
print("no")
# Iteration
for x in [1, 2, 3, 4]:
print(x)
# Slicing
number = [1, 2, 3, 4]
print(number[4:])
# Function len()
print(len(number))
# Function max()
print(max(number))
# Function min()
print(min(number))
# Function list
no = {'a', 'b'}
print(list(no)) | true |
49ba616fc87d3f9287ef22e444a7b872839f1aa7 | Akshay-Chandelkar/PythonTraining2019 | /Ex21_Arthimetic.py | 1,458 | 4.125 | 4 |
print("Free fall code to begin")
def add(num1,num2):
sum = num1 + num2
print("The sum of two numbers is : ", sum)
def sub(num1,num2):
sub = num2 - num1
print("The difference between the two numbers is : ", sub)
def mul(num1,num2):
mul = num1 * num2
print("The multiplication of the two numbers is : ", mul)
def div(num1,num2):
div = num2/num1
print("The division of the two numbers is :", div)
def Menu():
while True:
print("1. Add\n2. Substract\n3. Multiply\n4. Division\n5. Exit")
choice = int(input("Enter your choice :: "))
if(choice > 0 and choice <6):
return choice
else:
print("Please enter the correct choice.")
def ArithmaticOperations(num1,num2):
choice = 0
while choice != 5:
choice = Menu()
if(choice == 1):
add(num1,num2)
elif (choice == 2):
sub(num1,num2)
elif (choice == 3):
mul(num1,num2)
elif (choice == 4):
div(num1,num2)
elif (choice == 5):
break
else:
Menu()
def main():
num1 = int(input("Please enter first number : "))
num2 = int(input("Please enter second number : "))
ArithmaticOperations(num1,num2)
#add(num2=30,num1=10)
#sub(num1,num2)
#mul(num1,num2)
#div(num1,num2)
if __name__ == '__main__':
main()
| true |
c57f2c473a90a15353b101a8bd2e6b8f4031ceb3 | Akshay-Chandelkar/PythonTraining2019 | /Ex64_Stack_List.py | 2,492 | 4.125 | 4 | def IsStackFull(L1):
if IsStackEmpty(L1):
print("\nThe stack is empty.\n")
elif len(L1) >= 6:
return True
else:
print("\nThe stack is not full.\n")
def IsStackEmpty(L1):
if L1 == []:
return True
else:
return False
def Push(L1):
if not IsStackFull(L1):
no = eval(input("\nEnter the element to push in the stack :: "))
L1.append(no)
else:
print("\nSorry cant add an element as the stack is full\n")
return L1
def Pop(L1):
if not IsStackEmpty(L1):
print("\nRemoved the element {} from top of the stack\n ".format(L1.pop()))
else:
print("\nSorry cant remove an element as the stack is empty.\n")
def Peep(L1):
if not IsStackEmpty(L1):
print("\nThe current top of the stack element is {}\n".format(L1[len(L1)-1]))
else:
print("\nSorry the stack is empty.\n")
def Display(L1):
if not IsStackEmpty(L1):
print("\nThe current stack is {}\n".format(L1))
else:
print("\nThe stack is empty.\n")
'''
def DeleteStack(L1):
if not IsStackEmpty(L1):
del(L1)
print("The stack deleted successfully.")
else:
print("The stack is empty.")
'''
def menu(L1):
#choice = 0
while True:
print("Enter the stack operation ::\n1. Push\n2. Pop\n3. IsStackFull\n4. IsStackEmpty\n5. Peep\n6. Display\n7. DeleteStack\n8. Exit\n")
choice = eval(input("Enter your choice :: "))
if choice == 1:
Push(L1)
elif choice == 2:
Pop(L1)
elif choice == 3:
if IsStackFull(L1):
print("\nThe stack is full.\n")
elif choice == 4:
if IsStackEmpty(L1):
print("\nThe stack is empty.\n")
else:
print("\nThe stack is not empty.\n")
elif choice == 5:
Peep(L1)
elif choice == 6:
Display(L1)
elif choice == 7:
if not IsStackEmpty(L1):
del(L1)
print("\nThe stack deleted successfully.\n")
else:
print("\nThe stack is empty.\n")
L1 = []
elif choice == 8:
break
else:
print("\nYou have entered an invalid choice.\n")
def main():
print("Create a stack \n")
L1 = []
menu(L1)
if __name__ == '__main__':
main() | true |
d8dc56075b59c4790ef758177723e44a2b09bf8f | vonnenaut/coursera_python | /7 of 7 --Capstone Exam/probability.py | 854 | 4.21875 | 4 | # Fundamentals of Computing Capstone Exam
# Question 12
def probability(outcomes):
""" takes a list of numbers as input (where each number must be between 1 and 6 inclusive) and computes the probability of getting the given sequence of outcomes from rolling the unfair die. Assume the die is rolled exactly the number of times as the length of the outcomes input. """
total_rolls = len(outcomes)
individual_probabilities = [0.1, 0.2, 0.3, 0.15, 0.05, 0.2]
lt_sum = 0 # sum of likelihood of a value times that value times the total number of rolls
probability = 1
for idx in range(len(outcomes)-1):
probability *= individual_probabilities[outcomes[idx]-1]
return probability
print probability([4, 2, 6, 4, 2, 4, 5, 5, 5, 5, 1, 2, 6, 2, 6, 6, 4, 6, 2, 3, 5, 5, 2, 1, 5, 5, 3, 2, 1, 4, 4, 1, 6, 6, 4, 6, 2, 4, 3, 2, 5, 1, 3, 5, 4, 1, 2, 3, 6, 1]) | true |
56555a338b03786e7de3d8cd5546f8d3b5f65158 | vonnenaut/coursera_python | /7 of 7 --Capstone Exam/pick_a_number.py | 1,280 | 4.15625 | 4 | # Fundamentals of Computing Capstone Exam
# Question 17
scores = [0,0]
player = 0
def pick_a_number(board):
""" recursively takes a list representing the game board and returns a tuple that is the score of the game if both players play optimally by choosing the highest number of the two at the far left and right edge of the number list (board)
returns a tuple with current player's score first and other player's score second """
global player
start = 0
end = len(board)
print "board:", board
# base case
if len(board) == 1:
print "\n\n---base case reached---"
return board
print "\n\n------ recursive case ------"
print "board:", board
print "board[0]:", board[0]
print "board[len(board)-1]:", board[len(board)-1]
if board[0] >= board[len(board) - 1]:
print "True"
choice = board[0]
start = 1
else:
print "False"
choice = board[len(board)-1]
end -= 1
print "board[start:end]:", board[start:end]
pn_helper(player, choice)
if player == 0:
player = 1
else:
player = 0
return pick_a_number(board[start:end])
def pn_helper(player, value):
global scores
scores[player] += value
print "scores:", scores
print pick_a_number([5,2,3,1])
# print pick_a_number([12, 9, 7, 3, 4, 7, 4, 7, 3, 16, 4, 8, 12, 1, 2, 7, 11, 6, 3, 9, 7, 1]) | true |
dcceddfae83a164aeae8bfa0fdb6177fad4b90de | vonnenaut/coursera_python | /2 of 7 -- Intro to Interactive Programming with Python 2/wk 6/quiz_6b_num8.py | 2,021 | 4.34375 | 4 | """
We can use loops to simulate natural processes over time. Write a program that calculates the populations of two kinds of “wumpuses” over time.
At the beginning of year 1, there are 1000 slow wumpuses and 1 fast wumpus. This one fast wumpus is a new mutation. Not surprisingly, being fast gives it an advantage, as it can better escape from predators.
Each year, each wumpus has one offspring. (We'll ignore the more realistic niceties of sexual reproduction, like distinguishing males and females.). There are no further mutations, so slow wumpuses beget slow wumpuses, and fast wumpuses beget fast wumpuses. Also, each year 40% of all slow wumpuses die each year, while only 30% of the fast wumpuses do.
So, at the beginning of year one there are 1000 slow wumpuses. Another 1000 slow wumpuses are born. But, 40% of these 2000 slow wumpuses die, leaving a total of 1200 at the end of year one. Meanwhile, in the same year, we begin with 1 fast wumpus, 1 more is born, and 30% of these die, leaving 1.4. (We'll also allow fractional populations, for simplicity.)
Beginning of Year Slow Wumpuses Fast Wumpuses
1 1000 1
2 1200 1.4
3 1440 1.96
… … …
Enter the first year in which the fast wumpuses outnumber the slow wumpuses. Remember that the table above shows the populations at the start of the year.
"""
year = 2
num_slow_wumpuses = 1000
num_fast_wumpuses = 1
def YearoftheFastWumpus(year, num_slow_wumpuses, num_fast_wumpuses):
while num_slow_wumpuses > num_fast_wumpuses:
num_slow_wumpuses = 2 * (num_slow_wumpuses - (num_slow_wumpuses * 0.4))
num_fast_wumpuses = 2 * (num_fast_wumpuses - (num_fast_wumpuses * 0.3))
print "Year: " + str(year) + "\n# Slow: " + str(num_slow_wumpuses) + "\n# Fast: " + str(num_fast_wumpuses)
year += 1
return "Fast wumpuses overtake on year " + str(year)
print YearoftheFastWumpus(year, num_slow_wumpuses, num_fast_wumpuses)
## #1 36.5 49
## #2 912.5 343
## #7 168
## #8 46 (must be 45 or 47) | true |
c9d3d1735eadee86c6601193da7690ed39d6e472 | 777shipra/dailypython | /assignment_acadview/question_9.py | 255 | 4.125 | 4 | sentence=raw_input("enter your sentence :")
uppercase_letters=0
lowercase_letters=0
for x in sentence:
if x.isupper():
uppercase_letters +=1
elif x.islower():
lowercase_letters +=1
print uppercase_letters
print lowercase_letters
| true |
b67904bd5415cde5c5ddc1a4e1cb121c47778274 | 777shipra/dailypython | /enumerate.py | 261 | 4.25 | 4 | choices=['pizza','ice','nachos','trigger']
for i,item in enumerate(choices):
print i,choices #prints the whole list
print i,item #prints the content of the list
for i,items in enumerate (choices,1):
print i,items #begins the itteration from index 1
| true |
83757a54e0ca9d5c0acac7dbf949a800eac053ff | KudzanaiGomera/cs50_Projects | /cs50_web/Python/lopps.py | 402 | 4.21875 | 4 | # iterate through a list of numbers
for i in [0,1,2,3,4,5,6]:
print (f"iterate through a list of numbers: {i}")
# iterate through a list of strings
names = ["Kudzai", "Steve", "John", "Adam"]
for name in names:
print(f"iterate through a list of strings: {name}")
# iterate through a string a print ech char at a time
s = "String"
for ch in s:
print(f"iterate through a string: {ch}") | false |
c222489968812c65d58847cbe1b7780f9f620b4c | elormcent/centlorm | /conditional.py | 542 | 4.21875 | 4 | i = 6
if(i % 2 == 0):
print ("Even Number")
else:
print ("Odd Number")
def even():
number = int(input("Enter a whole number :- "))
if (number > 0 % 2 == 0):
print("It\'s an even number, nice work")
elif (number > 0 % 2 == 1):
print("it\'s an odd number, good job")
elif (number == 0):
print("you entered \'0' 'Zero'")
elif (number < 0 ):
print("you entered a negetive number")
else:
print("Enter a number greater than \'0' 'Zero'")
even()
| true |
a97025850246a1a6e2a630565d20da91579e84fe | olivianauman/programming_for_informatics | /value_return.py | 392 | 4.15625 | 4 | def multiply3to9(input_number):
sum = 0
for to_multiply_with in range(3, 10, 2):
product = input_number * to_multiply_with
print(' {} * {} = {:.2f}'.format(input_number, to_multiply_with, product))
sum += product
return sum
sum1 = multiply3to9(-2.5)
sum2 = multiply3to9(21)
sum3 = multiply3to9(10.3)
print("{}, {}, {}'.format(sum1 ,sum2, sum3)) | false |
e40b81ba5afa39fdfe0b6384a5802695f53b1662 | olivianauman/programming_for_informatics | /untitled-2.py | 995 | 4.40625 | 4 | # turtle trys
import turtle # set window size
turtle.setup(800,600)
# get reference to turtle window
window = turtle.Screen()
# set window title bar
window.title("making a shape")
# set background color
window.bgcolor('purple')
the_turtle = turtle.getturtle()
# default turtle # 3 attributes: positioning, heading (orientation), pen
# creating a box with relative positioning
the_turtle.hideturtle()
# to see the turtle or not to see. #the_turtle.forward(100) # relative positioning
# the turtle starts by looking to the right (0 degrees)
the_turtle.setposition(100, 0)
# absolute positioning the_turtle.left(90) # turning 90 degrees to the left #the_turtle.setheading(135) # explicitly lookig in the 90 deg angle # see what happends when you change 90 above to something else
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
# exit on close window
turtle.exitonclick() | true |
a4c327eb87a6b535eeb6a6750f86279eedf0b16b | peterlulu666/CourseraStartingWithPython | /Assignment 4.6.py | 1,064 | 4.4375 | 4 | # 4.6 Write a program to prompt the user for
# hours and rate per hour using input to
# compute gross pay. Pay should be the
# normal rate for hours up to 40 and time-and-a-half
# for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function
# called computepay() and use the function to do the
# computation. The function should return a value.
# Use 45 hours and a rate of 10.50 per hour to test
# the program (the pay should be 498.75). You should
# use input to read a string and float() to convert
# the string to a number. Do not worry about error
# checking the user input unless you want to - you
# can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
def computepay(h, r):
h = float(h)
r = float(r)
if h <= 40:
pay = h * r
else:
pay = 40 * r + (h - 40) * r * 1.5
return pay
hrs = float(input("Enter Hours:"))
rate_per_hour = float(input("Enter rate per hour:"))
p = computepay(hrs, rate_per_hour)
print("Pay", p)
| true |
43141dce566e017494468bec1d4ff2d904f45477 | RekidiangData-S/SQLite-Project | /sqlite_App/app.py | 751 | 4.15625 | 4 | import database
#database.create_db()
def main():
print("""
WELCOME TO STUDENTS DATABASE
############################
Select Operation :
(1) for create Table
(2) for Add Record
(3) for Show Records
(4) for Delete Records
(5) for Records Selection
""")
operation = input("Enter your Choice : ")
if operation == "2":
database.add_record()
elif operation == "3":
database.show_all()
elif operation == "4":
database.delete_one(id)
elif operation == "5":
database.select()
elif operation == "1":
print("Please Contact DataBase Admonistrator for this Operation")
else:
print("Try again !!")
main()
#database.add_record()
#database.show_all()
#database.delete_one(id) | true |
d13dcf6e579b458d12f013700eb760936d9f2e4c | cubicova17/Python_scripts | /fib.py | 936 | 4.21875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose: FibNumbers
#
# Author: Dvoiak
#
# Created: 07.10.2014
# Copyright: (c) Dvoiak 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
def fib(x):
"""Recursive function of Fibonacci number"""
if x==0:
return 0
elif x==1:
return 1
else:
return fib(x-1)+fib(x-2)
def fib2(x):
"""Making a list of "x" fib numbers (not recursive)
Returns a list of fib numbers"""
l = [0,1]
while len(l)<=x:
l.append(l[-1]+l[-2])
return l
def fib3(x):
"""Another way to get fib number (not recursive)"""
a = 0
b = 1
for i in range(x-1):
a,b = b,a+b
return b
def main():
N = 7
print fib(N)
print fib2(N)
print fib3(N)
if __name__ == '__main__':
main() | true |
b882a6c8f38065b75d2fdeff2c640cc84ac731f4 | kimchison/HardWay | /ex30.py | 424 | 4.125 | 4 | people = 20
cars = 40
buses = 50
if cars > people:
print "We should take the cars..."
elif cars < people:
print "We should not take the cars..."
else:
print "We can't decide."
if buses > cars:
print "Thats too many buses"
elif buses < cars:
print "Maybe we could take the buses"
else:
print "We still can't decide"
if people > buses:
print "Lets just take the buses"
else:
print "Fine, lets stay at home then..." | true |
576672d0fdacac1002b6d96deed88c7ada514fd4 | mschruf/python | /division_without_divide_operation.py | 1,493 | 4.3125 | 4 | def divide(numerator, denominator, num_decimal_places):
"""Divides one integer by another without directly using division.
Args:
numerator: integer value of numerator
denominator: integer value of denominator
num_decimal_places: number of decimal places desired in result
Returns:
- Type 'float' containing result of division to specified number of
decimal places; final digit not rounded
Raises:
ValueError: if 'denominator' is zero or 'num_decimal_places' is not
positive integer
"""
if denominator == 0 or num_decimal_places < 0:
raise ValueError
pieces = []
# determine sign of final number, then make both numerator and denominator
# positive for simplicity
sign = 1
if numerator < 0:
sign = -sign
numerator = -numerator
if denominator < 0:
sign = -sign
denominator = -denominator
if sign < 0:
pieces.append('-')
# determine integral part
num_units = 0
while numerator >= denominator:
numerator -= denominator
num_units += 1
pieces.append(str(num_units))
pieces.append('.')
# determine fractional part
for _ in range(num_decimal_places):
numerator *= 10
num_units = 0
while numerator >= denominator:
numerator -= denominator
num_units += 1
pieces.append(str(num_units))
return float(''.join(pieces))
| true |
e366ffbd98c7cf6e860489e91b1f07457695b5ab | KishenSharma6/SF-Airbnb-Listings-Analysis | /Project_Codes/03_Processing/Missing_Stats.py | 1,102 | 4.15625 | 4 | import pandas as pd
import numpy as np
def missing_calculator(df,data_type = None):
"""
The following function takes a data frame and returns a dataframe with the following statistics:
data_type takes a string or list of strings referenceing data type
missing_count: Number of missing values per column
missing_%: Returns the % of total values missing from the column
The function also returns a list of columns that containg
"""
if data_type == None:
missing = pd.DataFrame(index=df.isna().sum().index)
missing['count'] = df.isna().sum()
missing['percentage'] = (missing['count']/len(df)) * 100
missing = missing[missing['percentage'] > 0].sort_values(by = 'percentage', ascending = False)
else:
missing = pd.DataFrame(index=df.select_dtypes(data_type).isna().sum().index)
missing['count'] = df.isna().sum()
missing['percentage'] = (missing['count']/len(df)) * 100
missing = missing[missing['percentage'] > 0].sort_values(by = 'percentage', ascending = False)
return(missing) | true |
320c5067f7607baedb6009db27bca5f99e60b74e | muralimandula/cspp1-assignments | /m7/p3/Functions - Assignment-3/assignment3.py | 1,521 | 4.125 | 4 | """
A program that calculates the minimum fixed monthly payment needed
in order pay off a credit card balance within 12 months
using bi-section method
"""
def payingdebt_offinayear(balance, annual_interestrate):
""" A function to calculate the lowest payment"""
def bal_d(balance, pay, annual_interestrate):
""" A function to calculate balance"""
balnace_due = balance
for _ in range(1, 13):
unpaid_balance = balnace_due - pay
balnace_due = unpaid_balance*(1 + (annual_interestrate/12.0))
return balnace_due
payment_low = balance/12.0
monthly_interestrate = annual_interestrate/12.0
payment_high = (balance*((1 + monthly_interestrate)**12))/12.0
payment = (payment_high + payment_low)/2.0
epsilon = 0.03
while True:
# print(bal_d(balance, payment, annual_interestrate))
if bal_d(balance, payment, annual_interestrate) > epsilon:
payment_low = payment
elif bal_d(balance, payment, annual_interestrate) < -epsilon:
payment_high = payment
else:
return round(payment, 2)
payment = (payment_high + payment_low)/2.0
# if bal_d(balance, payment, annual_interestrate) <= epsilon:
def main():
"""
A function for output
"""
data = input()
# data = "4773 0.2"
data = data.split(' ')
data = list(map(float, data))
print("Lowest Payment: " + str(payingdebt_offinayear(data[0], data[1])))
if __name__ == "__main__":
main()
| true |
db9cb334ca1e7502b06fac5edfdc3fb24c47fc64 | jleko75/Python_SQLite | /sqlite_demo.py | 2,147 | 4.15625 | 4 | import sqlite3
from employee import Employee
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('employee.db')
c = conn.cursor()
# budući baza podataka već postoji ovo nam ne treba
# c.execute("""CREATE TABLE employees (
# first text,
# last text,
# pay integer
# )""")
# načini na koji unosimo podatke u tablicu
# 1.
#c.execute("INSERT INTO employees VALUES ('Jozo', 'Leko', 60000)")
# 2.
#c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp_1.first, 'last': emp_1.last, 'pay': emp_1.pay})
# 3. funkcija
def insert_emp(emp):
with conn:
c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})
# načini na koji selektiramo podatke iz tablice
# 1.
#c.execute("SELECT * FROM employees WHERE last='Leko'")
#print(c.fetchone())
# 2.
#c.execute("SELECT * FROM employees WHERE last=?",('Leko'))
# 3.
c.execute("SELECT * FROM employees WHERE last=:last",{'last':'Leko'})
print(c.fetchmany())
# 4. funkcija
def get_emps_by_name(lastname):
c.execute("SELECT * FROM employees WHERE last=:last", {'last': lastname})
return c.fetchall()
def update_pay(emp, pay):
with conn:
c.execute("""UPDATE employees SET pay = :pay
WHERE first = :first AND last = :last""",
{'first': emp.first, 'last': emp.last, 'pay': pay})
def remove_emp(emp):
with conn:
c.execute("DELETE from employees WHERE first = :first AND last = :last",
{'first': emp.first, 'last': emp.last})
emp_1 = Employee('John', 'Doe', 80000)
emp_2 = Employee('Jane', 'Doe', 90000)
emp_3 = Employee('Mirela', 'Doe', 80000)
emp_4 = Employee('Klara', 'Doe', 75000)
emp_5 = Employee('Ema', 'Doe', 85000)
emp_6 = Employee('Ante', 'Leko', 95000)
# insert_emp(emp_1)
# insert_emp(emp_2)
# insert_emp(emp_3)
# insert_emp(emp_4)
# insert_emp(emp_5)
# insert_emp(emp_6)
print(emp_3.first)
emps = get_emps_by_name('Doe')
print(emps)
update_pay(emp_2, 95000)
remove_emp(emp_1)
emps = get_emps_by_name('Doe')
print(emps)
conn.commit()
conn.close()
| false |
7d25fca29ef23d397b784da8567293279cf4d0ca | alvinuy1110/python-tutorial | /oop/basic.py | 867 | 4.40625 | 4 | #####
# This is the OOP tutorial
#####
title = "OOP Tutorial"
print(title)
# Basic class
print("\nBasic Class\n")
# class definition
class A():
# constructor
def __init__(self):
print("classA initialized")
# constructor
def __init__(self, name=None):
print("classA initialized")
self.name=name
def get_name(self):
return self.name;
def set_name(self, name):
self.name = name;
pass
# Main stuff
a = A() # constructor
a.name="classA"
print(a.get_name()) # method call
# unknown property
# attr = a.prop1 # will throw an Error
attr = getattr(a,'prop1', 'defaultValue') # safe retrieval and return defaultValue if not available
print(attr)
a.set_name("newClass") # method invocation
print(a.get_name())
# constructor 2
a2=A("A2")
print(a2.get_name())
# call destructor
del a
del a2
| true |
2aaad3f3fe4b0a57e481f2b752266a7dc636a6e3 | alvinuy1110/python-tutorial | /loop/loop.py | 809 | 4.4375 | 4 | #####
# This is the Looping tutorial
#####
title = "Looping Tutorial"
print(title)
# Looping
print("\n\nLooping\n\n")
myMap = {"key1": "value1", "key2": 1234}
print(myMap)
# print the entries
print("\nKey-Value\n")
for k, v in myMap.items():
print(k, v)
# loop with the index
print("\nIndex-Value\n")
for (i, v) in enumerate(myMap):
print(i, v)
# loop 2 lists
print("\nZip example\n")
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
# while if loop
print("\nWhile loop\n")
x = 0
while (True):
if (x >= 5):
break
elif (x > 2):
print("{0} is greater than 2".format(x))
x = x + 1
else:
print(x)
x = x + 1
| true |
c115a55e98a112cbd4f2170590cfbbb219c9720a | cal1log/python | /tuples.py | 243 | 4.125 | 4 | #!/usr/bin/env python3
'''creating a tuple'''
tup = (10, 20, 30, 40)
'''getting a tuple index value'''
print(tup[2])
'''impossible to change values in a tuple'''
try:
tup[2] = 60
except:
print("a tuple can not changes your values")
| true |
69b832863c278164de52ef419b82d3c4d5bee86d | sudhanvalalit/Koonin-Problems | /Koonin/Chapter1/Exercises/Ex5.py | 1,427 | 4.1875 | 4 | """
Exercise 1.5: Write programs to solve for the positive root of x^2-5 using the Newton-Raphson
and secant methods. Investigate the behavior of the latter with changes in the initial guesses
for the root.
"""
import numpy as np
from scipy.misc import derivative
tolx = 1e-6
def f(x):
return x**2 - 5.0
def Newton_Raphson(f, x):
dx = 0.2
fvalue = f(x)
count = 0
while abs(fvalue) > tolx:
x += dx
fprime = derivative(f, x, 1e-4)
fvalue = f(x)
dx = -fvalue/fprime
count += 1
if count > 1000:
raise Exception("Exceeded the number of iterations.")
break
return x
def Secant(f, x):
diff = 0.1
df = 0.1
while abs(diff) > tolx:
x1 = x + df
f1 = f(x)
f2 = f(x1)
dx = x1 - x
df = f2 - f1
df = -f(x1) * dx/df
diff = f2 - f1
x = x1
return x
def main():
result = Newton_Raphson(f, 4.0)
print("Root using Newton Raphson method: {:.6F}".format(result))
result1 = Secant(f, 4.0)
print("Root using Secant method: {:.6F}".format(result1))
# Investigate the behavior of latter method, i.e. secant method
print("Iter \t Result \t Error")
for i in range(10):
result = Secant(f, i)
diff = np.sqrt(5) - result
print("{:2} \t {:.6f} \t {:.5E}".format(i, result, diff))
if __name__ == "__main__":
main()
| true |
02774b2a40e58bf843a661fde07fc87b91bcdabd | Scientific-Computing-at-Temple-Physics/prime-number-finder-Scadow121 | /primes.py | 1,479 | 4.25 | 4 | # This is a comment. Python will ignore these lines (starting with #) when running
import math as ma
import time
# To use a math function, write "ma." in front of it. Example: ma.sin(3.146)
# These functions will ask you for your number ranges, and assign them to 'x1' and 'x2'
x1 = raw_input('smallest number to check: ')
x2 = raw_input('largest number to check: ')
# This line will print your two numbers out
print x1, x2
""" Text enclosed in triple quotes is also a comment.
This code should find and output all prime numbers between (and including) the numbers entered initially.
If no prime numbers are found in that range, it should print a statement to the user.
Now we end the comment with triple quotes."""
# The rest is up to you!
x1=int(x1)
x2=int(x2)
if x1 < x2:
print "The prime numbers between" ,x1, "and" ,x2, "are:"
x = x1
d = 2
while x != (x2+1):
if x != d:
q = x%d
if q != 0:
if d >= x:
if x > 0:
print x
x = x+1
d = 2
else:
x = x+1
d = 2
else:
d = d+1
else:
x = x+1
d = 2
else:d = d+1
else:
print "Invalid Input Detected!"
time.sleep(0.5)
print "Initiating Self-Destruct Sequence (This may take a while)..."
time.sleep(10)
| true |
f862fbb0d2ebc93e57d6e571899c699563c5d86b | anthonyhertadi/Python-Course | /Day 2/conditional.py | 541 | 4.125 | 4 | # == comparison
# = assignment operator
cuaca ="ga hujan"
if cuaca == "hujan" or cuaca == "Hujan":
print("BAWA PAYUNG CUK!!!")
elif cuaca == "tidak tahu":
print("Jaga-jaga aja bor")
else:
print("Gausa Bawa Payung, Bego!")
nilai = 80
#!= =tidak sama dengan
if nilai >= 75 and nilai <= 90:
print("Lumayan")
elif nilai < 50:
print("Begok!")
if nilai != 100:
print("Tidak Sempurna")
suhu = int(input("Suhu : "))
if suhu > 20 and suhu < 30:
print("Hangat")
elif suhu >= 30:
print("Panas")
else:
print("Dingin") | false |
f1ac4e45bc78b065f5cb55fde220b57f011d71e9 | plotnik102rus/Stady_repo | /Task 2-5.py | 735 | 4.28125 | 4 | #Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
my_list = [9, 6, 5, 3, 3, 2]
print(my_list)
us_num = int(input('Введите число рейтинга: '))
my_list.append(us_num)
my_list.sort(reverse=True)
print(my_list)
| false |
a1b046530bf211a353f6d3fd7dbbc9b7a134020d | test-learn/github-learn | /helloWorld.py | 1,533 | 4.3125 | 4 | print("Hello World!!!")
print("This is my first python program")
intVal = 5
floatVal = 4.54
boolVal = True
print(boolVal)
boolVal = False
print(intVal)
print(floatVal)
print(boolVal)
# single line comment
"""
Saare jahaan se achha
"""
print("Adding above 2 numbers = ", intVal+floatVal)
operator1 = 2
operator2 = 2
operator3 = 2
operator1 **= 2
operator2 //= .5
operator3 %= 2
print(operator1, operator2, operator3)
# String slicing
string = "Alligator"
print(string[:4])
print(string[:3])
print(string[4:7])
print(string[6:])
print("-----------------------------------------\n")
string = "Manchester United"
print(string)
print("Length of the string is", len(string))
print(str(12345)[2])
str1 = "albania"
print("albania in upper case is ", str1.upper())
# print("albania in upper case is ", "albania".upper())
str2 = "BELGIUM"
print("BELGIUM in lower case is ", str2.lower())
# print("BELGIUM in lower case is ", "BELGIUM".lower())
print("\n-------------------Using print for concatenation------------------\n")
print("I am a string")
print(100)
city = "New Delhi"
country = "India"
population = 1000000
print("The capital of %s is %s" % (city, country))
print("The population of %s, the capital of %s is %d" % (city, country, population))
print("\n-------------------Ask user for input-----------\n")
city = input("Which city do you live in?")
print("You are a resident of %s" % city)
print("\n---------Evaluating comparison operators----------------\n")
print(8 > 8)
print(6 <= 7)
print(6 == 8)
print(6 != 7)
| false |
3b7ec7522103f8d09d04e3955ffc1167c1aca47d | abdulwasayrida/Python-Exercises | /Exercise 6.18.py | 569 | 4.21875 | 4 | #Exercise 6.18
#Display a matrix of 0s and 1s
#Rida Abdulwasay
#1/12/2018
def printMatrix(n): #Create a function
from random import randint
for side1 in range (n):
for side2 in range (n):
print(randint(0, 1), end=" ") #randint generates the random number sequence
print(" ")
#Prompt the user to enter a number
def main ():
number = eval (input ("Please enter a number: "))
printMatrix(int(number))
if number <= 0:
print ("That is not a valid number:")
main () #Call the main function
| true |
e65af2007a3a9096a6dc4569338d5b84aa4e93fa | abdulwasayrida/Python-Exercises | /RegularPolygon.py | 1,418 | 4.3125 | 4 | #Exercise 7.5
#Geometry: n-sided regular polygon
#Rida Abdulwasay
#1/14/2018
import math
#Create a Class named RegularPolygon
class RegularPolygon:
def __init__(self, n = 3, side = 1, x = 0, y = 0):
self.__n = n
self.__side = side
self.__x = x
self.__y = y
#Create a function to the number of side (n)
def getN(self):
return self.__n
#Create a function to get the length of the side
def getSide(self):
return self.__side
#Create a function to get the X coordinate of the center
def getX(self):
return self.__x
#Create a function to get the Y coordinate of the center
def getY(self):
return self.__y
#Create a function to get the Perimeter
def getPerimeter(self):
perimeter = self.__n * self.__side
return perimeter
#Create a function to get the Area
def getArea(self):
n = self.__n
side = self.__side
areaPart1 = n * (side **2)
areaPart2 = 4 * math.tan ( math.pi / n )
area = areaPart1 / areaPart2
return area
#Create a function to set the number of sides
def setN(self, n):
self.__n = n
#Create a function to set the side length
def setSide(self, side):
self.__side = side
#Create a function to set the center coordinates
def setXY(self, x, y):
x , y = self.__x , self.__y
| true |
23ebf6103e927ea58302f57258cb19ef96079f0e | abdulwasayrida/Python-Exercises | /Exercise 4.23.py | 985 | 4.21875 | 4 | #Exercise 4.23
#Geometry: point in a rectangle?
#Rida Abdulwasay
#1/8/2018
import turtle
#Prompt the user to enter a point
x , y = eval(input("Please enter a point with two coordinates:"))
#Draw the rectangle
turtle. color ("blue")
turtle. penup ()
turtle. forward (2.5)
turtle. left (90)
turtle. pendown()
turtle. forward (5)
turtle. left (90)
turtle. forward (5)
turtle. left (90)
turtle. forward (10)
turtle. left (90)
turtle. forward (5)
turtle. left (90)
turtle. forward (5)
#Draw the point
turtle. pendown ()
turtle. color ("red")
turtle. begin_fill ()
turtle. penup ()
turtle. goto (x , y)
turtle.pendown ()
turtle. circle (2)
turtle. end_fill ()
turtle. hideturtle ()
#Display the status of the point
x2, y2 = x , y
x1, y1 = 0, 0
distance = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5
if distance <= 10 and distance >= 5.0/2:
print ("Point (" , x , "," , y, ") is inside of the rectangle")
else:
print ("Point (", x , ",", y , ") is outside the rectangle")
| false |
a947b5056d77c1dcb67ece941a86ce3afd26cdf2 | Faranaz08/assignment2 | /decimaltobin.py | 226 | 4.21875 | 4 | # decimal to binary usingfunction
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2 ,end=' ' )
# decimal number
dec = int(input("enter a decimal number"))
convertToBinary(dec)
print() | false |
e6a084c2bf6c0c34e3ffcd81ec94d893412a74db | chengming-1/python-turtle | /W7/lab-7/names.py | 612 | 4.1875 | 4 |
# Create an empty dictionary
names = {}
names['Wash'] = 'Rick'
names['Geier'] = 'Caitlin'
names['DiLisio'] = 'Armand'
names['wang']='chengming'
a = input("Enter the last name of a student: ")
b = input("Enter the First name of a student: ")
names[a]=b
while True:
last_name = input("Enter a student's last name: ")
if last_name in names:
print("Their first name is", names[last_name])
if last_name not in names:
print("I dont know that student")
if last_name == "":
# If the user hits enter without entering a name, stop the loop
break
| true |
09b19aa33e576b71a463bd1aced49b14e2e0d74b | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Exercise/page_85_exercise_04.py | 657 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Assume that the variables x and y refer to strings. Write a code segment that prints these strings in
alphabetical order. You should assume that they are not equal.
Solution:
The sorted words are:
bui
khang
le
ngoc
"""
# Program to sort alphabetically the words form a string provided by the user
my_str = "LE BUI NGOC KHANG"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = [word.lower() for word in my_str.split()]
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
| true |
53878427622bba5b8e795204524588c123540e36 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_203_exercise_02.py | 719 | 4.25 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton.
(Hint: The estimate of the square root should be passed as a second argument to the function.)
Solution:
2.0000000929222947
"""
approximating = 0.000001
def newton2(x, estimate):
"""
Calculate approximating square
:param estimate:
:param x: enter a number to calculate approximating square
:return: the estimate of its square root
"""
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference > approximating:
estimate = newton2(x, estimate)
return estimate
print(newton2(4, 1)) | true |
34df6e92f6125e3408e46221b645c44b2855e728 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_182_exercise_02.py | 569 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: The factorial of a positive integer n, fact(n), is defined recursively as follows:
fact(n) = 1 , when n = 1
fact(n) n * fact (n-1) , otherwise
Define a recursive function fact that returns the factorial of a given positive integer
Solution:
Enter n to calculate: 3
Factorial of 3 is: 6
"""
number = int(input("Enter n to calculate: "))
def fact(n):
if n == 1:
return 1
else:
return n * fact(n - 1)
result = fact(number)
print(f"Factorial of {str(number)} is: " + str(result)) | true |
81125a2c8610d4531755bb4a53cb19aa3d946c96 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_02.py | 640 | 4.40625 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script that inputs a line of encrypted text and a distance value and outputs plaintext using a
Caesar cipher. The script should work for any printable characters
Solution:
Enter the coded text: khoor#zruog
Enter the distance value: 3
hello world
"""
# Request the inputs
code = input("Enter the coded text: ")
distance = int(input("Enter the distance value: "))
plainText = ''
for ch in code:
ordvalue = ord(ch)
cipherValue = ordvalue - distance
if cipherValue < 0:
cipherValue = 127 - (distance - (1- ordvalue))
plainText += chr(cipherValue)
print(plainText) | true |
7a5c1a0d7c416a8f88934c5b6daecb4c36fefa45 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Projects/page_204_exercise_09.py | 623 | 4.125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a program that computes and prints the average of the numbers in a text
file. You should make use of two higher-order functions to simplify the design.
Solution:
Enter the file name: textnumber.txt
The average is 3.0
"""
def main():
fileName = input("Enter the file name: ")
total = 0
count = 0
with open(fileName, 'r') as f:
for line in f:
for num in line.strip().split():
total += float(num)
count += 1
print("\nThe average is " + str(total / count))
if __name__ == '__main__':
main() | true |
47c65a3c577e406863dba437b479719540e39061 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH03/Projects/page_99_exercise_02.py | 1,005 | 4.3125 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Problem: Write a program that accepts the lengths of three sides of a triangle as inputs. The program output should
indicate whether or not the triangle is a right triangle. Recall from the Pythagorean theorem that in a right triangle,
the square of one side equals the sum of the squares of the other two sides.
Solution:
Enter length a: 3
Enter length b: 4
Enter length c: 5
The triangle is a right triangle
Enter length a: 2
Enter length b: 3
Enter length c: 4
The triangle is not a right triangle
"""
# Requests the input
a = int(input("Enter length a: "))
b = int(input("Enter length b: "))
c = int(input("Enter length c: "))
# compute the squares
square1 = a ** 2
square2 = b ** 2
square3 = c ** 2
# Check condition and print ringt triangle or normal triangle
if square1 + square2 == square3 or square2 + square3 == square1 or square1 + square3 == square2:
print("The triangle is a right triangle")
else:
print("The triangle is not a right triangle") | true |
6873aa32b9630205bbc7475864686dd85187beaa | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_132_exercise_06.py | 1,004 | 4.375 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Use the strategy of the decimal to binary conversion and the bit shift left operation defined in Project 5
to code a new encryption algorithm. The algorithm should add 1 to each character’s numeric ASCII value, convert
it to a bit string, and shift the bits of this string one place to the left. A single-space character in the
encrypted string separates the resulting bit strings.
Solution:
Enter a message: Hello, World!
0010011 1001101 1011011 1011011 1100001 011011 000011 0110001 1100001 1100111 1011011 1001011 000101
"""
plainText = input("Enter a message: ")
code = ""
for ch in plainText:
ordValue = ord(ch) + 1
bstring = ""
while ordValue > 0:
remainder = ordValue % 2
ordValue = ordValue // 2
bstring = str(remainder) + bstring
# shift one bit to left
if len(bstring) > 1:
bstring = bstring[1:] + bstring[0]
# Add encrypted character to code string
code += bstring + " "
print(code) | true |
81627d0a80c0c03f3027ff7296a3638a447c37e7 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH04/Projects/page_133_exercise_09.py | 941 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write a script named copyfile.py. This script should prompt the user for the names of two text files.
The contents of the first file should be input and written to the second file.
Solution:
Enter the input file name: test9.txt
Enter the output file name: test9_output
This script creates a program listing from a
source program. This script should prompt the user for the names of two files. The
input filename could be the name of the script itself, but be careful to use a different
output filename!
"""
# request the input
inputFile = input("Enter the input file name: ")
outputFile = input("Enter the output file name: ")
# open the input file and read the text
outfile = open(outputFile, "w")
# open the input files
with open(inputFile, 'r') as file:
index = 1
for line in file:
print(line)
outfile.write("%d>"%index + line)
index += 1
outfile.close() | true |
fc90debc52d5f84e0d03ab770ba10746405d657f | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH07/Exercise/page_218_exercise_03.py | 480 | 4.46875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Add a function named circle to the polygons module. This function expects the same arguments as the square
and hexagon functions. The function should draw a circle. (Hint: the loop iterates 360 times.)
Solution:
"""
import turtle
def polygon(t, length, n):
for _ in range(n):
t.fd(length)
t.lt(360 / n)
bob = turtle.Turtle()
bob.penup()
bob.sety(-270)
bob.pendown()
polygon(bob, 30, 60)
turtle.mainloop()
| true |
26ce3efa3df58e629c706ad5da9b8457ba0e9d52 | lebuingockhang123/L-p-tr-nh-python | /LeBuiNgocKhang_53157_CH06/Exercise/page_199_exercise_02.py | 317 | 4.21875 | 4 | """
Author: Le Bui Ngoc Khang
Date: 12/07/1997
Program: Write the code for a filtering that generates a list of the positive numbers in a list
named numbers. You should use a lambda to create the auxiliary function.
Solution:
[1, 79]
"""
numbers = [1, -2, -66, 79]
result = list(filter(lambda x: x > 0, numbers))
print(result) | true |
5c5fc3250152575883481aca9ee77e0a632f7c95 | Dukiemar/RSA-Encryption | /RSA_Encryption.py | 2,632 | 4.34375 | 4 | import random
def PGP_encryption():
p=input("enter the 1st prime number:")#prompts the user to enter the value for p
q=input("enter the 2nd prime number:")#prompts the user to ented the value for q
message=input("enter message:")
def isPrime(n): #this function ristricts the user to only enter prime numbers
for i in (range (2,n)):
if n%i==0:
return False
return True
if isPrime (int(p))==False or isPrime(int(q))==False:
return "not prime numbers" #if and of the numbers are not prime the system prompts the user
return encrypt(int(p),int(q),str(message))#if the numbers entered are prime the function the runs the encrypt function
def encrypt(p,q,string): #Main encryption algorithm
n=p*q #calculate the value for n which is the product of p x q
z=(p-1)*(q-1) #calculate the value for z which represent phi n
def gcd(x, y): #this is the general function the computes the greatest common divisor between two numbers
while x != 0:
(x, y) = (y % x, x)
return y
for i in range (2,n): #this function computes the value fo e which is relatively prime to z
if gcd(i,z)==1:
e=i
def Extended_Euclid(m,n):# this function utilizes the gcd function to compute the value for d using modulo inverse
if gcd(m,n)!=1:
return "Invalid"
A1,A2,A3 = 1,0,m
B1,B2,B3 = 0,1,n
while B3!=0:
Q = A3//B3
T1,T2,T3 = A1-Q*B1,A2-Q*B2,A3-Q*B3
A1,A2,A3 = B1,B2,B3
B1,B2,B3 = T1,T2,T3
d=A1%n
return d
print ("The values for n :", n,",The value for e:",e,",The value for z:",z,",The value for d:",Extended_Euclid(e,z))
x=[]
for i in range(0,len(string)): #perform conversions to produce the encrypted message in string format
x+=[ord(string[i])]
msg=[]
for a in x:
c=(a**e)%n
msg+=[c]
fin_msg=""
for ele in msg:
fin_msg+=str(ele)+ " "
print("Message:")
print (fin_msg)
def decrypt(fin_msg,n,z,e):# decrypts the encrypted message
dec_msg=""
msg=fin_msg.split(" ")
d=(Extended_Euclid(e,z))
for i in range (0,len( msg)-1):
m= int((int(msg[i])**d)%n)
dec_msg+=chr(m)
return dec_msg
print ("Decrypted Message : ")
return decrypt(fin_msg,n,z,e)
| true |
f7df966b90cd84cadf6805203d190df700a58f9f | prastabdkl/pythonAdvancedProgramming | /chap7lists/plotting/sec5piechart.py | 511 | 4.25 | 4 | # plotting a Piechart
# Author: Prastab Dhakal
# Chapter: plotting
import matplotlib.pyplot as plt
def main():
#create a list of values
values=[20,60,80,40]
#title
plt.title("PIE CHART")
#create a list of labels for the slices.
slice_labels=['1st Qtr','2nd Qtr','3rd Qtr','4th Qtr']
#create a pie chart from the values
plt.pie(values,labels=slice_labels,colors=('r','b','y','c'))
#display the pie chart.
plt.show()
#defining main function
main() | true |
941f9950cf21e526a0cb8c50feb2a553d6e5d4c3 | prastabdkl/pythonAdvancedProgramming | /chap6FilesAndException/others/save_file_records.py | 2,541 | 4.125 | 4 | # This program gets employee data from the user and
# saves it as records in the employee.txt file.
# read the records and show until the end is reached handles the value errors,
# read file error and searches the file until the end is reached
#
# Author: Prastab Dhakal
# Chapter: Files and Exception(Complex problem)
def write_records():
# Get the number of employee records to create.
num_emps = int(input('How many employee records ' +'do you want to create? '))
# Open a file for writing.
emp_file = open('employees.txt', 'w')
# Get each employee's data and write it to the file.
for count in range(1, num_emps + 1):
# Get the data for an employee.
try:
print('Enter data for employee #', count, sep='')
name = input('Name: ')
id_num = int(input('ID number: '))
dept = input('Department: ')
except ValueError:
print('invalid input: ValueError')
# Write the data as a record to the file.
emp_file.write(name + '\n')
emp_file.write(str(id_num) + '\n')
emp_file.write(dept + '\n')
# Display a blank line.
print()
# Close the file.
emp_file.close()
print('Employee records written to employees.txt.')
# Call the main function.
def read_records():
try:
infile = open('employes.txt','r')
name = infile.readline()
while name != '':
id_num = infile.readline()
dept = infile.readline()
#print the data
#name = name.rstrip()
#id_num = id_num.rstrip()
#dept =dept.rstrip()
print('Name:',name,'id_num:',id_num,'dept:',dept,sep='')
name = infile.readline()
infile.close()
except Exception:
print('File not found')
exit(0)
def search_records():
found = False
search = input('Enter the name you want to search?')
emp_file = open('employees.txt','r')
name = emp_file.readline()
while name != '':
id_num = emp_file.readline()
dept = emp_file.readline()
name = name.rstrip()
if name == search:
print('Name:',name)
print('id_num:',id_num,end='')
print('Dept:',dept)
found = True
name = emp_file.readline()
emp_file.close()
if not found:
print('The name',search,'was not found')
def main():
write_records()
read_records()
search_records()
main() | true |
d5fc347cad1f2a3a1cd26cab15653aea5f9bb986 | rodri0315/pythonCSC121 | /chapter3/area_of_rectangles.py | 966 | 4.59375 | 5 | # Chapter 1 Assignment
# Author: Jorge Rodriguez
# Date: February 5, 2017
print('You will enter the length and width for two rectangles')
print('The program will tell you which rectangle has the greater area')
# get length and width of 2 rectangles
rect_length1 = float(input('Enter the length of the first rectangle: '))
rect_width1 = float(input('Enter the width of the first rectangle: '))
rect_length2 = float(input('Enter the length of the second rectangle: '))
rect_width2 = float(input('Enter the width of the first rectangle: '))
# calculate area of both rectangles
rect_area1 = rect_width1 * rect_length1
rect_area2 = rect_length2 * rect_width2
# compare which rectangle has the greater area
if rect_area1 > rect_area2:
print('Your first rectangle has a greater area than your second rectangle')
elif rect_area1 < rect_area2:
print("Your second rectangle had a greater area than your first rectangle")
else:
print('Both rectangles had the same area!')
| true |
fab42d2bbb28bff895054c136584314f4091fb20 | xis24/CC150 | /Python/FreqOfMostFrequentElement.py | 965 | 4.25 | 4 | from typing import List
class FreqOfMostFrequentElement:
'''
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
'''
def maxFrequency(self, nums: List[int], k: int) -> int:
left = 0
ret = 1 # min value
curSum = 0
for right in range(len(nums)):
curSum += nums[right]
# we want to find out the valid condition curSum + k >= nums[right] * (right - left +1)
# so when the while condition stops, it's the condition.
while curSum + k < nums[right] * (right - left + 1):
curSum -= nums[left]
left += 1
ret = max(right - left + 1, ret)
return ret
| true |
29108375b2c46d239764d70dd6b7fc4416c5e89d | xis24/CC150 | /Python/SortColors.py | 931 | 4.15625 | 4 | from typing import List
class SortColors:
# 1. discuss the approach
# 2. run the test case
# 3. ask if I can start to code
# 4. start to code
# 5. run test case with code
# 6. time complexity and space complexity
def sortColors(self, nums: List[int]) -> None:
zeros = 0 # position next zero should be
twos = len(nums) - 1 # posisiton next two should be
cur = 0 # current position
while cur <= twos:
if nums[cur] == 2:
nums[cur], nums[twos] = nums[twos], nums[cur]
twos -= 1
elif nums[cur] == 0:
nums[cur], nums[zeros] = nums[zeros], nums[cur]
zeros += 1
cur += 1
else:
cur += 1
return nums
if __name__ == '__main__':
obj = SortColors()
print(obj.sortColors([2, 1, 0, 2]))
print(obj.sortColors([2, 2, 1, 2]))
| true |
2d8c9ba19b177f95ecf6e65da4c5a5c353390d42 | travisthurston/OOP_example | /Card.py | 549 | 4.125 | 4 | #Card class is a blueprint of the card object
#This is the parent or base class for Minion
class Card:
#initializer to create the attributes of every class object
def __init__(self, cost, name):
self.cost = cost
self.name = name
#attributes - argument - parameter - describes the object
#give the card a cost attribute
#give the card a name attribute
#behaviors - methods - functions
def printCardInfo(self):
print("Name:" + self.name)
print("Cost:" + str(self.cost))
| true |
4a2186d1443b1dcba7bd4a02c93afe9cb55e4855 | Ustabil/Python-part-one | /mini_projects/guess_the_number/guess_the_number.py | 2,497 | 4.28125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#Codeskulptor URL: http://www.codeskulptor.org/#user40_06oB2cbaGvb17j2.py
import simplegui
import random
current_game = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
# remove this when you add your code
global secret_number
if current_game == 0:
range100()
elif current_game == 1:
range1000()
else:
print "Something bad happened..."
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
# remove this when you add your code
global secret_number
global allowed_Guesses
global current_game
current_game = 0
allowed_Guesses = 7
secret_number = random.randrange(0, 100)
print "\nGuess a number between 0 and 100, within", allowed_Guesses, "guesses!"
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global allowed_Guesses
global current_game
current_game = 1
allowed_Guesses = 10
secret_number = random.randrange(0, 1000)
print "\nGuess a number between 0 and 1000, within", allowed_Guesses, "guesses!"
def input_guess(guess):
# main game logic goes here
global allowed_Guesses
guess = int(guess)
allowed_Guesses -= 1
# remove this when you add your code
print "\nGuess was", guess
if guess == secret_number:
print "Correct!"
new_game()
elif allowed_Guesses == 0:
print "No more guesses!"
new_game()
elif guess > secret_number:
print "Lower!"
print "Remaining guesses:", allowed_Guesses
elif guess < secret_number:
print "Higher!"
print "Remaining guesses:", allowed_Guesses
else:
print "Something weird happened o.O"
# create frame
frame = simplegui.create_frame('Guess the Number', 200, 200)
# register event handlers for control elements and start frame
button1 = frame.add_button('Range is 0 - 100', range100, 200)
button2 = frame.add_button('Range is 0 - 1000', range1000, 200)
inp = frame.add_input('Enter a guess:', input_guess, 200)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
| true |
4523e4efe62db4005d9e09b9fa8e5f20b548ef81 | grebwerd/python | /practice/practice_problems/shortestPath.py | 1,021 | 4.15625 | 4 | def bfs_paths(graph, start, goal):
queue = [(start, [start])] #queue is a list made up of a tuple first tuple is a start and the second tuple is a list
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path): #for each next adjacency node not in the set already
print("next is ", next)
if next == goal: # if next equals the goal
yield path + [next] #add the goal to the path, breaks out and returns a generator
else:
print("Adding the node ", next, " to the path")
queue.append((next, path + [next]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
def main():
graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])}
print(shortest_path(graph, 'A','F'))
if __name__ == '__main__':
main() | true |
befb06130ebf46def192f3a33c799e7139303290 | abaker2010/python_design_patterns | /decorator/decorator.py | 861 | 4.125 | 4 | """
Decorator
- Facilitates the addition of behaviors to individual objects without
inheriting from them
Motivation
- Want to augment an object with additional functionality
- Do no want to rewrite or alter existing code (OCP)
- Want to keep new functionality separate (SRP)
- Need to be able to interact with existing structures
- Two options:
- Inherit from required object (if possible)
- Build a Decorator, which simply references the decorated object(s)
"""
import time
def time_it(func):
def wrapper():
start = time.time()
result = func()
end = time.time()
print(f'{func.__name__} took {int(end - start) * 1000} ms')
return result
return wrapper
@time_it
def some_op():
print('Starting op')
time.sleep(1)
print('We are done')
return 123
# some_op()
# time_it(some_op)
some_op()
| true |
69ceec17993f350329a7f6214657fc9aae84ef1a | Zolton/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 806 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of
***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
test = "THtHThth"
test2 = "abcthefthghith"
test3 = "abcthxyz"
count = 0
def count_th(word):
global count
if len(word) == 0:
return count
if word[:2] == "th":
count = count + 1
word = word[2:]
count_th(word)
elif word[:2] != "th":
if word[1:3] == "th":
count = count + 1
word = word[2:]
count_th(word)
elif word[1:3] != "th":
word = word[2:]
count = count
count_th(word)
return count
print(count_th(test))
| true |
7c2549bcb4f95d76184c334a4968773a0ab7e500 | Zchhh73/Python_Basic | /chap6_struct/struct_break_continue.py | 208 | 4.15625 | 4 | for item in range(10):
if item == 3:
break
print('Count is : {0}'.format(item))
print('\n')
for item in range(10):
if item == 3:
continue
print('Count is : {0}'.format(item)) | true |
9ad465abc7b49c53b21b65897650da85f39303f0 | Lousm/Python | /01_py基础/第1周/day05/test06.py | 2,383 | 4.40625 | 4 | # 学生管理
a = {'001': {"name": '小张', 'age': 21, "address": "北京"},
'002': {"name": '小明', 'age': 22, "address": "山东"},
'003': {"name": '小王', 'age': 23, "address": "河北"},
'004': {"name": '小李', 'age': 24, "address": "北京"}}
def add():
snum = input("请输入你要添加的学号:")
while True:
if snum in a:
snum = input("已存在!请输入你要添加的学号:")
else:
break
b = {}
name = input("请输入姓名:")
age = input("请输入年龄:")
address = input("请输入地址:")
b['name'] = name
b['age'] = age
b['address'] = address
a[snum] = b
print("添加成功!添加的信息为:%s" % snum, end='')
print(a.get(snum))
def change():
b = {}
snum = input("请输入你要修改的学号:")
while True:
if snum not in a:
snum = input("不存在!请输入你要修改的学号:")
else:
break
name = input("请输入要修改的姓名:")
age = input("请输入要修改的年龄:")
address = input("请输入要修改的地址:")
a.get(snum)['name'] = name
a.get(snum)['age'] = age
a.get(snum)['address'] = address
a[snum] = a.get(snum)
print("修改成功!修改后的信息为:%s" % snum, end='')
print(a.get(snum))
def find():
snum = input("请输入你要查找的学号:")
while True:
if snum not in a:
snum = input("不存在!请重新输入学号:")
else:
break
print("%s的信息为:" % snum, end='')
print(a.get(snum))
def delt():
snum = input("请输入你要删除的学号:")
while True:
if snum not in a:
snum = input("不存在!请重新输入你要删除的学号:")
else:
break
del a[snum]
print("删除成功!", a)
def start():
while True:
oper = input(
"请输入你要进行的操作:\n\ta.增加学生记录.\n\tb.修改学生记录.\n\tc.删除学生记录.\n\td.查看学生信息.\n\tq.退出学生系统.\n")
if oper == 'a':
add()
elif oper == 'b':
change()
elif oper == 'c':
delt()
elif oper == 'd':
find()
else:
exit(0)
start()
| false |
4b1bb8a4e501b50680d29d4688405b1a5c0f8bf4 | mgtz505/algorithms | /implementations/sorting_algorithms/quicksort.py | 518 | 4.15625 | 4 | print("Implementation of Quicksort")
test_data = [3,11,4,0,7,2,12,7,9,6,5,10,3,14,8,5]
def quickSort(N):
length = len(N)
if length <= 1:
return N
else:
larger, smaller = [], []
pivot = N.pop()
for num in N:
if num < pivot:
smaller.append(num)
else:
larger.append(num)
return quickSort(smaller) + [pivot] + quickSort(larger)
print(quickSort(test_data)) #[0, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 10, 11, 12, 14]
| true |
3e36b2f72dbe1c248365e51566f81a21e6e18b3e | alex-mucci/ce599-s17 | /18-Design and Classes/Car.py | 2,655 | 4.4375 | 4 | #constansts
START_NORTH = 0
START_SOUTH = 0
START_EAST = 0
START_WEST = 0
# Define the class
class Car(object):
"""
Base class for a car
"""
def __init__(self, color,location = [0,0],direction = 'N'):
if len(location) < 2 or len(location) > 2:
print('location is the x,y coordinates of the car')
else:
self.color = color
self.location = location
self.x = location[0]
self.y = location[1]
self.direction = direction
def go(self,units,movement):
"""
function to move the car the given distance in the given direction
"""
if movement == 'forward':
if self.direction == 'N':
self.y = self.y + units
elif self.direction == 'S':
self.y = self.y - units
elif self.direction == 'E':
self.x = self.x + units
elif self.direction == 'W':
self.x = self.x - units
else:
print('Direction options are N, S, E, and W')
self.location = [self.x,self.y]
elif movement == 'backward':
if self.direction == 'N':
self.y = self.y - units
elif self.direction == 'S':
self.y = self.y + units
elif self.direction == 'E':
self.x = self.x - units
elif self.direction == 'W':
self.x = self.x + units
else:
print('Direction options are N, S, E, and W')
self.location = [self.x,self.y]
else:
print('Possible movements are forward and backward')
def turn_right(self):
if self.direction == 'N':
self.direction = 'E'
elif self.direction == 'S':
self.direction = 'W'
elif self.direction == 'E':
self.direction = 'S'
elif self.direction == 'W':
self.direction = 'N'
else:
print('direction is wrong')
def turn_left(self):
if self.direction == 'N':
self.direction = 'W'
elif self.direction == 'S':
self.direction = 'E'
elif self.direction == 'E':
self.direction = 'N'
elif self.direction == 'W':
self.direction = 'S'
else:
print('direction is wrong')
def printcar(self):
print('Car Color is ' + self.color)
print('Car Location is ')
print(self.location)
print('Car Direction is ' + self.direction)
| true |
8969c70857b05f92b3cec8f3339bb543498b39e3 | kolevatov/python_lessons | /simple_object.py | 550 | 4.15625 | 4 | # Simple object
class Simple(object):
"""Simple object with one propertie and method"""
def __init__(self, name):
print("new object created")
self.__name = name
def __str__(self):
return "Simple object with name - " + self.__name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print ("Wrong value")
else:
self.__name = new_name
obj1 = Simple("Buba")
print (obj1)
obj1.name = ""
print (obj1) | true |
fd4890d93ad997451e2fb0a222e793c5beb4a3bb | kolevatov/python_lessons | /calculation table.py | 711 | 4.34375 | 4 | # Составить программу вывода таблицы умножения на число M
# Таблица составляется от M * a, до M * b, где M, a, b запрашиваются у пользователя.
print("Программа ввывода таблицы умножения на число M")
m = int(input("Введите число M: "))
a = int(input("Введите число a: "))
b = int(input("Введите число b: "))
while a > b:
print("a должно быть меньше b")
a = int(input("Введите число a: "))
b = int(input("Введите число b: "))
while a <= b:
print(m, "x", a, "=", m * a)
a += 1
# | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.