blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
47f22bd3d24bf9fbbade6c4dfd4188e67b8c6978 | vaniparidhyani/Pythonic | /Sandbox/Easy/list_split.py | 388 | 4.125 | 4 | #!/usr/bin/python
#There is a given an array and split it from a specified position, and move the first part of array add to the end.
def splitList(mylist,n):
first_half = []
second_half = []
for i in range(0,n):
first_half.append(mylist[i])
for j in range(n,len(mylist)):
second_half.append(mylist[j])
print second_half+first_half
li = [1,2,3,4,5,6]
splitList(li,2)
| true |
54d570dcf607b80fc5f5af7a7daaddae4b551e35 | vaniparidhyani/Pythonic | /Sandbox/Easy/armstrong_no.py | 513 | 4.3125 | 4 | #!/usr/bin/python
#Given a number x, determine whether the given number is Armstrong number or not.
# Examples:
#Input : 153
#Output : Yes
#153 is an Armstrong number.
#1*1*1 + 5*5*5 + 3*3*3 = 153
#Input : 120
#Output : No
#120 is not a Armstrong number.
#1*1*1 + 2*2*2 + 0*0*0 = 9
no = raw_input("Enter no to check if it's armstrong or not : ")
no_of_digits = len(no)
sum = 0
for i in no:
sum += pow(int(i),no_of_digits)
if sum == int(no):
print "It is Armstrong"
else:
print "It is not Armstrong"
| true |
bf5788c47889f5a2e2b7ac65d5534fdce9d99e5f | githuan/python_journey | /Intro_to_Python_Development/numbers.py | 1,018 | 4.40625 | 4 | #!/usr/bin/env python3
# Numbers can be stored in variables
pi = 3.14159
print(pi)
# You can do math with numbers
# + Addition
# - Subtraction
# * Multiplication
# / Division
# ** Exponent
first_num = 6
second_num = 2
print(first_num + second_num)
print(first_num ** second_num)
# If you combine strings with numbers, Python gets confused
days_in_feb = 28
# print(days_in_feb + ' days in February') # WRONG
# Correction - Convert number to string so Python will treat it as concatenate strings
print(str(days_in_feb) + ' days in February')
# Numbers can be stored as strings
# numbers stored as strings are treated as strings
first_num = '5'
second_num = '6'
print(first_num + second_num)
# The input function always returns strings
first_num = input('Enter first number ')
second_num = input('Enter second number ')
print(first_num + second_num)
# Numbers stored as strings must be converted to numeric values before doing math
print(int(first_num) + int(second_num))
print(float(first_num) + float(second_num))
| true |
9f6f2516f8d6c308d10a0f04db9af779a49aa3fa | githuan/python_journey | /Crash_Course/extras/age_restrictions.py | 311 | 4.25 | 4 | #!/usr/bin/env python3
age = input("How old are you? ")
age = int(age)
if age <= 17:
print("\nYou will be able to vote when you are a little older.")
elif age <= 20:
print("\nYou can vote but no tobaco of alcohol will be served.")
else:
print("\nYou can party but do not drive under infulence.")
| true |
c2296718ef6dd705dc40650daeaf5c9734909015 | everyusernameistaken1/learning- | /guessnumber.py | 748 | 4.15625 | 4 | #Guess a number
import random
secretNumber=random.randint(1,10)
#Ask for name
print('Hello! What is your name?')
name= input()
print('Well, ' + name + ' I am thinking of a number between 1 and 10.')
print('DEBUG: Secret number is ' +str(secretNumber))
for guessesTaken in range(1,7):
print('Take a guess!')
guess= int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break #This condition is for the correct guess.
if guess == secretNumber:
print('You guessed right! You took ' + str(guessesTaken) + ' guesses.')
else:
print('The correct number was ' + str(secretNumber))
| true |
d47fc4acc3dd5b41b8e447325d13729d70f281c5 | kblasi/portfolio | /hw5.py | 2,052 | 4.4375 | 4 | '''
This program takes a csv file with population data in Iowa from 2010-2018 and
puts it into a dictionary. It then prompts the user to input the desired key
which is the year, and it will print out the population. If the user enters
an empty string, the program will exit. If the user enters invalid key, it will
explain the directions and prompt them again.
'''
#Author: Katie Blasi
pop_file = open("PEP_2018_PEPANNRES.csv")
#read the line of the file
pop_file_records = pop_file.readlines()
#go thro each line of different state
for pop_record in pop_file_records:
#create dictionary to put key and values in
pop_years={}
#split the populations into a list by each comma
record_list = pop_record.split(',')
#first year of data is 2010
curr_year = 2010
#iterate through the list of data
for index in range(len(record_list)):
#set the dictionary key to the corresponding data value
pop_years[str(curr_year)] = eval(record_list[index])
#update the year
curr_year+=1
#welcome print statements and directions
print("Welcome to the Iowa Population Retriever")
print("Enter year between 2010 and 2018 to get Iowa's population that year")
print("Press enter to exit")
user_input = input("Enter year: ")
#loop with conditions
entering_years = True
while entering_years:
#if entered year is in the keys
if user_input in pop_years:
#print and prompt again
print(pop_years[user_input])
user_input = input("Enter year: ")
#if user enters empty string
elif user_input == '':
print("Thank you for using our service")
#change condition to false and print thanks
entering_years = False
#else (input not in key)
else:
#print directions and prompt again
print("Enter year between 2010 and 2018 to get Iowa's population that year")
print("Press enter to exit")
user_input = input("Enter year: ")
#close the file
pop_file.close() | true |
a1a984f1a29611bf05d1a91a6523b1dd69c7964b | Akumatic/ExamScan | /scan/utils.py | 1,611 | 4.375 | 4 | # SPDX-License-Identifier: MIT
# Copyright (c) 2019 Akumatic
import math
def distance (
p: tuple,
q: tuple
) -> float:
""" Calculates direct distance between two points given as tuples.
Args:
p (tuple):
A tuple containing x and y coordinates
q (tuple):
A tuple containing x and y coordinates
Returns:
A float with the distance between given points as value
"""
return math.sqrt((p[0] - q[0])**2 + (p[1] - q[1])**2)
def find_closest_element (
points: list,
point: tuple
) -> tuple:
""" Finds the closes element to a given point
Args:
points (list):
A list containing tuples of coordinates (x, y)
point (tuple):
The (x, y) coordinates of the given point
Returns:
the tuple of the closest point and the distance
between the given and closest point
"""
start, min_dist = None, None
for p in points:
dist = distance(p[:2], point)
if min_dist is None or dist < min_dist:
start, min_dist = p, dist
return start, min_dist
def circularity (
area: float,
perimeter: float
) -> float:
""" Calculates the circularity shape factor with given area and perimeter.
Args:
area (float):
area of a shape
perimeter (float):
length of the perimeter of a shape
Returns:
A float with the circularity shape factor as value
"""
if perimeter == 0:
return 0.0
return (4 * math.pi * area) / (perimeter ** 2) | true |
404e4237e3bee8e6e849ba5ce6d73b630da573bb | ihorios/game | /lol.py | 830 | 4.28125 | 4 | # - *- coding: utf-8 - *-
# Lesson 1
cars = "BMW, Ferrary, Toyota, Opel"
print(cars)
cars_list = ['BMW', 'Ferrary', 'Toyota', 'Opel']
print(cars_list)
print(cars_list[3])
cars_list[2] = "Mersedes"
print(cars_list)
fred = cars_list[2]
print(fred)
print(cars_list[1:3])
numbers = [1, 2, 3, 4, 5]
strings = ["досить ", "цифри ", "рахувати"]
my_list = numbers + strings
print(my_list)
cars_list.append("Lamborgini")
print(cars_list)
del cars_list[0]
print(cars_list)
list1 = [1, 2, 3, 4, 5]
list2 =['I', "am", "a", 'little', 'doc']
list3 = list1 + list2
print(list3)
favorite_sports = {'Кріштіан Рональдо': 'Футбол',
'Майкл Типпетт': 'Баскетбол',
'Эдвард Элгар': 'Бейсбол',
'Ребекка Кларк': 'Нетбол',
'Этель Смит': 'Бадминтон',
'Фрэнк Бридж': 'Регби'}
print(favorite_sports)
# Lesson 2
import
| false |
913306307e8a3f9d35b041bfd3cc43e8a05f5f7c | kajetan-mazur/isdivide2 | /function-exercise-reverse-string.py | 252 | 4.125 | 4 | def reverse_string(sentence):
return sentence[::-1]
reversed_string = reverse_string("John have cat")
print(reversed_string)
def reversing_string():
sentece = input("Give me sentence: ")
return sentece[::-1]
print(reversing_string())
| false |
e251b5bf490bc24e59868a7620b34444edb206f1 | abzilla786/eng-54-python-basics | /exercise_109.py | 889 | 4.25 | 4 | while True:
age = int(input('What is your age? '))
driver_licence = input('Do you have a drivers licence? (Y/N) (Write exit to end)\n')
if (age >= 18) and (driver_licence == 'Y'):
print('You can vote and drive')
elif (age >= 16) and (age < 18):
print('you can\'t legally drink but your mates/uncles might have your back')
elif age >= 18:
print('You can vote')
elif driver_licence == 'Y':
print('You can drive')
elif age < 18:
print('You\'re too young, go back to school!')
elif driver_licence == 'exit':
break
print('No idea mate')
# - You can vote and drive
# - You can vote
# - You can driver
# - you can't legally drink but your mates/uncles might have your back (bigger 16)
# - Your too young, go back to school!
# as a user I should be able to keep being prompted for input until I say 'exit'
| true |
36cdcc23754698f15ca7be2f981ad0bace99a21d | abzilla786/eng-54-python-basics | /exercise_108.py | 930 | 4.25 | 4 | # Dictionary basics :D
#1 - Define a dictionary call story1, it should have the followign keys:
# start, middle and end
story_dict = {'start': 'In the beginning there was a hero named bob',
'middle': 'as he fought on with the evil wizard his bald head kept shining like a cue ball',
'end': 'the hero bob slipped and landed on the edge of his own sword....the end'
}
#2 - Print the entire dictionary
print(story_dict)
#3 - Print the type of your dictionary
print(type(story_dict))
#4 - Print only the keys
print(story_dict.keys())
#4 - print only the values
print(story_dict.values())
#5 - print the individual values using the keys (individually, lots of printing commands)
print(story_dict['start'])
print(story_dict['middle'])
print(story_dict['end'])
#6 - Now let's add a new key:value pair.
# 'hero': yourSuperHero
story_dict['hero'] = 'BOB'
print(story_dict['hero'])
| true |
f35629486b843d1fdc96f213f1a666b66e07e414 | stOracle/Migrate | /Programming/CS303E/Hailstone.py | 1,650 | 4.28125 | 4 | # File: Hailstone.py
# Description: A program generating the number of "hailstone" operations for a range of numbers
# Student Name: Stephen Rauner
# Student UT EID: STR428
# Course Name: CS 303E
# Unique Number: 50475
# Date Created: 9/20/15
# Date Last Modified: 9/20/15
def main():
#define variables
cycle_length = 0
max_length = 0
num_max = 0
#prompt the user to enter the range
lo = int(input("Enter starting number of the range:"))
hi = int(input("Enter ending number of the range:"))
#error checking of input
while (lo <= 0) or (lo >= hi):
lo = int(input("Enter starting number of the range:"))
hi = int(input("Enter ending number of the range:"))
#go through each number in that range (outer loop)
while (lo <= hi):
#assign dummy variable num so lo doesn't loop forever and
#set cycle_length = 0 before each iteration of inner loop
cycle_length = 0
num = lo
#inner loop to do calculations - stops when num == 1
while (num != 1):
#for each number in that range compute the cycle length
if (num % 2 == 0):
num = num // 2
cycle_length += 1
else:
num = num * 3 + 1
cycle_length += 1
#if cycle length is greater than or equal to the max cycle length replace max cycle
#length with current cycle length and num_max
#with current number
if (cycle_length >= max_length):
num_max = lo
max_length = cycle_length
#moving on to next number
lo += 1
#outside of the two loops print out the result
print("The number", num_max, "has the longest cycle of", max_length, end=".")
main() | true |
ad4e4b718b9086aaaf56c9b74944dfb93af1ef5b | stOracle/Migrate | /Programming/CS303E/ferlittle.py | 585 | 4.15625 | 4 | def ferlittle(num):
for a in range (2, num):
if (a % 7 == 0) or (a % 13 == 0) or (a % 31 == 0):
continue
elif ((a ** (num - 1)) % num != 1):
return [False, a]
#elif (num % a == 0):
#return [False, a]
return [True]
def main():
print ("\n{:>40}:".format("Fermat's Little Theorem"))
print ("{:>36}".format("a^(p-1) % p == 1"))
num = int(input("\nUse Fermat's little number to check for primality: "))
sol = ferlittle(num)
if (sol[0] == False):
print ("{} is not prime: consider a = {}".format(num, sol[1]))
else:
print ("{} is prime".format(num))
main()
| false |
693118d8d5b966a4ac32c60adfd349afb0d05529 | sunshinexf3133/Python_BronzeIII | /hanjia/.svn/pristine/b3/b3f71c6dcb6f1d126370536c55614da81514ddfc.svn-base | 796 | 4.3125 | 4 | #coding:utf-8
#使用列表解析进行筛选
###下面函数使用列表解析删除字符串中的所有元音
#[c for c in s if c.lower() not in 'aeiou'],这是一个筛选型列表解析,
#它以每次一个字符的方式扫描s,将每个字符转换为小写,再检查它是不是元音。
#如果是元音,则不将其加入最终的列表,否则将其加入最终列表
#
#该列表解析的结果是一个字符串列表,因此我们使用join将所有字符串拼接成一个,
#再返回这个字符串。
#eatvowels.py
def eat_vowels(s) :
"""Removes the vowels from s."""
return ''.join([c for c in s if c.lower() not in 'aeiou'])
if __name__ == "__main__" :
s = raw_input("Please input a string :")
print('After eat_vowels:{}'.format(eat_vowels(s)))
| false |
0c195e84f58bc0ce5bbee4da5cf030d9aec1f573 | cs-richardson/whosaiditpart1-2-tle21 | /Who Said It? .py | 1,195 | 4.15625 | 4 | def get_counts(file_name):
dictionary = dict() #Empty dictionary
file = open(file_name,'r') #Open files and put it in read mode
count = 0 #The count variable, used to count how many words there are
for line in file:
text = file.read() #This takes the whole text itself
raw_words = text.split() #This splits it into words
for i in range(0, len(raw_words)): #Looping from 0 to
words = raw_words[i].lower()
if words in dictionary: #If the words are already in the dictionary, I added one to it
dictionary[words] = dictionary[words] + 1
count = count + 1
else:
dictionary[words] = 1 #If the words are not in the dictionary, I make a new element and make it equal to one.
count = count + 1
dictionary.update({'_total': count}) #Adds the last element "Total" into the dictionary with the amount of words
print (dictionary) #Prints out the dictionary, to see how frequently used each words are
file.close() #Closes file
get_counts("hamlet-short.txt")
| true |
164f8da006add28ec4c6224a6366692c36a95dc1 | Nathaliaz/python_udemy | /prueba_bucles.py | 1,015 | 4.28125 | 4 | """Los bucles for y while son estructuras de control iterativas (también llamadas cíclicas).
Permiten ejecutar un mismo código, de manera repetida, mientras se cumpla una condición."""
anio = 2001
while anio <= 2012:
print(anio)
"""Verificar que en la consola se ejecuta continuamente el valor 2001.
Presionar el botón Stop para finalizar la ejecución.
Este comportamiento se debe a que la variable anio vale 2001, y la condición while especifica
que se imprima el valor de dicha variable mientras sea menor a 2012."""
"""Se agrega una nueva linea.
Ahora el bucle while realiza una nueva acción: Mientras el año sea menor a 2012 va a imprimir el año, y además, va a sumarle 1.
Cada vez que hace esto actualiza el valor de la variable anio.
Ejemplo: La primera vez tomará anio = 2001, al ser menor que 2012, imprimirá 2001 y además le sumará 1 al valor de la variable,
quedando la variable anio con el valor 2002."""
anio = 2001
while anio <= 2012:
print(anio)
anio += 1
| false |
022c33553582b3f6096ba0291d1939a92187884e | Scientific-Computing-at-Temple-Physics/planets-with-io-gt8mar | /Forst_WeightPlanets.py | 1,442 | 4.15625 | 4 | # Marcus Forst
# Weights on Different Planets
# Inputs: planet name, altitude above avg radius, explorer mass
import math as ma
pname= input("What is the name of the planet?")
alt=float(input('What is the altitude above the average radius of the planet?'))
mass=float(input('What is the mass of the explorer?'))
G=6.674*(10**(-11))
# This reads the data file
f=open("planet_data.dat", "r")
# Ignores the first line
for line in f:
if line[0]=="#": continue
data = line.split(";") #splits the line into lists using the delimeter ;
if data[0].upper() == pname.upper(): #selects the correct line of data for the given planet
prad = data[1].split() #selects the numerical value for the radius
den = data[2].split() #selects the numerical value for the density
break #stops the program from running needlessly past the selected planet
prad_n = float(prad[0])#makes the numerical values floats
den_n = float(den[0])
si_prad = prad_n*1000 #converts to SI
si_den = den_n*1000
m_planet = float(si_den*(4.0/3.0)*ma.pi*(si_prad**3)) #computes the mass of the planet
Fg = round((G*m_planet*mass)/((si_prad+alt)**2),3) #computes the force due to gravity (weight)
grav = round((G*m_planet)/((si_prad+alt)**2),3) #computes the acceleration due to gravity
print ("The weight of the explorer is", Fg, "N")
print ("The acceleration due to gravity is", grav, "g's")
# Outputs: the explorer's weight, the Gravitational acceleration in g's
f.close()
| true |
584e6d495a102cc614385a489b50d745dade3dbe | blackman147/pythonditel | /ChapterThree/Employee.py | 1,785 | 4.28125 | 4 | class Employee:
_firstname = ""
_lastname = ""
_monthly_salary = 0
_yearly_salary = 0
_monthly_salary_after_increase = 0
_yearly_salary_after_increase = 0
def employee_data(self, firstname, lastname, salary):
self._firstname = firstname
self._lastname = lastname
if salary > 0:
self._monthly_salary = salary
else:
print("invalid salary amount")
def yearly_salary(self):
self._yearly_salary = self._monthly_salary * 12
def salary_increment_rate(self, rate):
self._monthly_salary_after_increase = self._monthly_salary + ((rate / 100) * self._monthly_salary)
def yearly_salary_after_increment(self, rate):
self._yearly_salary_after_increase = (self._monthly_salary + ((rate / 100) * self._monthly_salary)) * 12
def display(self):
print("Employee firstname is: " + str(self._firstname))
print("Employee lastname is: " + str(self._lastname))
print("Employee monthly salary is: " + str(self._monthly_salary))
print("Employee yearly salary is: " + str(self._yearly_salary))
print("Employee salary after 10% increase is: " + str(self._monthly_salary_after_increase))
print("Employee yearly salary after 10% increase is: " + str(self._yearly_salary_after_increase))
def main():
emp1 = Employee()
emp1.employee_data("Joy", "Udom", 100000)
emp1.yearly_salary()
emp1.salary_increment_rate(10.0)
emp1.yearly_salary_after_increment(10.0)
emp1.display()
print( "Employee two ")
emp2 = Employee()
emp2.employee_data("Blackman", "Francis", 100000)
emp2.yearly_salary()
emp2.salary_increment_rate(10.0)
emp2.yearly_salary_after_increment(10.0)
emp2.display()
main()
| false |
e7c1cbab91eb26ebbc0a556ce61e8d53b8f5f737 | bmlam/learn-py | /simple_decorator.py | 863 | 4.15625 | 4 | #! /usr/bin/python3
def our_decorator(func): # our_decorator amends/enriches the behaviour of foo
def some_inner_func(x): # argument must have the same name as the argument of func ?!
print("Before calling " + func.__name__)
func(x)
print("After calling " + func.__name__)
return some_inner_func
def foo(x):
print("Hi, foo has been called with '%s'" \
% str(x)) # str serves to convert every data type to string
foo( "call foo directly" )
foo( 123 )
#print("We now decorate foo with f:")
#foo = our_decorator(foo)
print("****** after decoration:")
foo(x= 42)
# we do not need to change the behaviour of foo for good. Instead we can create a "new" function
# which
foo1 = our_decorator(foo)
foo1( "foo1")
foo("foo")
our_decorator(123) # this line yields nothing in stdout !
print( type(our_decorator(123) ) )
| true |
2732dab198f4d3b65b42906dc8457912628de46f | StombieIT/Frameworks | /cls_sqlite3.py | 2,815 | 4.25 | 4 | class DataBase(sqlite3.Connection):
def __init__(self, filename):
'''
filename serves as the name of file of your
database when you initialize creating object
of this class
'''
self.filename = filename
self.db = sqlite3.Connection(self.filename)
self.cursor = self.db.cursor()
def create(self, table, **kwargs):
'''
table is the name of table which you want to
create
kwargs is arguments in which key serves as
the name of var and the value of it serves
as type of it
'''
var = ["{} {}".format(key.strip(), value.strip().upper()) for key, value in kwargs.items()]
self.cursor.execute("CREATE TABLE IF NOT EXISTS {t}({v})".format(t=table, v=', '.join(var)))
self.db.commit()
def delete(self, table):
'''
table is the name of table you want to delete
'''
self.cursor.execute("DROP TABLE {t}".format(t=table))
self.db.commit()
def log(self, table, **kwargs):
'''
table is the name of table you want to use
kwargs is arguments in which key serves as
name in which you want to log something and
the value of it serves as value you want to log
'''
keys = []
for key in kwargs.keys():
keys.append(key.strip())
values = []
for value in kwargs.values():
values.append(value.strip())
self.cursor.execute("INSERT INTO {t} ({k}) VALUES ({v})".format(t=table, k=', '.join(keys), v=', '.join(values)))
self.db.commit()
def search(self, table, **kwargs):
'''
table is the name of table you want to use
kwargs is argument in which key serves as
name of var and the value of it serves as
condition of searching
'''
assert len(kwargs) == 1
for var, crit in kwargs.items():
self.cursor.execute("SELECT * FROM {t} WHERE {v} {c}".format(t=table, v=var.strip(), c=crit.strip()))
break
yield from self.cursor.fetchall()
def search_with_and(self, table, **kwargs):
'''
table is the name of table you want to use
kwargs is arguments in which key serves as
name of var and the value of it serves as
condition of searching with using operator 'AND'
between conditions
'''
assert len(kwargs) > 1
crit = ["{v} {c}".format(v=key.strip(), c=value.strip()) for key, value in kwargs.items()]
self.cursor.execute("SELECT * FROM {t} WHERE {c}".format(t=table, c=' AND '.join(crit)))
yield from self.cursor.fetchall()
def search_with_or(self, table, **kwargs):
'''
table is the name of table you want to use
kwargs is arguments in which key serves as
name of var and the value of it serves as
condition of searching with using operator 'OR'
between conditions
'''
assert len(kwargs) > 1
crit = ["{v} {c}".format(v=key.strip(), c=value.strip()) for key, value in kwargs.items()]
self.cursor.execute("SELECT * FROM {t} WHERE {c}".format(t=table, c=' OR '.join(crit)))
yield from self.cursor.fetchall()
| true |
a4e7417540fa0a4930cf7d062f293c9d85dbfd03 | Zidane786/Geometry_Game | /turtle_revision.py | 1,660 | 4.46875 | 4 | import turtle # importing turtle
"""
Since we are Creating Geometry Game and applying some turtle graphic so lets do some
revision of turtle so we can get a kick start
"""
"""
Note if we want to see code of any class or Method so what we can do is
->select that class or function
->then right click and go to the Go To option
->than click Declaration Usage and it will open file where the code corresponding to
that class or function is written.
OR
->select that class or function and press CTRL+ALT+B we will get same result
"""
# Creating Canvas/Turtle Instance
my_turtle = turtle.Turtle() # Create Arrow/Turtle
my_turtle.penup() # Pull the pen up -- no drawing when moving.
my_turtle.goto(50, 75) # Move turtle to an absolute position. (Go to a Certain Co-ordinate)
my_turtle.pendown() # Pull the pen down -- drawing when moving. Since we want to draw the line now
my_turtle.forward(100) # Move the Turtle forward by the specified distance. here we done 100 pixel
my_turtle.left(90) # Turn turtle head (arrow head) left by angle 90 degree
my_turtle.forward(200) # move the turtle forward by 200 pixels
my_turtle.left(90) # turn arrow head left by 90 degree
my_turtle.forward(100) # move the turtle forward by 100 pixels
my_turtle.left(90) # turn arrow head left by 90 degree
my_turtle.forward(200) # move the turtle forward by 200 pixels
turtle.done() # if not written screen will get close automatically Note:-its library name turtle.done()
"""
So we are done we needed this much for our Geometry game if you want to know more about turtle than try to learn using
documentation its really easy to learn this Turtle Module
"""
| true |
d548ff7fc3e221d67ec68ff26841da0863b91ea5 | Michael-Lyon/ClassDemo | /catchup1.py | 497 | 4.125 | 4 | #dictionaries
all_student = {}
new_student = {
"name":"Jane",
"surname":"Abu",
"class":"Python",
"sport":"VolleyBall",
"music":"dance"
}
print(new_student['name'])
for key in new_student:
# print(f"{key} ===> {new_student[key]}")
pass
for key, value in new_student.items():
# print(key, value)
pass
new_student['music'] = "Electronic"
print(new_student['music'])
new_student.update({'color':'black'})
print(new_student)
empty = new_student.copy() | false |
c2e1dd915cb854f42d6181aeb595024bef5fc768 | avsingh999/Python-for-beginner | /merge_sort_on_doubly_linked_list.py | 2,634 | 4.28125 | 4 | # Program for merge sort on doubly linked list
# A node of the doublly linked list
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# Function to merge two linked list
def merge(self, first, second):
# If first linked list is empty
if first is None:
return second
# If secon linked list is empty
if second is None:
return first
# Pick the smaller value
if first.data < second.data:
first.next = self.merge(first.next, second)
first.next.prev = first
first.prev = None
return first
else:
second.next = self.merge(first, second.next)
second.next.prev = second
second.prev = None
return second
# Function to do merge sort
def mergeSort(self, tempHead):
if tempHead is None:
return tempHead
if tempHead.next is None:
return tempHead
second = self.split(tempHead)
# Recur for left and righ halves
tempHead = self.mergeSort(tempHead)
second = self.mergeSort(second)
# Merge the two sorted halves
return self.merge(tempHead, second)
# Split the doubly linked list (DLL) into two DLLs
# of half sizes
def split(self, tempHead):
fast = slow = tempHead
while(True):
if fast.next is None:
break
if fast.next.next is None:
break
fast = fast.next.next
slow = slow.next
temp = slow.next
slow.next = None
return temp
# Given a reference to the head of a list and an
# integer,inserts a new node on the front of list
def push(self, new_data):
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
def printList(self, node):
temp = node
print("Forward Traversal using next poitner")
while(node is not None):
print (node.data, end=" ")
temp = node
node = node.next
print ("\nBackward Traversal using prev pointer")
while(temp):
print (temp.data, end=" ")
temp = temp.prev
# Driver program to test the above functions
dll = DoublyLinkedList()
dll.push(5)
dll.push(20);
dll.push(4);
dll.push(3);
dll.push(30)
dll.push(10);
dll.head = dll.mergeSort(dll.head)
print ("Linked List after sorting")
dll.printList(dll.head)
| true |
e5aff0e209016f787403f594e376a60d0ad0f7e4 | Rutie2Techie/Hello_python | /attempt/attempt.py | 689 | 4.21875 | 4 | #Ask the User a question like "Who is PM of India?"
#Track in how many attempts the user answers.
#Give hints based on how many guesses the user makes.
question="who is Pm of india?"
attempt=0
while True(ans):
attempt=attempt+1
if ans=="Modi":
print("correct ans")
break
else:
print("incorrect ans")
if count(attempt)==1:
hint1="he is 70 years old"
print(hint1)
elif count(attempt)==2:
hint2="he is from BJP"
print(hint2)
elif count(attempt)==3:
hint3="he has white beard"
print(hint3)
else:
print("you are loser")
| true |
5d0ebcd89bbfa34efaa37b48157753e8594ef029 | JustinC222/Python | /Find_Monisen_Numbers.py | 1,280 | 4.25 | 4 | # Written by: Justin Clark
# Program Description: This program will calculate a variable amount of Monisen Numbers.
from math import sqrt
#This function will find all the prime numbers between 2 and 100:
def find_primes():
for i in range(2,101):
flag = True
x = int(sqrt(i))
for j in range(2,x+1):
if(i % j == 0):
flag = False
break
if(flag):
print(i,end=" ")
if(i == 100):
print("\n")
#This function allows you to pass a number and inquire if it is prime or not. Returns True or False.
def is_prime(x):
a = int(sqrt(x))
for j in range(2,a+1):
if(x % j == 0):
return False
return True
# This function will output the first 6 Monisen Numbers.
# If you would like to calculate more than 6 Monisen numbers, change the 19, two lines below, "for P in range(2,19)", to a higher value and as long as there is another Monisen number in that range, it will output it.
# A Monisen Number is any number that is a prime result of Some_Monisen_Number = 2^(another_prime_#) - 1.
def get_Monisen_Numbers():
for P in range(2,19):
if(is_prime(P)):
M = 2**P - 1
if(is_prime(M)):
print(M, end = " ")
#This outputs the results from the get_Monisen_Numbers function:
print("\nMonisen Numbers: ")
get_Monisen_Numbers()
print("\n")
| true |
7cca930c3ccb89b08afaa3c5b4068b4430ae1260 | JoeDurrant/python-exercises | /is_prime.py | 727 | 4.125 | 4 | #Returns True if x is prime, False if not prime
def is_prime(x):
try:
if x <= 1:
return False #Negative numbers and 1 are not prime
else:
for i in range(2,x):# range(2,2) returns an empty list so 2 is seen as prime
if x % i == 0:
return False
return True #If this is reached then no factors have been found
except TypeError:
print("Your input has to be a positive integer!")
print(is_prime(0))
print(is_prime(1))
print(is_prime(2))
print(is_prime(3))
print(is_prime(4))
print(is_prime(5))
print(is_prime(6))
print(is_prime(7))
print(is_prime(8))
print(is_prime(9))
print(is_prime(10))
print(is_prime(11))
print(is_prime("12")) | true |
5118694850871e6fed4467fbf782a9856ac33683 | RuchitaPawar/Python-Assignment-2 | /Assignment 2/Assignment2_1.py | 364 | 4.125 | 4 | from Arithmetic import *
num1 = input("Enter first number")
no1 = int(num1)
num2 = input("Enter second number")
no2 = int(num2)
print("Addition of two numbers is:")
Add(no1,no2)
print("Substraction of two numbers is:")
Sub(no1,no2)
print("Multiplication of two numbers is:")
Mult(no1,no2)
print("Division of two numbers is:")
Div(no1,no2)
| true |
f0f67cec2c94ad3dd6b6b4bae629e041839c29f2 | RuchitaPawar/Python-Assignment-2 | /Assignment 2/Assignment2_9.py | 233 | 4.125 | 4 | def countDigit(value):
count = 0
while(value > 0):
value = value // 10
count = count + 1
return count
num1 = input("Enter number:")
no1 = int(num1)
res = countDigit(no1)
print("Number of digits are",res)
| true |
031b98bb551eb003298d6748f36566299481aff8 | GarconeAna/aulasBlue | /aula06-exercicios/exercicio3.py | 520 | 4.3125 | 4 | # 03 - Faça um script que o usuário escolha um número de início, um número de fim, e um número de
# passo. O programa deve printar todos os números do intervalo entre início e fim, "pulando" de
# acordo com o intervalo passado.
numeroInicio = int(input('Digite o número inicial: '))
numeroFim = int(input('Digite o número final: '))
numeroIntervalo = int(input('Digite o número de intervalo entre os números digitados anteriormente: '))
for i in range(numeroInicio,numeroFim,numeroIntervalo) :
print(i) | false |
a8d59010fb8bba4a018d7a681e8bb9db4a92bafd | Mr-Nicholas/udacity-studies | /python-intro/profanity-editor/profanity-editor.py | 927 | 4.15625 | 4 | import urllib
''' This simple program reads a .txt file and removes common profanities'''
# save a list of profane words
# take input from a user
# convert the input to a string
# if the input contains one of the profane words, remove it
# print the sanitised input to the screen
def read_txt():
quotes = open("/Users/Heath/apps/udacity-studies/python-intro/profanity-editor/quotes.txt")
file_contents = quotes.read()
print(file_contents)
quotes.close()
test_profanity(file_contents)
def test_profanity(text_to_check):
connection = urllib.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check)
output = connection.read()
# print(output)
connection.close()
if "true" in output:
print("Profanity has been detected.")
elif "false" in output:
print("No profanity has been found.")
else:
print("Error in scanning file provided.")
read_txt()
| true |
5d6323f98e60098265c01ec5251703fd62ae04ab | julia2288-cmis/julia2288-cmis-cs2 | /cs2quiz3.py | 1,372 | 4.59375 | 5 | #Section 1: Terminology
# 1) What is a recursive function?
# base case - doesn't do anything
#calling it again -
#
# 2) What happens if there is no base case defined in a recursive function?
#The function won't do work at all
#
#
# 3) What is the first thing to consider when designing a recursive function?
#To define a function
#
#
# 4) How do we put data into a function call?
#by
#
# 5) How do we get data out of a function call?
#by return
#
#
#Section 2: Reading
# Read the following function definitions and function calls.
# Then determine the values of the variables q1-q20.
#a1 = 1 + (2+5)
#a2 = 1 + (6+2-1) or 1 + (6+1)
#a3 = -1
#b1 = 2
#b2 = 0
#b3 = -2
#c1 = -2
#c2 = 4 +2 =4da,m wrong
#c3 =
#d1 = 6 wrong
#d2 = 1 + (6) wrong
#d3 = (4, 2, 1 wrong
#Section 3: Programming
#Write a script that asks the user to enter a series of numbers.
#When the user types in nothing, it should return the average of all the odd numbers
#that were typed in.
#In your code for the script, add a comment labeling the base case on the line BEFORE the base case.
#Also add a comment label BEFORE the recursive case.
#It is NOT NECESSARY to print out a running total with each user input.
def average():
n = odd()
n = raw_input("Next number: ")
if n == abs(float(odd))
return
if n == "":
return average
def odd():
if n/2 == false
else:
abs(float(odd))
| true |
e72a9addae0fe7052947d739c8fd03a7706bc043 | julia2288-cmis/julia2288-cmis-cs2 | /cs2quiz1.py | 1,833 | 4.3125 | 4 | #Part 1: Terminology (15 points)
#1 1pt) What is the symbol "=" used for?
# That is called assignment operator, and it's used for putting a value into a variable.
#+1
#
#2 3pts) Write a technical definition for 'function'
# A function is a named sequence of statements that performs a computation.
#+3
#
#3 1pt) What does the keyword "return" do?
# It takes the function and gives a result.
#+1
#
#4 5pts) We know 5 basic data types. Write the name for each one and provide two
# examples of each below
# 1: interger
# 2: float
# 3: strings
# 4: boolean
# 5: tuple
#+2.5
#5 2pts) What is the difference between a "function definition" and a
# "function call"?
# Function deifnition specifies(in other word, defines) the new function, and function call is actualling calling the function that has been specified.
#+1
#
#
#6 3pts) What are the 3 phases that every computer program has? What happens in
# each of them
# 1: programming languages
# 2: compiled
# 3: interpreted
#1
#Part 2: Programming (25 points)
#Write a program that asks the user for the areas of 3 circles.
#It should then calculate the diameter of each and the sum of the diameters
#of the 3 circles.
#Finally, it should produce output like this:
#Circle Diameter
#c1 ...
#c2 ...
#c3 ...
#TOTALS ...
# Hint: Radius is the square root of the area divided by pi
import math
def float(a, r):
return a / r**2 / pi
def output():
out = """
circle diameter
c1: {}
c2: {}
c3: {}
total: {}
""". format()
return out
def main():
A = raw_input("What is the area for c1?: ")
B = raw_input("What is the area for c2?: ")
C = raw_input("What is the area for c3?: ")
area = mult(float(r), float(2))
out = output(area, A, pi, r)
print out
main()
# area = pi * radius^2
# a / pi / = x
# x / x = radius
# radius * 2 = diameter
| true |
1e0f192f50bce7ba67cea2d5eccc762e90de553d | iniyan-kannappan/python | /Programs/game/Recap Assignment-Double game3.py | 1,435 | 4.125 | 4 | import random
print('Do you want play the coin toss game or the number guessing game.')
print("If you want to play 'Coin Toss Game', press 1.")
print("If you want to play 'Number Guessing Game', press 2.")
game=int(input())
if game==1:
print('You have chosen the coin toss game.')
count=0
computerpicks=[]
userpicks=[]
for loop in range(1,11,1):
coin=['Heads','Tails']
choice=random.choice(coin)
computerpicks.append(choice)
userinput=input('Enter Heads or Tails:')
userpicks.append(userinput)
if choice==userinput:
print('You got it right.')
count=count+1
else:
print('You got it wrong.')
print('Total score:',count,'/10.')
print('Computer picks:',computerpicks)
print('User picks:',userpicks)
elif game==2:
print('You have chosen the number guessing game.')
priorguesses=[]
randomnumber=random.randint(1,10)
#print(randomnumber)
while True:
print('Try to guess the number:')
number=int(input())
if randomnumber==number:
print('You are right.')
print('Correct guess.You guessed:',number)
print('Prior guesses:',priorguesses)
break
else:
print('You are wrong.')
priorguesses.append(number)
| true |
92b224398024b46f023a0cb4abcb8820d563d288 | vmsclass/Python-Core-level- | /sum_of_digits.py | 700 | 4.25 | 4 | # Description : Program to print the sum of individual digits in a given number.
# Example : 462 , then your output is 12. (4+6+2)
# 462 ===> 4 + 6 + 2 ( Human : left to right)
# 462 ===> 2 + 6 + 4 ( Program logic : right to left)
# sum = 0
# n = 462 (n > 0)
# Step 1: find the last_digit (last_digit = n%10)
# Step 2: add the last_digit with the sum (sum = sum + last_digit)
# Step 3: remove the last_digit ( n = n//10 )
# repeat step 1 to 3 until the n>0 false.
# sum = 0
# sum = 0 + 2 = 2
# sum = 2 + 6 = 8
# sum = 8 + 4 = 12
n=int(input("enter a number"))
sum=0
while n>0:
last_digit=n%10
sum=sum+last_digit
n=n//10
print("The sum of individual digits",sum)
| true |
7e674fc14cc0f3261c0ca89fcabca7fdeca8136c | KanagasabapathiE2/PythonLearn | /Assignment8-Thread/5_ThreadLockSemaphor.py | 1,020 | 4.46875 | 4 | """
Design python application which contains two threads named as thread1 and thread2.
Thread1 display 1 to 50 on screen and thread2 display 50 to 1 in reverse order on
screen. After execution of thread1 gets completed then schedule thread2.
"""
import threading
def Threads(fun,strname,locker):
fun(strname,locker)
def Thread1(no,lock):
lock.acquire()
for i in range(1,no+1):
print(i)
lock.release()
def Thread2(no,lock):
lock.acquire()
for i in range(no,0,-1):
print(i)
lock.release()
def main():
#print("Enter the No : ")
#no = int(input())
no = 50
lock = threading.Lock()
thread1 = threading.Thread(target= Threads,args=(Thread1,no,lock,))
thread2 = threading.Thread(target= Threads,args=(Thread2,no,lock,))
print("Thread1 Displaying 1 to 50")
thread1.start()
thread1.join()
print("Thread2 Displaying 50 to 1")
thread2.start()
thread2.join()
#Entry Function
if __name__ == "__main__":
main() | true |
e7643d2003bc44f87eb65245aab9a0ba9e5ae149 | KanagasabapathiE2/PythonLearn | /Assignment3/2MaxFromList__2.py | 697 | 4.125 | 4 | """
Write a program which accept N numbers from user and store it into List. Return Maximum
number from that List.
Input : Number of elements : 7
Input Elements : 13 5 45 7 4 56 34
Output : 56
"""
def Max(lst):
if(len(lst)>0):
maxno = lst[0]
for i in range(len(lst)):
if(maxno<lst[i]):
maxno=lst[i]
return maxno
def main():
lst = []
num = int(input("Enter how many elements you want:"))
for i in range(num):
no = int(input("Enter num {}:".format(i+1)))
lst.append(no)
result= Max(lst)
print("Maximum no of List is: ",result)
#Entry Function
if __name__ == "__main__":
main() | true |
3a0b5f51ce7c9907312783440a6ce3af7f4a76a7 | KanagasabapathiE2/PythonLearn | /Assignment1/FindLengthOfString__10.py | 645 | 4.15625 | 4 | """
Write a program which accept name from user and display length of its name.
Input : Marvellous Output : 10
"""
def FindLengthOfStringUsingLoop(strname):
counter = 0
for _chr in strname:
counter+=1
return counter
def FindLengthOfStringStandardFunction(strname):
return len(strname)
def main():
inputName=input("Enter Name : You want to check Length ")
outputLength= FindLengthOfStringUsingLoop(inputName)
print(outputLength)
length=FindLengthOfStringStandardFunction(inputName)
print("Length is: ",length)
#Entry Function
if __name__ == "__main__":
main() | true |
173be159020ea9dcd4748250cdba52dc5dc87c0d | shashank2791/Work-On-Numpy-In-Python | /Q1.py | 389 | 4.1875 | 4 | ##1. Using numpy, WAP that takes an input from the user in the form of a list and calculate the
##frequency of occurrence of each character/integer in that list (count the number of
##characters).
import numpy as np
lst = np.array(list(input()))
(unique, counts) = np.unique(lst, return_counts=True)
frequencies = np.asarray((unique, counts)).T
print(frequencies)
| true |
268442c92f07830de691f190c02b373e4f4e5186 | jingjielim/intermediate_python_sentdex | /zip_tutorial.py | 386 | 4.46875 | 4 | x = [1,2,3,4]
y = [7,8,3,2]
z = ['a','b','c','d']
# # zip makes a zip object
# # zip object is iterable
# print(list(zip(x,y,z)))
# for i in zip(x,y,z):
# print(i)
# zip with list comprehensions
[print(a,b,c) for a,b,c in zip(x,y,z)]
# variables in a for loop are stored
# variable `x` is being overwritten
for x,y in zip(x,y):
print(x,y)
# `x` is no longer a list
print(x)
| false |
b283506ce9bf036792205a6ecba4543f5ff9945a | cshoaib05/Python_programs | /Programs/LIST.py | 1,585 | 4.125 | 4 | a=10
b=20
id(a) #to check adress
type(a) #to check data type #### pooling for integer are done for 256 integer value
#### if statement work in True and false
print('OUTPUT:',a) # , use for printing string with var
print("a=%d b=%d" %(a,b)) # % method of printing
print("a={} b={}".format(a,b)) #format method for printing
a=[1,25,36,43,45,46,45,8] # create a object of data types
print(a)
print(a[3]) #printing a list
print(len(a)) # length of list
print(min(a)) # min value of list
print(max(a)) # max value of list
b=[1,2,'hello','python']
print(len(b))
b.insert(3,543) #insert function to insert a value at desire location (index loaction,value)
print(b) # value shift to next location
b.remove('hello') #remove function to remove the value ( value)
print(b)
print(b.index(2)) #index of (value)
a.sort() # sort a list in assending order object.sort()
print(a)
a.sort(reverse=True) # to sort a list in decending order
print(a)
a.reverse() # reverse a list
print(a)
a.clear() # clear a list
print(a)
a.append(10) # append function to add a var at last fo list
a.append(20)
a.append(30)
a.append(40)
print(a)
a.pop() # to remove the last elemnt inserted
print(a)
a[2]=50 # to change the element value
print(a)
c=[[1,2,3],[4,5,6],4,5,a] #multi dimensional list
print(c)
print(c[1][1]) #to print desire index value of d list
c[4].sort(reverse=True)
print(c)
######### TUPLE ########
# Tuple cant be change
d=(1,2,3,6,4) # defining tuple
print(d) | true |
9d01c0bc5cce40c5094ee4ff5bf5d716d13a89dc | chainchomp440/chainchomp | /calc.py | 1,423 | 4.125 | 4 | ##this is a prototype
import random
yesList = ['yes','yup','okay','sure','ok']
name = input('what is your name?\n')
print ('hello,',name)
#'if a rare coincidence happens, use shift command 4'
if name.lower() == 'burt':
ask = input('do you want to play a game?')
while ask.lower() in yesList:
randomNumber = random.randint(1,100)
guess = input('guess my random number')
while int(guess) != randomNumber:
if int(guess)>randomNumber:
print ('too high!')
elif int(guess)<randomNumber:
print ('too low!')
guess = input('wrong! guess my random number again!')
print ('Correct!')
ask = input('do you want to play another game?')
else:
ask = input('do you want to use a calculator?')
while ask.lower() in yesList:
num1 = int(input('enter a number'))
sign = input('enter the sign')
num2 = int(input('enter the 2nd number'))
result = 'ERROR'
if sign == '+':
result = (num1+num2)
elif sign == '-':
result = (num1-num2)
elif sign == '*':
result = (num1*num2)
elif sign == '/':
result = (num1/num2)
else:
print('what sign have you typed? I am very confused.')
print(num1,sign ,num2,'=',result)
ask = input('do you want to use another calculator?')
| true |
f610a46d668d8b6bc8c838353ff1963789322b28 | Mohitgola0076/Day4_Internity | /Closures_and_Decorators.py | 2,457 | 4.875 | 5 | '''
Decorators are also a powerful tool in Python which are implemented using closures and
allow the programmers to modify the behavior of a function without permanently modifying it.
'''
# 1.) Nested functions in python
def outerFunction(text):
text = text
def innerFunction():
print(text)
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')
# 2.) Python Closures
# Python program to illustrate
# closures
def outerFunction(text):
text = text
def innerFunction():
print(text)
# Note: we are returning function
# WITHOUT parenthesis
return innerFunction
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
# Output :
Hey!
# 3.) Python program to illustrate closures
import logging
logging.basicConfig(filename='example.log',
level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info(
'Running "{}" with arguments {}'.format(func.__name__,
args))
print(func(*args))
# Necessary for closure to
# work (returning WITHOUT parenthesis)
return log_func
def add(x, y):
return x+y
def sub(x, y):
return x-y
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)
# Output :
6
9
5
10
# 4.) defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
# Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution
# 5.) Code for testing decorator chaining
def decor1(func):
def inner():
x = func()
return x * x
return inner
def decor(func):
def inner():
x = func()
return 2 * x
return inner
@decor1
@decor
def num():
return 10
print(num())
# Output :
400
| true |
ee3727aeaab3cdb2fcf6c5ecfcb09e1c79c808b8 | ictrobot/alevel-coursework | /src/ciphers/keyword.py | 2,965 | 4.1875 | 4 | import tkinter as tk
from string import ascii_uppercase
from cipher_window import CipherWindow
from ciphers.substitution import substitution
def keyword_mapping(keyword):
"""Generates the substitution mapping from a keyword"""
# letters to be used as the keys
input_letters = list(ascii_uppercase)
# remaining letters to be mapped
mapping_letters = list(ascii_uppercase)
mapping = {}
for letter in keyword.upper():
if letter in mapping_letters:
# if the letter hasn't already been mapped, map the next input
# letter to it, and remove it from the letters to map
mapping[input_letters.pop(0)] = letter
mapping_letters.remove(letter)
# map the remaining letters
for letter in mapping_letters:
mapping[input_letters.pop(0)] = letter
return mapping
def valid_keyword(text):
"""Returns if the text is a valid keyword"""
for letter in text:
chr_code = ord(letter)
if not (65 <= chr_code <= 90 or 97 <= chr_code <= 122):
# if the character is not an uppercase or lowercase letter, invalid key
return False
# all uppercase or lowercase letters, so valid key
return True
class KeywordCipher(CipherWindow):
"""Base Cipher Window for the Keyword Cipher"""
def __init__(self, application, mode):
self.stringvar_entry = None
super(KeywordCipher, self).__init__(application, "Keyword Cipher - " + mode)
def get_key(self):
"""Returns the key or None if it is invalid"""
key = self.stringvar_entry.get()
if len(key) > 0 and valid_keyword(key):
return key
def run_cipher(self, text, key):
"""Subclasses actually run the Keyword cipher"""
raise NotImplementedError()
def tk_key_frame(self):
"""Get the key input"""
frame = tk.Frame(self)
tk.Label(frame, text="Keyword: ").grid(row=0, column=0)
self.stringvar_entry = tk.StringVar(frame)
self.stringvar_entry.trace("w", lambda *args: self.update_output())
tk.Entry(frame, validate="key", validatecommand=(frame.register(valid_keyword), "%P"), textvariable=self.stringvar_entry).grid(row=0, column=1)
return frame
class KeywordEncrypt(KeywordCipher):
"""Keyword Encryption Cipher Window"""
def __init__(self, application):
super(KeywordEncrypt, self).__init__(application, "Encrypt")
def run_cipher(self, text, keyword):
mapping = keyword_mapping(keyword)
return substitution(text, mapping)
class KeywordDecrypt(KeywordCipher):
"""Keyword Decryption Cipher Window"""
def __init__(self, application):
super(KeywordDecrypt, self).__init__(application, "Decrypt")
def run_cipher(self, text, keyword):
mapping = keyword_mapping(keyword)
reversed_mapping = {b: a for a, b in mapping.items()}
return substitution(text, reversed_mapping)
| true |
79b1f9a2cacd3332d649ce267a51d367c6b41aaf | agarwan1/Python_Calculator | /calculator.py | 1,358 | 4.25 | 4 | from calcart import logo
def add(n1,n2):
return n1 + n2
def subtract(n1,n2):
return n1-n2
def multiply(n1,n2):
return n1*n2
def divide(n1,n2):
if n2 != 0:
return n1/n2
else:
return 0
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
function = operations["*"]
function(2,3)
def calculator():
print(logo)
num1 = float(input("What's the first number?: "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue: #True
operation_symbol = input("Pick an operation form the line above: ")
num2 = float(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)
print(f"{num1}{operation_symbol}{num2}={answer}")
if input(f"Type 'y' to continue calculating with {answer} or type 'n' to start a new calculation: ") == "y":
num1 = answer
else:
should_continue = False
calculator() #takes back to beginnning, recursion.
calculator()
'''
operation_symbol = input("Pick another operation: ")
num3 = int(input("What's the next number? "))
calculation_function = operations[operation_symbol]
second_answer = calculation_function(calculation_function(num1,num2),num3)
print(f"{first_answer}{operation_symbol}{num3}={second_answer}")
''' | true |
1d78da1407f5198c1337b14cc7a5f3f80bea85ca | samhabib/FirstProject | /Exercise15.py | 1,052 | 4.3125 | 4 | '''Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the
user the same string, except with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.'''
def splitter(test):
answer = test.split()
return reverse(answer)
def reverse(test):
x = len(test)
z = x - 1
if x % 2 == 0:
for D in range(z):
if D < int(x / 2):
temp = test[D]
test[D] = test[z - D]
test[z - D] = temp
else:
y = (x - 1) / 2
y = int(y)
for E in range(z):
if E < y:
temp = test[E]
test[E] = test[z - E]
test[z - E] = temp
return test
testString = input("Type in a long string of words and I shall return them in reverse order: ")
result = " ".join(splitter(testString))
print(result)
| true |
59d79fcb9faf19c4af86836f2388b9949a26452f | samhabib/FirstProject | /Exercise13.py | 749 | 4.625 | 5 | '''Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of
numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in
the sequence is the sum of the previous two numbers in the sequence.
The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)'''
n = int(input("Give me any number and I will calculate that many Fibonnaci terms for you "))
if n == 1:
Fib = [1]
elif n == 2:
Fib = [1, 1]
elif n >= 3:
Fib = [1, 1]
for i in range(1, n-1):
Fib.append(Fib[i - 1]+Fib[i])
print(Fib)
| true |
ba6eb78dbf52fd212028f81106fb6870a9adcfca | JoshVL/SkribblFormatter | /skribblformat.py | 1,500 | 4.25 | 4 | '''
Skribbl Formatter - Formats a text file to be used as a custom Skribbl.IO word list
Josh Villanueva
'''
# Removing Special Characters
def remChars(inWord):
inWord = inWord.replace(',', '')
inWord = inWord.replace('.', '')
inWord = inWord.replace('!', '')
inWord = inWord.replace('=', '')
inWord = inWord.replace(';', '')
inWord = inWord.replace(':', '')
return inWord
# Main Function
def main():
# Obtain text file to format
fileName = input("Enter the txt file location: ")
txtFile = open(fileName, "r")
# Creates the formated txt file to put formated words
listOfWords = []
formatedTxt = open("Formated.txt", "w+")
# Reads through the given txt file to format words into formated txt
if txtFile.mode == 'r':
for line in txtFile:
for word in line.split():
# Remove special characters
word = remChars(word)
# Adds the word to list of stored words
if not((word == '') or (word.casefold() in listOfWords)):
listOfWords.append(word)
# Writes to the text file
for x in range(len(listOfWords)):
formatedTxt.write(listOfWords[x] + ", ")
# Closing the text files once finished
print("\nFormatted words successfully. Please check Formated.txt for your formated list of words.")
txtFile.close()
formatedTxt.close()
if __name__ == "__main__":
main() | true |
ecb33b16d898aa54079804e2dd3143b0dc972342 | iamrivu/CBSE-CS | /python/divisibility.py | 933 | 4.28125 | 4 | """
In math, divisibility refers to a number's quality of being evenly divided by another number,
without a remainder left over
"""
# EX 1
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
# EX 2
# Function to check whether a number is divisible by 7
def isDivisibleBy7(num) :
# If number is negative, make it positive
if num < 0 :
return isDivisibleBy7( -num )
# Base cases
if( num == 0 or num == 7 ) :
return True
if( num < 10 ) :
return False
# Recur for ( num / 10 - 2 * num % 10 )
return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) )
# Driver program
num = 616
if(isDivisibleBy7(num)) :
print ("Divisible")
else :
print ("Not Divisible") | true |
49cd6922fddcc3b98531bcaddf1b6c3621b69415 | iamrivu/CBSE-CS | /python/swap.py | 305 | 4.125 | 4 | # simple swap
a = 5
b = 6
temp = a
a = b
b = temp
print(a)
print(b)
# using xor it will not use extra bit like temp
a = 10
b = 11
a = a ^ b
b = a ^ b
a = a ^ b
print(a)
print(b)
# only in python
a = 15
b = 16
# works only in same line (it's goes into stack and reverse)
a,b = b,a
print(a)
print(b) | true |
3429a74449d15009ccb7171f39df1e9625839235 | HugoBahman/Assignment | /Variable_Input_Placeholder_Practise.py | 764 | 4.40625 | 4 | #Hugo
#9/9/14
#Variable, Input, and Placeholder Practise
print("Hello!")
#print command will output what it's been told to in the brackets following it
first_name = input("What's your name: ")
#first_name is a variable and will be paired with whatever the user puts in
#input will take the user's input from whatever they type
#The green text in the speech marks will appear exactly as it's been typed
print(first_name)
#print here will take the first_name variable and show it to the user
print("Hi {0}! What's up?".format(first_name))
#print will show the user the what's between the first and last brackets
#"{0}" is a placeholder that will be replaced by whatever follows the .format
#.format(first_name) will bring up the first_name variable
| true |
6cff565ff4ed899c7725cf5272525dfb7b279b7e | WilliamVJacob/Python-Code | /22-filecount.py | 412 | 4.125 | 4 | #program to print the number of word, total alphabet and total lines
s="Hello my name is william"
def file2string():
fp=open("a","r")
s=fp.read();
fp.close();
return s
def countletter(s):
c=0;d=0;
for i in range(0,len(s)):
if(s[i]==' ' or s[i]=='\n'):
d=d+1;
if(s[i]=='\n'):
c=c+1;
print("the total words are",d,"total alpha are",len(s)-d,"and lines are :",c);
s=file2string()
countletter(s)
| true |
8ad9de6af052ec2c38c4a95407d2b85c12393af3 | laihoward/leetcode_practice | /sort_algorithms/review_sort.py | 816 | 4.15625 | 4 | def bubble_sort(num):
for i in range(len(num)):
for j in range(len(num)-i-1):
if num[j]>num[j+1]:
num[j+1],num[j]=num[j],num[j+1]
print(num)
return num
def selection_sort(num):
len_num=len(num)
for i in range(len_num):
res = i
for j in range(i,len_num-1):
if num[res]>num[j+1]:
res = j+1
# print(num[res])
num[i],num[res]=num[res],num[i]
print(num)
return num
def insertionSort(num):
for i in range(1,len(num)):
res=num[i]
j=i-1
while j>=0 and res<num[j]:
num[j+1]=num[j]
j-=1
num[j+1]=res
print(num)
return num
array = [38,27,43,3,9,82,10]
# bubble_sort(array)
# selection_sort(array)
insertionSort(array) | false |
a2d0bfe9dae8605877042cd913d227d788ca8ceb | laihoward/leetcode_practice | /sort_algorithms/insertion_sort.py | 318 | 4.21875 | 4 | def insertionSort(array):
for i in range(len(array)):
j = i-1
key = array[i]
while j>-1 and key<array[j]:
array[j+1]=array[j]
j-=1
array[j+1] = key
if __name__ == '__main__':
array = [38,27,43,3,9,82,10]
insertionSort(array)
print(array)
| false |
2fa600ca9a0fae745ed4cac4c0ed2828f2856764 | alokaviraj/python-program | /newton_square _root.py | 391 | 4.15625 | 4 | def newton_sqrt(n):
approx=0.5*n
exact_approx=(0.5*(approx+(n/approx)))
while(exact_approx!=approx):
approx=exact_approx
exact_approx=(0.5*(approx+(n/approx)))
return approx
n=int(input('enter the number'))
print("the square root by newton method ",newton_sqrt(n))
| true |
b2a99f2c31a74feca8bf27863138df14e7cd0523 | nantesgi/Algorithms-and-Programming-I | /Matrizes/Exemplo 1.py | 951 | 4.25 | 4 | # Exemplo 1
# todas as linhas da matriz possui a mesma quantidade de elementos
matriz = [[4, 23, 12, 4] , [5, 6, 7, 13] , [32, 37, 2, -1]]
# primeiro elemento da matriz: [4, 23, 12, 4]
# segundo elemento da matriz: [5, 6, 7, 13]
# terceiro elemento da matriz: [32, 37, 2, -1]
# imprimindo toda a lista/matriz
print(matriz)
# imprimindo cada uma das linhas da lista/matriz
print(matriz[0]) # primeiro elemento da matriz: [4, 23, 12, 4]
print(matriz[1]) # segundo elemento da matriz: [5, 6, 7, 13]
print(matriz[2]) # terceiro elemento da matriz: [32, 37, 2, -1]
print()
for i in range(0, 3):#i = 0, 1, 2
# j = 0, 1, 2, 3
for j in range(4): # impressão das colunas da linha i
print("{:6.0f}". format(matriz[i][j]), end=' ')
print()
print()
linhas = len(matriz) # quanto elementos tem na matriz? 3 (3 listas!)
print("A matriz tem {} linhas".format(linhas))
colunas = len(matriz[0])
print("A matriz tem {} colunas.".format(colunas)) | false |
1ae9c9d16c7a0b3689600859e86c7e54aa27dd0a | nantesgi/Algorithms-and-Programming-I | /Matrizes/Exemplo 2.py | 966 | 4.21875 | 4 | # Exemplo 2
# cada linha da matriz pode possuir uma quantidade específica de elementos
matriz = [[4], [5, 6, 7, 3, 6, -12, 13], [32, 2, -1]]
# primeiro elemento da matriz: [4]
# segundo elemento da matriz: [5, 6, 7, 3, 6, -12, 13]
# terceiro elemento da matriz: [32, 2, -1]
# imprimindo toda a lista/matriz
print(matriz)
# imprimindo cada uma das linhas da lista/matriz
print(matriz[0])
print(matriz[1])
print(matriz[2])
print()
#i percorre as linhas
for i in range(0, 3):
# j percorre as colunas da linha i
# len(matriz[i]) retorna a quantidade de elementos da linha i
for j in range(len(matriz[i])): # impressão das colunas da linha i
print("{:3.0f}". format(matriz[i][j]), end=' ')
print()
print()
linhas = len(matriz)
print("A matriz tem {} linhas".format(linhas))
print("A linha 1 tem {} colunas.".format(len(matriz[0])))
print("A linha 2 tem {} colunas.".format(len(matriz[1])))
print("A linha 3 tem {} colunas.".format(len(matriz[2]))) | false |
f564f3cc9c13e09dc2dbcb506757add72190165c | nelsonleopold/CS-212-Python-Programming | /NLeopold_if_logical3.py | 1,507 | 4.25 | 4 | #Name: Nelson Leopold
#Date: 9/10/2020
#Describe what the program will do -- Asks user to input Item, Price, and Quantity, then ouputs
#Item, Price, Quantity, Total Price, Discount Amount, and Total After Discount
item = input("Please enter an item: ")
#asks for user input and verifies that price is a positive float
while True:
price = input("Please enter the item price: ")
try:
price = float(price)
if price < 0:
print("\nPrice must be a positive number")
continue
break
except:
print("\nPrice must be a positive number")
#asks for user input and verifies that quantity is a positive integer
while True:
quantity = input("Please enter the item quantity: ")
try:
quantity = int(quantity)
if quantity < 0:
print("\nQuantity must be a positive number")
continue
break
except:
print("\nQuantity must be a positive integer")
totalPrice = price * quantity
#calculate proper discount based on quantity ordered
if quantity >= 100 and quantity <= 1000:
discountAmount = totalPrice * 0.05
elif quantity > 1000:
discountAmount = totalPrice * 0.10
else:
discountAmount = 0
#output properly formatted
print("\n\nItem: ", item)
print("Price: ${:.2f}".format(price))
print("Quantity: ", quantity)
print("Total: ${:.2f}".format(totalPrice))
print("Discount Amount: ${:.2f}".format(discountAmount))
print("Total After Discount: ${:.2f}".format(totalPrice - discountAmount)) | true |
424109eeb6e0be04f2a81086b17073e7e0090ef5 | nelsonleopold/CS-212-Python-Programming | /NLeopold_forloop_counteven.py | 282 | 4.25 | 4 | #Name: Nelson Leopold
#Date: 9/21/2020
#Describe what the program will do -- This for loop will iterate through the numbers 1-100, printing and
#keeping track of the even numbers
counter = 0
for num in range(0, 100, 2):
print(num)
counter += 1
print("Total Even Numbers:", counter) | true |
2da90ee282ecdbaff8ccc02e7a64de3cc4a9081f | amandabui/amandabui.github.io | /cs61a/assets/py/disc05.py | 2,359 | 4.375 | 4 | class Pet(object):
def __init__(self, name, owner):
self.is_alive = True
self.name = name
self.owner = owner
def eat(self, thing):
print(self.name + ' ate a ' + str(thing) + '!')
def talk(self):
print(self.name)
class Dog(Pet):
def talk(self):
print(self.name + 'says woof!')
class Cat(Pet):
def __init__(self, name, owner, lives=9):
### do something
Pet.__init__(self, name, owner)
## super().__init__(name, owner)
self.lives = lives
def talk(self):
"""A cat says meow! when asked to talk."""
print("meow!")
def lose_life(self):
"""A cat can only lose a life if they have at least one life.
When lives reaches zero, is_alive becomes False."""
if self.lives >= 1:
self.lives -= 1
if self.lives == 0:
self.is_alive = False
class NoisyCat(Cat): # fill this line in
""" A cat that repeats things twice. """
def __init__(self, name, owner, lives=9):
# Is this method necessary? Why or why not?
Cat.__init__(self, name, owner, lives)
# not necessary because it will automatically
# call your parent class's constructor for you
def talk(self):
"""Repeat what a Cat says twice."""
# print("meow!")
# print("meow!")
Cat.talk(self)
Cat.talk(self)
class Email:
"""Every email object has 3 instance attr:
message, sender name, recipient name"""
def __init__(self, msg, sender_name, recipient_name):
self.msg = msg
self.sender_name = sender_name
self.recipient_name = recipient_name
class Mailman:
def __init__(self):
self.clients = {}
def send(self, email):
""" Take an email and put it in the inbox of the client
it is addressed to """
client = self.clients[email.recipient_name]
client.receive(email)
def register_client(self, client, client_name):
""" Takes a client object and client_name and adds it
to the clients instance attribute. """
self.clients[client_name] = client
class Client:
def __init__(self, mailman, name):
self.inbox = []
self.mailman = mailman
self.name = name
mailman.register_client(self, name)
def compose(self, msg, recipient_name):
""" Send an email with the given message msg to the
given recipient client. """
email = Email(msg, self.name, recipient_name)
self.mailman.send(email)
def receive(self, email):
""" Take an email and add it to the inbox of this
client. """
self.inbox.append(email)
| false |
c79a4d6fbf4c6edc216898b409984e74a698ff50 | zhangxy12138/leetcode | /python_leetcode/x的平方根.py | 1,205 | 4.28125 | 4 | # -*-coding:utf-8-*-
# 实现int sqrt(int x)函数。
# 计算并返回x的平方根,其中x 是非负整数。
#
# 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
#
# 示例 1:
#
# 输入: 4
# 输出: 2
# 示例 2:
#
# 输入: 8
# 输出: 2
# 说明: 8 的平方根是 2.82842...,
# 由于返回类型是整数,小数部分将被舍去
# def mySqrt(x):
# if x == 0 or x ==1:
# return x
# max = x
# min = 0
# while (max - min > 1):
# m = (max + min) // 2
# if (x / m < m):
# max = m
# else:
# min = m
# return min
def mySqrt(x):
"""
:type x: int
:rtype: int
"""
if x <= 1:
return x
r = x
k = 0
while r > x / r:
r = (r + x / r) // 2
k+=1
print(k)
return int(r)
# def mySqrt(x): # 牛顿迭代
# if x == 0:
# return 0
# c,x0 = float(x),float(x)
# while 1:
# xi = 0.5*(x0+c/x0)
# if abs(x0-xi) < 1e-7:
# break
# x0 = xi
# return int(x0)
if __name__ =='__main__':
print(mySqrt(8))
| false |
58f7b92765a166f703c154019e60eb55aad64ca4 | xplagueis/myoldnoobpygarbage | /app2deneme.py | 833 | 4.34375 | 4 | #-*-coding:utf-8-*-
# nested list mantığı:
# 0.index [------1.index-----] #2.index
nestedlist = ["chrome",["firefox","yandex"],"opera"]
print("Nested list: ",nestedlist)
print("1. index: ",nestedlist[1])
print("1.indexin 0. indexi: ",nestedlist[1][0])
print("-"*125) #çizgi ile ayır
dersler = ["matematik","edebiyat","fizik","kimya","tarih","biyoloji"]
#görev: ikinci ve son liste elemanının çıktısını al
print(dersler)
print(dersler[2].upper())
print(dersler[-1].upper()) #uzun listelerde -1 daha fonksiyoneldir.
print("-"*125)
dersler = ["matematik","edebiyat","fizik","kimya","tarih","biyoloji"]
print(dersler[2:4]) #fizik ve kimya elemanlarının çıktısını al
print(dersler[:2]) #ilk iki elemanın çıktısını al
print(dersler[-2:]) #son iki elemanın çıktısını al | false |
95ed5695d55a52dd00c0de2676c7eb1bf2a51b04 | dustinblainemyers/day_3_python_practice | /python_exercises2.py | 1,632 | 4.21875 | 4 | #Day 3 exercises set 2
choice = input("What exercise do you want to run ? ")
if choice == "1":
day = int(input('Day (0-6)? '))
days_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
print(days_week[day])
elif choice == "2":
day = int(input('Day (0-6)? '))
sleep = "Sleep in"
work = "Go to work"
if day == 0 or day == 6:
print(sleep)
else:
print(work)
elif choice == "3":
celsius_input = int(input("Temperature in C? "))
Fahrenheit_return = celsius_input * 1.8 + 32
print('%.1f F' % Fahrenheit_return)
elif choice == "4":
bill_amount = float(input('Total bill amount? '))
#user selects level of service from 1 being bad , 2 being fair, and 3 being good.
user_input = input('Level of service? (Choose 1 for bad, 2 for fair, and 3 for good) ')
number_to_split = int(input('Enter the number of people to split the bill between (enter 1 if it is just you) :'))
if user_input == "1":
#bad service level
tip_amount = bill_amount * .1
elif user_input == "2":
# fair service level
tip_amount = bill_amount * .15
elif user_input == "3":
# good service level
tip_percentage = .2
tip_amount = bill_amount * .2
else: print("You did not enter a valid selection. Please run the program again")
total = (bill_amount + tip_amount) / number_to_split
print('Total amount per person: ${:.2f}'.format(total))
print('Your tip is : ${:.2f}'.format(tip_amount))
| true |
5dd314c204c75a7b88c7e19ed4e225d4ddbd9169 | coraallensavietta/Python_Projects | /NextPrime.py | 708 | 4.15625 | 4 | #Next Prime Number - Have the program find prime numbers until the user chooses to stop asking for the next one.
def Prime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for x in range(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
more = raw_input("Welcome to the prime number generator. Your first prime number is 2. Would you like another prime number? ")
n = 2
while more == "yes" or more == "YES" or more == "Yes":
n += 1
if Prime(n) is True:
print "Your next prime number is " + str(n) + "."
more = raw_input("Would you like another prime number? ")
else:
print "Goodbye" | true |
39754fac35398d41b1d846820e822d0c5643c996 | brombaut/BEC | /ctci/ch1/ex1_is_unique/python/is_unique.py | 344 | 4.15625 | 4 |
# Returns true if a string has all unique characters
def is_unique(string):
charDict = dict()
for char in string:
if char in charDict:
return False
charDict[char] = 1
return True
if __name__== "__main__":
if is_unique("tesrgu"):
print('Is Unique')
else:
print('Is Not Unique')
| true |
56193a97a6e66b942925317b893ea4976b2bcc76 | DominiquePaul/data-science-and-cloud-solution-course | /Session2 - Flask and APIs/1-pandas_numpy/pandas_exercises.py | 1,466 | 4.25 | 4 | # your turn!
# 1. load the boston housing set (data --> housing.csv) and into a dataframe and
# try to understand what each of the columns means
### your code below this line ###
### your code above this line ###
# 2. select a subset of your data and create some plots of the distributions
# using the seaborn package. Try to understand which of the features might
# have the strongest impact on the price (='medv' column)
### your code below this line ###
### your code above this line ###
# 3. Create a subset of the data using three features and split the data into
# a training and testing set. Before you do so, however, shuffle the data
# by using the iloc function together with a list of the shuffled row ids.
# Have a look at the numpy package for useful functions
### your code below this line ###
### your code above this line ###
# 4. Run a multiple linear regression using the statsmodel package and print
# the summary of your regression. Comment on your results
### your code below this line ###
### your code above this line ###
# 5. Create three scatterplots for each of your chosen three features and the
# price on the y-axis. Plot your predictions as well as the actual labels, but use different colours
### your code below this line ###
### your code above this line ###
# 6. Save one of your plots to your local directory
### your code below this line ###
### your code above this line ###
| true |
26a0e9fd86ae4575c8976809a8b0200207970a3a | Gi1ia/TechNoteBook | /Algorithm/899_Orderly_Queue.py | 888 | 4.15625 | 4 | """
So in summary, if k = 1, we can just basically rotate the array unless we get to the smallest lexicographical order. If K >= 2, we can simply exchange the relative order of any pair of elements in the string. First, we rotate the array appropriately, until we manage to have the desired pair at the beginning of the array. Then we can swap the relative order of the pair by just applying 2-move. That's why we can just sort the String for the case k >= 2.
"""
import collections
class Solution:
def orderlyQueue(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
if not S:
return ""
if K == 1:
return min(S[:i] + S[i:] for i in range(len(S)))
return "".join(sorted(S))
s1, k1 = "acbd", 2 #abcd
s2, k2 = "acbfegd", 3 # abcdefg
s = Solution()
print(s.orderlyQueue(s2, k2)) | true |
6db025c6251923c22322ecbc7889469bb06a329a | alexmudra/python_experiments | /Iterators_generators/10-delegating-to-subgenerator.py | 728 | 4.34375 | 4 | """
В Python 3 существуют так называемые подгенераторы (subgenerators).
Если в функции-генераторе встречается пара ключевых слов yield from,
после которых следует объект-генератор, то данный генератор делегирует
доступ к подгенератору, пока он не завершится (не закончатся его значения),
после чего продолжает своё исполнение.
"""
def generator():
yield from (3 * x for x in range(5))
yield from (2 * x for x in range(5, 10))
for i in generator():
print(i)
| false |
5c5fc007975705d74d9fd19a71af9db95ebb1025 | alexmudra/python_experiments | /recursia.py | 333 | 4.15625 | 4 | # прилад дуже простої рекурсії
def recursia(a):
if a == 0:
return
print("Result of recurs. func is:", a)
recursia(a - 1)
recursia(5)
'''
Result of recurs. func is: 5
Result of recurs. func is: 4
Result of recurs. func is: 3
Result of recurs. func is: 2
Result of recurs. func is: 1
''' | false |
43e8efe3e668604e701a30baa1d90f843da282c5 | alexmudra/python_experiments | /work_with_misha/one.py | 2,757 | 4.34375 | 4 | """
що значить ** ?
Возведение в степень
"""
"""
що значить //?
Целочисленное деление Возвращает неполное частное от деления. Тобто повертає тільки цілу частину
"""
"""
що значить %?
ділення по модулю. Повертає остаток від ділення
"""
"""
1) Напишите программу, которая считывает три числа и выводит их сумму. Каждое число записано в отдельной строке.
"""
#Option 1
# def summ_num (first_num, sec_num, th_num):
#
# return first_num + sec_num + th_num
#
#
# print(summ_num(12,10, 20))
"""
2) n школьников делят k яблок поровну, неделящийся остаток остается в корзинке.
Сколько яблок достанется каждому школьнику?
Сколько яблок останется в корзинке?
Программа получает на вход числа n и k и должна вывести искомое количество яблок (два числа).
"""
n = int(input("Введіть к-сть школярів: "))
k = int(input("Введіть к-сть яблук: "))
#перемінну х де яблука ділимо цілочисленно на к-сть учнів
x = k // n
print("kdsjfkjnsf", x)
y = k - (x * n)
print(k // n)
print(k - (k // n) * n) #це не розумію
"""
3) В школе решили набрать три новых математических класса.
Так как занятия по математике у них проходят в одно и то же время,
было решено выделить кабинет для каждого класса и купить в них новые парты.
За каждой партой может сидеть не больше двух учеников.
Известно количество учащихся в каждом из трёх классов.
Сколько всего нужно закупить парт чтобы их хватило на всех учеников?
Программа получает на вход три натуральных числа: количество учащихся в каждом из трех классов.
"""
n = int(input("Введіть к-сть школярів в 1му класі: "))
s = int(input("Введіть к-сть школярів в 2му класі: "))
t = int(input("Введіть к-сть школярів в 3му класі: "))
s = (n+s+t)//2
print("Кількість парт", s)
| false |
718b17342a0808a0207ca3959703125f2689a24c | chrislimqc/NTU_CompSci | /CZ2001/selfpractice/binarySearch.py | 1,232 | 4.21875 | 4 | # list is the list to be searched through
# start is the original index of the first item in the list
# end is the original index of the last item in the list
# n is the value you want to find
def binarysearch(list, start, end, x):
if end < start:
return -1
else:
mid = (start + end) // 2
if list[mid] == x:
return mid
elif x < list[mid]: # if x is smaller than middle (on the left)
return binarysearch(list, start, mid-1, x)
else: # if x is larger than middle (on the right)
return binarysearch(list, mid+1, end, x)
testList_even = [1, 2, 4, 7, 11, 16] # test data set (even number of items)
print("Original list is " + str(testList_even))
print("16 is found in index " + str(binarysearch(testList_even, 0, len(testList_even)-1, 16)))
print("13 is found in index " + str(binarysearch(testList_even, 0, len(testList_even)-1, 13)))
testList_odd = [1, 2, 4, 7, 11, 16, 22] # test data set (odd number of items)
print("Original list is " + str(testList_odd))
print("16 is found in index " + str(binarysearch(testList_odd, 0, len(testList_odd)-1, 16)))
print("13 is found in index " + str(binarysearch(testList_odd, 0, len(testList_odd)-1, 13))) | true |
5e9f8f1ab4b800cbc21fdbe592361f91528a7756 | ravi4all/PythonWE_Morning_2020 | /Input_Statement.py | 291 | 4.21875 | 4 | # by default input returns string type of data
name = input("Enter your name : ")
print("Hello " + name)
# we need to type cast input into int
num_1 = int(input("Enter first number : "))
num_2 = int(input("Enter second number : "))
result = num_1 + num_2
print("Result is",result)
| true |
79355011190fdb3302e45815197715cf39fd4de3 | janealdash/Part4 | /Task4.py | 801 | 4.125 | 4 | # 4)ContactList
# Создайте класс ContactList, который должен наследоваться от
# встроенного класса list. В нем должен быть реализован метод
# search_by_name, который должен принимать имя, и возвращать список
# всех совпадений. Замените all_contacts = [ ] на all_contacts =
# ContactList(). Создайте несколько контактов, используйте метод
# search_by_name.
class ContactList(list):
def search_by_name(self):
all_contacts={'Mommy':00001,'Daddy':00002,'Jane':00003,'Granny':00004}
name=input('Enter the name:')
print(all_contacts.get(name))
all_contacts=ContactList()
all_contacts.search_by_name()
| false |
785fb86db12ecb371202ce3fab255a7925139b9c | FlorinCiocirlan/Dojos | /exercise1.py | 539 | 4.25 | 4 | """ try:
print("Hello !")
user_input=float(input("How many degrees are in your city right now ? : "))
print("Okay so there are " , user_input , "Fahrenheit degrees")
print("So if you would have been in Europe")
celsius=(5/9) * (user_input - 32)
print("There would have been like" ,float(celsius), "Celsius Degrees right now")
except ValueError as e:
print("The value of Farenheit Degrees can't be literals") """
"""
print(float("8.7"))
print(int(8.7))
print(int(float(8.6))) """
print(str(8.6))
print(bool(8)) | false |
f20972ec9c710ac5ef9f5319d7b70a4a96075418 | dangerous3/geekbrains-python-algorithms-and-data-structures | /m2-cycles-functions-recursion/task2.py | 1,045 | 4.3125 | 4 | '''
Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
'''
a = input('Введите целое число: ')
# Счетчик четных цифр
odd = 0
# Счетчик нечетных цифр:
even = 0
# Цикл выполняется столько раз, сколько цифр в числе
for i in range(len(a)):
# Пример получения цифры 6 (второй с конца) в числе 34560: 34560 % 100 = 60 (остаток от деления), затем этот
# остаток целочисленно делим на 10: 60 // 10 = 6
num = (int(a) % (10 ^ (i + 1))) // 10 ^ i
if num % 2 == 0:
odd += 1
else:
even += 1
print(f'Количество четных цифр в числе {a}: {odd}, количество нечетных цифр: {even}')
| false |
d31f745373c6ef9ae06c6a4e58d8333db77e0228 | dangerous3/geekbrains-python-algorithms-and-data-structures | /m2-cycles-functions-recursion/task7.py | 588 | 4.15625 | 4 | '''
Написать программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство:
1+2+...+n = n(n+1)/2, где n — любое натуральное число.
'''
n = int(input('Введите n: '))
sum = 0
for i in range(n):
sum = sum + (i + 1)
print(f'Сумма чисел от 1 до {n}: {float(sum)}')
print(f'Сумма чисел по формуле: {(n * (n + 1)) / 2}')
if sum == (n * (n + 1)) / 2:
print('Формула верна!')
| false |
af353531af5f83e506bff32a823985180d522330 | dangerous3/geekbrains-python-algorithms-and-data-structures | /m1-algorithms-intro/task2.py | 881 | 4.34375 | 4 | '''По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b,
проходящей через эти точки.'''
x1 = input("Введите абсциссу первой точки: ")
y1 = input("Введите ординату первой точки: ")
x2 = input("Введите абсциссу второй точки: ")
y2 = input("Введите ординату второй точки: ")
x1 = float(x1)
y1 = float(y1)
x2 = float(x2)
y2 = float(y2)
# Уравнение прямой, проходящей через две точки: (y2 - y1) * x + (x2 -x1) * y + (x1 * y2 - x2 * y1) = 0
print(f"Уравнение прямой, проходящей через две заданные точки: {y2 - y1} * x + {x2 - x1} * y + ({x1 * y2 - x2 * y1}) = 0")
| false |
ade6ab0a4a0293c3ebf4c8e88cfa88356b21dc56 | TharunEllendula/Python | /Day4_B21.py | 1,253 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
##Introduction to list datatype
# In[9]:
#def:list is defined as order collection of items
# In[1]:
To difine a list we use -----> []
# In[ ]:
# In[ ]:
students = ['ram','shiva','sai','sita']
# In[2]:
type(students)
# In[ ]:
#assigning the individual elements on the opt:
# In[ ]:
Intro to index : it starts with 0,1,2,3,4,5.........
# In[3]:
students[1]
# In[ ]:
How to modify,alter,delete the elements in the list data type
# In[4]:
print(students)
# In[ ]:
# In[ ]:
## Modify the the data shiva ------> shivam
# In[5]:
students[1] = 'shivam'
# In[6]:
print(students)
# In[ ]:
# In[ ]:
## Append(add's at last) the the data --------> radha
# In[ ]:
# In[7]:
students.append('radha')
# In[8]:
print(students)
# In[10]:
## append at selceted place means insert
# In[12]:
print(students)
# In[14]:
students.insert(1, 'hari')
# In[15]:
print(students)
# In[16]:
print(students[1])
# In[ ]:
# In[17]:
#how to del the element from list
# In[18]:
print(students)
# In[20]:
del students[4]
# In[21]:
print(students)
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
| false |
5a63006c0afb9c11bb5bfc0c24990aacaca23336 | inhyebaik/Practice-Coding-Questions | /algorithms/mergesort.py | 830 | 4.15625 | 4 | def mergesort(arr):
"""
Time: O(N log N)
"""
if len(arr) < 2:
return arr
mid = len(arr) // 2
left = mergesort(arr[:mid])
right = mergesort(arr[mid:])
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
import unittest
class Tests(unittest.TestCase):
def test_mergesort(self):
f = mergesort([3, 2, 1, 7, 6, 5, 4])
answer = [1,2,3,4,5,6,7]
self.assertEqual(f, answer)
if __name__ == '__main__':
unittest.main() | false |
ea2c8fd61208ada04547b9847e5349fb0d220536 | Nahayo256/cswpy | /5.py | 705 | 4.46875 | 4 | #Three Restaurants: Start with your class from Exercise 9-1. Create three
#different instances from the class, and call describe_restaurant() for each
#instance.
class restaurant():
def __init__(self, name, cuisine_type):
self.name = name.title ()
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.name +' serves the best '+ self.cuisine_type + ".")
def open_restaurant(self):
print(self.name + " is now open.")
a = restaurant('Medelin Restaurant','Mexican food')
a.describe_restaurant()
b = restaurant('Village Restaurant','Ugandan food')
b.describe_restaurant()
c = restaurant('KFC Restaurant','fast food')
c.describe_restaurant() | true |
f932804f1495a5a248344334f75aa4057b6fd700 | Gurshansingh1206/pyk | /hello.py | 463 | 4.34375 | 4 | # Reversing a list using reversed()
#def Reverse(lst):
#return [ele for ele in reversed(lst)]
# Driver Code
lst = [10, 11, 12, 13, 14, 15]
print(reversed(lst))
# Reversing a list using reverse()
def Reverse(lst):
lst.reverse()
return lst
print(Reverse(lst))
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
G=["Gurshan","Gurveer","Gurwinder"]
A=["Abhi","Gunnu","Sabbi"]
print(G+A)
A=[[1,2],[3,4],[5,6],[[12,21],[31,13]],[7,8]]
print(A)
| false |
3f4f4e5e343880994886b6c17590258f2e860114 | winnie-cypher/Zuri-tasks | /hello.py | 2,036 | 4.3125 | 4 |
#variable
#cup => anything you want, ranging from liquid to solid, to other things
#cup = "water"; #water is the content inside the container cup. our container is a variable
#print(cup)
#cup = "sand"
#print(cup)
#calculations
#Firstvalue = 50
#SecondValue = 20
#operation - addition
#result = Firstvalue + SecondValue
#print(result)
#crate = ["Sand","water",7,5.9,True] #list, array
#print (crate[0])
#crate.append("mike")
#print (crate[5])
#name = "Mike" #string - s
#age = 55 #number - d
#print("His name is %s and he is %d years old" % (name,age))
#sampleList = ['Mike','love','dove']
#print("some text %s" % sampleList)
#string = "i am a string"
#string2 = "mike b"
#string3 = "UPPERCASE"
#print(string3.lower())
#print(string[::-1])
#print(string.startswith("i"))
#print(string.startswith("p"))
#operators
#firstValue = 14
#secondValue = 3'''
#print(firstValue + secondValue)
#print(firstValue - secondValue)
#print(firstValue * secondValue)
#print(firstValue / secondValue)'''
#assignment operators
#variable = 5
#comparison
##print(firstValue == secondValue)
#print(firstValue > secondValue)
#print(firstValue < secondValue)
#print(firstValue <= secondValue)
#remainder
#print(firstValue % secondValue)
#voice = "Shout "
#print (voice * 5)
#aList = [1,2,3,4,5,6]
#print (aList * 3)
#A = [1,2,3,4]
#B = [5,6,7,8]
#print (A + B)
#age = 35
#print (age)
#age += 1
#print(age)
#age = 18
#height = 4
#if(age >= 18 and height >= 5):
#print('person can get on the ride')
#elif(age < 18 or height < 5):
#print('person cannot get on this ride')
#else:
#print('Error, something went wrong with your inputs')
#import datetime
##print ("Current date and time : ")
#print(date.strftime("%Y-%m-%d %H:%M:%S"))'''
#loops
#aList = [1,2,3,4,5,6]
#for item in aList:
# print (item)
#for x in range(6):
##if(not(x == 0)):
# print(x)
#count = 5
#while count > 0:
#print (count);
# count -= 1
def nameOfFunction(count):
print('this is a function %d' % count)S
| true |
83d55bb9ee00ff1708665008e838828c2153d6f8 | yanbarabankz/Netology | /Homeworks/Python Basics/Homework № 3 on Python Basics.py | 2,043 | 4.25 | 4 |
while True:
day = int(input("Введите день: "))
month = input("Введите месяц: ")
if (month == 'Январь' and day >=21) or (month == 'Февраль' and day <=18):
print('Ваш знак зодиака: Водолей')
if (month == 'Февраль' and day >=19) or (month == 'Март' and day <=20):
print('Ваш знак зодиака: Рыбы')
if (month == 'Март' and day >=21) or (month == 'Апрель' and day <=19):
print('Ваш знак зодиака: Овен')
if (month == 'Апрель' and day >=20) or (month == 'Май' and day <=20):
print('Ваш знак зодиака: Телец')
if (month == 'Май' and day >=21) or (month == 'Июнь' and day <=21):
print('Ваш знак зодиака: Близнецы')
if (month == 'Июнь' and day >=22) or (month == 'Июль' and day <=22):
print('Ваш знак зодиака: Рак')
if (month == 'Июль' and day >=23) or (month == 'Август' and day <=22):
print('Ваш знак зодиака: Лев')
if (month == 'Август' and day >=23) or (month == 'Сентябрь' and day <=22):
print('Ваш знак зодиака: Дева')
if (month == 'Сентябрь' and day >=23) or (month == 'Октябрь' and day <=23):
print('Ваш знак зодиака: Весы')
if (month == 'Октябрь' and day >=24) or (month == 'Ноябрь' and day <=22):
print('Ваш знак зодиака: Скорпион')
if (month == 'Ноябрь' and day >=23) or (month == 'Декабрь' and day <=21):
print('Ваш знак зодиака: Стрелец')
if (month == 'Декабрь' and day >=22) or (month == 'Январь' and day <=20):
print('Ваш знак зодиака: Козерог')
print()
| false |
2eee34e4d21e45a3c06438368fa885bf9d2cda3d | Niksscoder/Pygame | /Lecture/lecture_04.py | 1,435 | 4.25 | 4 | # keyboard events
import pygame
# methods of this lecture
# pygame.MOUSEBUTTONDOWN – mouse click down;
# pygame.MOUSEBUTTONUP – mouse click up;
# pygame.MOUSEMOTION – moving the mouse cursor;
# pygame.MOUSEWHEEL – mouse wheel rotation.(вращение)
pygame.init()
#size of screnn
W = 600
H = 400
#screen
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("mouse events")
#colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
FPS = 60
clock = pygame.time.Clock() # for FPS
# for drawing some figures
# if sp == None: for this case we don't draw rect yet
# else --> draw
sp = None
screen.fill(WHITE)
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
pressed = pygame.mouse.get_pressed()
# [0] index means that clicked down on the left button
if pressed[0]:
# return set of coordinates
pos = pygame.mouse.get_pos()
if sp is None:
# if we haven't started drawing yet -->
# sp ==pos(start position)
sp = pos
width = pos[0] - sp[0]
height = pos[1] - sp[1]
screen.fill(WHITE)
pygame.draw.rect(screen, RED, (sp[0], sp[1], width, height))
pygame.display.update()
else:
sp = None
clock.tick(FPS)
| true |
b23d7976569aea0c0df7728d9c36895f45a1f68c | elmotoja/lists-for-classes | /extra/data_structures_sets.py | 1,972 | 4.40625 | 4 | # sets
# The set data structure in Python models the mathematical definition of a set:
# an unordered collection of unique objects.
# The easiest way to think about sets is that they are like dictionaries without values; that is, the keys in a dictionary are a set.
# Checking whether something is in a set is very efficient compared to data structure like a list or tuple.
#
# Set literals are notated like dictionary literals, except that there are no values.
# To construct an empty set however, you need to use the set() function,
# ... as the {} literal is interpreted as an empty dictionary instead of an empty set.
numbers = set() # example how to create an empty set
duplicates = [1, 2, 1, 3, 1, 5, 2, 6, 7]
numbers = set(duplicates)
print(len(numbers), numbers)
# Because sets are unordered data structures, they cannot be indexed.
# Testing for membership (if x in y:)
# and iterating over a set (for x in y:)
# ... work in the same way as other data structures we have seen in Python.
# An object can be added to a set using the .add()
# Objects already in the set can be removed using the .remove() method
# Adding an object which is already in the set has no effect.
numbers = set([1,2,3])
numbers.add(5)
numbers.remove(2)
print(numbers)
# Mathematical sets have a number of standard operations that can be performed on two sets. Python sets have support for the union, intersection, and difference operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union
print(a & b) # Intersection
print(a - b) # Difference
print(b - a) # Difference
print(a ^ b) # Symmetric difference
# comparing sets
#
# Mathematical sets have three notions of comparison, which Python sets also implement. These are: is a subset, is a superset, and is disjoint.
a = {1, 2, 3}
b = {3, 4, 5}
c = {1, 2}
print(a.issubset(b), a.issuperset(b), a.isdisjoint(b))
# only hashable objects (it is mostly about being mutable) can be inserted into set (e.g. lists cannot)
| true |
6d486086fa4d48e50153cf2a8a04e6e2dc541092 | Anderson-git-oracle/python_fundamentals | /aula/aula06.py | 1,105 | 4.15625 | 4 | # Funçõe
# lista = []
# def adiciona(valor):
# global lista
# return lista.append(valor)
# def remove(valor):
# global lista
# return lista.remove(valor)
# adiciona('batata')
# remove('batata')
# print(lista)
#crie uma função que peça 2 números e retorne o maior
#se o valor for igual retorna "valores iguais"
# guarde em variavel e print
# def digite_2numeros(x,y):
# if x == y:
# print('valores iguais')
# else:
# return max(x,y)
# var = digite_2numeros (4,9)
# print(var)
# def ordenar(*valores):
# return sorted(valores, reverse=True)
# def subtrair(x,y):
# '''subtrai valores'''
# return x - y
# sub = lambda x,y: x - y
# carrinho = [{"nome": "Tenis", "valor": 21.70}, {"nome": "camiseta", "valor": 10.33}]
# black_friday = lambda x: x/2
# for c in carrinho:
# print(f'Nome do produto: {c["nome"]}')
# print(f'valor original: {c["valor"]}')
# print(f'valor com desconto: {black_friday(c["valor"])}')
# print('=-'*11)
# items = [1, 2, 3, 4, 5]
# double = list(map(lambda x: x*2, items))
# print(double)
| false |
3944d611ed2b679d0ddc1b2171e507c3f3168db4 | gaurabgain/python_practices | /angelayu/34pizzaV2.py | 594 | 4.21875 | 4 | #this is a pizza ordering program.
#size and price of pizza - small $15, medium $20, large $25.
#paperoni for - small +$2, medium & large +$3.
#cheese for +$1.
print("Welcome to python pizza.")
size=input("Which size of pizza do you want?\nS(small),M(medium),L(large)\n")
paperoni=input("Do you want paperoni?\Y/N\n")
cheese=input("Do you want cheese?\nY/N\n")
bill=0
if size=="S":
bill+=15
elif size=="M":
bill+=20
elif size=="L":
bill+=25
if paperoni=="Y":
if size=="S":
bill+=2
else:
bill+=3
if cheese=="Y":
bill+=1
print(f"Your bill is ${bill}.")
| true |
e41a8dd1549f9343d7245ba38ea16c6d35efa2f2 | alagram/Algorithms | /python/recursion/is_palindrome_with_indices.py | 353 | 4.1875 | 4 | # start is staring idex
# end is length of string
def is_palindrome(string, start, end):
if end <= 1:
return True
else:
return string[start] == string[end-1] and is_palindrome(string[start+1:end-1], start, end-2)
print is_palindrome("radar", 0, 5)
print is_palindrome("aibohphobia", 0, 11)
print is_palindrome("albert", 0, 6)
| true |
3c3c4aff06b3048381efc3b30e631ca26e641a83 | zac-higgins/Sprint-Challenge--Graphs | /search.py | 2,288 | 4.125 | 4 | from util import Queue, Stack
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
"""
Add a vertex to the graph.
"""
self.vertices[vertex_id] = set() # set of edges
# print("vertex added!")
def add_edge(self, v1, v2):
"""
Add a directed edge to the graph.
"""
if v1 in self.vertices:
self.vertices[v1] = v2
else:
raise IndexError("Vertex does not exist in graph")
def get_neighbors(self, vertex_id):
"""
Get all neighbors (edges) of a vertex.
"""
directions = self.vertices[vertex_id]
# for direction in directions:
# if directions[direction] != '?':
# return self.vertices[vertex_id]
def dft(self, starting_vertex):
"""
Print each vertex in depth-first order
beginning from starting_vertex.
"""
stack = Stack()
stack.push(starting_vertex)
visited = set()
while stack.size() > 0:
current_vertex = stack.pop()
# print(current_vertex)
if current_vertex not in visited:
visited.add(current_vertex)
print(current_vertex)
for next_vertex in self.get_neighbors(current_vertex):
stack.push(next_vertex)
# for vertex in visited:
# print(vertex)
def dfs(self, starting_vertex, destination_vertex):
"""
Return a list containing a path from
starting_vertex to destination_vertex in
depth-first order.
"""
stack = Stack()
stack.push(starting_vertex)
visited = set()
path = []
while stack.size() > 0:
current_vertex = stack.pop()
if current_vertex == destination_vertex:
path.append(current_vertex)
return path
if current_vertex not in visited:
visited.add(current_vertex)
path.append(current_vertex)
for next_vertex in self.get_neighbors(current_vertex):
stack.push(next_vertex) | true |
0c180bb21b2af3010c47ea3713db9942621602b4 | huginngri/Timaverkefni | /Tími7/V5.py | 559 | 4.28125 | 4 | import string
# palindrome function definition goes here
def pali(flottur):
gamliflottur = flottur.lower()
bilofl = string.whitespace + string.punctuation
for char in gamliflottur:
if char in bilofl:
gamliflottur = gamliflottur.replace(char, '')
if gamliflottur[::-1] == gamliflottur:
return flottur + " is a palindrome."
else:
return flottur + " is not a palindrome"
in_str = input("Enter a string: ")
# call the function and print out the appropriate message
awns = pali(in_str)
print(awns) | true |
449f3639fdf3d81faca085a2ee53e5108c21be87 | Erin-dunn/e_dunn_python3rps | /gameFunctions/winlose.py | 1,050 | 4.125 | 4 | from random import randint
from gameFunctions import gamedunn
# define a python funtion that takes an argument
def winorlose(status):
#status will be either won or lost - you're passing this in as an argument
print ("called win or lose")
print("*******************")
print("You", status + "! Would you like to play again?")
choice = input ("Y / N: ")
print(choice)
if (choice is "N") or (choice is "n"):
print("You chose to quit.")
exit()
elif (choice is "Y") or (choice is "y"):
#reset the game so that we can we can start all over again
#this will break, currently - we will fix this next class
gamedunn.player_lives = 1
gamedunn.computer_lives = 1
gamedunn.total_lives = 1
gamedunn.player = False
gamedunn.computer = gamedunn.choices[randint(0,2)]
else:
#not a y or n, so make the user pick a valid choice
print("make a valid choice, Y or N")
#this is recursion - call a function
#from insoode itself. Basically just re-up the choice
#and force the user to pick yes or no(y or n)
winorlose(status)
| true |
910311c8135e3e89feb307906fe23291b1928733 | 124tranvita/inventwithpython_3rd | /dragons.py | 1,493 | 4.125 | 4 | import random
import time
#display the intro of the game
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
#ask player to choose what cave will be go into
def chooseCave():
choice = 0
while choice not in [1, 2]:
try:
choice = int(input('which cave will you go into? (1 or 2) '))
except:
print('Character not accepted!!!')
else:
print('Please select only 1 or 2!!!')
return choice
#check the dragon in this cave is friendly or not by random.randint()
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
time.sleep(2)
friendlyDragon = random.randint(1,2)
if chosenCave == friendlyDragon:
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite')
while True:
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
#ask player if they want to play again or not
choice = input('Play again? Y or N')
if choice[0].lower() == 'y':
continue
else:
print('Thank for playing game!!!')
break
| true |
77295801c217784ad3e99df259c3b585d2e26ed2 | CarolinaFraser/mirepositorio | /funciones/hektor5.py | 717 | 4.15625 | 4 | '''
Realiza una función llamada recortar(numero, minimo, maximo)
que reciba tres parámetros. El primero es el número a
recortar, el segundo es el límite inferior y el tercero el
límite superior. La función tendrá que cumplir lo siguiente:
Devolver el límite inferior si el número es menor que éste
Devolver el límite superior si el número es mayor que éste.
Devolver el número sin cambios si no se supera ningún límite.
Comprueba el resultado de recortar 15 entre los límites 0 y 10.
'''
def recortar(numero, minimo, maximo):
if numero < minimo:
return minimo
elif numero > maximo:
return maximo
else:
return numero
print(recortar(15,0,10)) | false |
1594b44d89b71e7e98b44769c2bbd148637f1b8f | hectorRperez/ejercicios-listas-tuplas | /ejercicio7_practica.py | 576 | 4.1875 | 4 | """ Ejercicio 7
Escribir un programa que almacene el abecedario en una lista,
elimine de la lista las letras que ocupen posiciones múltiplos de 3,
y muestre por pantalla la lista resultante. """
def mostrar_abecedario():
abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(len(abecedario), 0, -1):
if i % 3 == 0:
abecedario.pop(i-1)
print(abecedario)
if __name__ == '__main__':
mostrar_abecedario() | false |
e3497e8209d370d54cfbaad2ce5c7bda020b8a51 | hectorRperez/ejercicios-listas-tuplas | /ejercicio1_practica.py | 430 | 4.1875 | 4 | """ Ejercicio 1
Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua)
en una lista y la muestre por pantalla. """
def mostrar_materias(lista_materias):
for i in lista_materias:
print(i)
if __name__ == '__main__':
lista_materias = ['Matematicas','Física','Química', 'Historia', 'Lengua']
mostrar_materias(lista_materias) | false |
7ee85dedd6d11f2f6485c71ae684f6dff16121fd | AbdoDameen/Projects | /Programming Challenges/Ingredient Adjuster.py | 471 | 4.125 | 4 | number_of_cookies = float(input("How many are you trying to make: "))
sugar = 0.0312
flour = 0.0573
butter = 0.0208
sugar_amout = sugar * number_of_cookies
flour_amout = flour * number_of_cookies
butter_amount = butter * number_of_cookies
print("You would need "+ format(sugar_amout, '.2f') + " cup of sugar")
print("You would need "+ format(flour_amout, '.2f') + " cup of flour")
print("You would need "+ format(butter_amount, '.2f') + " cup of butter")
| true |
e66d45bf39e278e700297a124bbc7d96f34498e7 | afitz-gmu/code_examples | /Python/worksheet3_part2.py | 1,303 | 4.40625 | 4 | import math
class Point:
"""Represents two dimensional point
Attributes: x, y coordinate"""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
print("X coordinate: ", self.x)
print("Y coordinate: ", self.y)
x = int(input("Please enter an x coordinate: "))
y = int(input("Please enter an y coordinate: "))
point = Point(x, y)
class Circle:
"""creates a circle with a radius and point value"""
def __init__(self, radius):
self.radius = radius
point = Point(x, y)
def print(self):
print("X coordinate: ", point.x)
print("Y coordinate: ", point.y)
print("The radius of the circle is: ", self.radius)
print("The area of the circle is: %3f" % (self.area))
def move(self):
point.x = int(input("Please enter a new x coordinate: "))
point.y = int(input("Please enter a new y coordinate: "))
def area(self):
self.area = math.pi * (self.radius * self.radius)
radius = float(input("Please enter a radius: "))
circle = Circle(radius)
circle.area()
circle.print()
# calls the move method which will update the x and y values of the circle
circle.move()
#prints out the new circle details
circle.print()
| true |
fe0628f11143c43e0bfb133ff6128ee37d6ada09 | iustitia/examples | /dict_print.py | 269 | 4.28125 | 4 | d = {'anna': 4, 'jan': 5, 'maja': 7}
name = 'anna'
#print(d['anna'])
#print(d[name])
for key in d:
print(key)
print(d[key])
print('----')
for key, value in d.items():
print(key)
print(value)
print('----')
for value in d.values():
print(value)
| false |
fc248d4ae943bac60a38ed390e9c1975e7953f6b | sachinjose/Coding-Prep | /CTCI/Tree & Graph/q4.2.py | 555 | 4.125 | 4 | ### binary search tree with minimum height
class Node:
def __init__(self,item):
self.item = item
self.left = None
self.right = None
def create_tree(tree,start,stop):
if stop > start:
mid = (start + start)//2
root = Node(tree[mid])
root.left = create_tree(tree,start,mid-1)
root.right = create_tree(tree,mid+1,stop)
return root
else:
return None
def inorder(root):
if(root):
inorder(root.left)
print(root.item)
inorder(root.right)
tree = [1,2,3,4,5,6,7]
root = Node(0)
root = create_tree(tree,0,len(tree))
inorder(root) | true |
fb8010bc1c9a566be606d34b83b5b45f75152121 | rafaelsantosmg/cev_python3 | /cursoemvideo/ex087.py | 959 | 4.3125 | 4 | """Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
No final, mostre a matriz na tela, com a formatação correta.
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha."""
matriz = [[], [], []]
pares = []
par = coluna = num = 0
for l in range(0, 3):
for c in range(0, 3):
num = int(input(f'Informe o valor para a matriz [{l}, {c}]: '))
matriz[l].append(num)
if matriz[l][c] % 2 == 0:
par += num
pares.append(num)
print('=*' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]:^5}]', end='')
print()
for l in range(0, 3):
coluna += matriz[l][2]
print('=*' * 30)
print(f'A soma de todos os valores pares {pares} são: {par}')
print(f'A soma dos números da terceira coluna são: {coluna}')
print(f'Maior valor da segunda linha é {max(matriz[1])}')
| false |
508ccaaa7baf24d8113e5edc58b734da86241eb4 | rafaelsantosmg/cev_python3 | /cursoemvideo/ex039.py | 1,357 | 4.125 | 4 | """Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se
alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo."""
from datetime import date
from utilidadescev.dado import leiaint
from utilidadescev.string import linha
atual = date.today().year
linha(50, 'azul')
nasc = leiaint('Em que ano você nasceu? ')
sexo = str(input('Informe o sexo: M - Masculino, F - Feminino ')).upper().strip()
linha(50, 'azul')
idade = atual - nasc
linha(50, 'verde')
if sexo == "M":
print(f'Quem nasceu em {nasc} tem {idade} anos em {atual}')
if idade == 18:
print('Você tem que se alistar imediatamente!')
elif idade < 18:
saldo = 18 - idade
print(f'Falta {saldo} anos para você fazer o alistamento!')
print(f'Seu alistamento será no ano de {atual + saldo}')
else:
saldo = idade - 18
print(f'Já passou {saldo} anos do tempo do alistamento!')
print(f'Seu alistamento foi no ano {atual - saldo}')
elif sexo == "F":
print('O alistamento militar é obrigatório apenas para Homens!')
linha(50, 'verde')
else:
linha(30, 'vermelho')
print('Opção inválida')
linha()
print('Tenha um bom dia!')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.