blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1edba41774723a9513d2f54f1124286b91de2b22 | Greesha1337/python_basic_11.05.2020 | /hw5/hw5_task1/task1.py | 602 | 4.3125 | 4 | # Lesson 5 HomeWork - Task 1
"""
Создать программно файл в текстовом формате,
записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
with open('user_file.txt', 'a', encoding='UTF-8') as file:
while True:
user_words = input('Введите данные для записи в файл: ')
if user_words == '':
break
file.write(user_words + '\n')
file.close()
| false |
479a5121a83c7d842158e0103026d6705b5a355c | bdrummo6/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 2,415 | 4.375 | 4 |
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
new_node = BSTNode(value)
# Compare the new value with the parent node
if self.value:
# if value is less than the current parent node value
if value < self.value:
# if there is no left child node then a new node with the value is inserted to the left
if not self.left:
self.left = new_node
# if there is a left child node then insert is called on the left child node
else:
self.left.insert(value)
# if value is greater than or equal to the current parent node value
elif value >= self.value:
# if there is no right child node then a new node with the value is inserted to the right
if not self.right:
self.right = new_node
# if there is a right child node then insert is called on the right child node
else:
self.right.insert(value)
# if the root node of the BST is None then the new value is assigned to the root node's value
else:
self.value = value
# Return True if the tree contains the value and False if it does not
def contains(self, target):
if not self:
return False
# if the target value is less than current parent node's value
if target < self.value:
# if there is no left child node then the BST does not contain the target value
if not self.left:
return False
# if there is a left child node then contains is called on the left child node
return self.left.contains(target)
# if the target value is greater than or equal to the current parent node's value
elif target > self.value:
# if there is no right child node then the BST does not contain the target value
if not self.right:
return False
# if there is a right child node then contains is called on the right child node
return self.right.contains(target)
# target value is equal to the current node value
else:
return True
| true |
c949deb09588dd751cccd359fa7c403e47a1a46c | stefanpostolache/pythonHandsOnExamples | /complete/example-0/main.py | 1,433 | 4.21875 | 4 | import random
"""
Module containing functions to create a hand of cards
"""
def createHand(handsize):
"""
Creates a hand of cards
Args:
handsize (int): size of the hand of cards
Returns:
tuple: hand and remainder of the deck
"""
deck = generateDeck()
deck = shuffle(deck)
return deal(deck,handsize)
def generateDeck():
"""Generates a deck
Returns:
list: deck of cards
"""
deck = []
values = ["Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"]
suits = ["hearts","diamonds","spades","clubs"]
for value in values:
for suit in suits:
deck.append(value+" of "+suit)
return deck
def shuffle(deck):
"""Shuffles a deck of cards
Args:
deck (list): deck of cards
Returns:
list: shuffled deck of cards
"""
random.shuffle(deck)
return deck
def deal(deck,handsize):
"""
Separates a hand from the rest of the deck
Args:
deck (list): deck of cards
handsize (int): how many cards should a hand have
Returns:
tuple: hand and remainder of deck
"""
return (deck[:handsize],deck[handsize:])
def contains(deck,card):
"""[summary]
Args:
deck ([type]): [description]
card ([type]): [description]
Returns:
[type]: [description]
"""
return card in deck
| true |
bbdf381fbe52e6039ea91ba56e7cbd259b503ae9 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula09/aula09_1.py | 803 | 4.65625 | 5 | """Exemplos aula 09."""
frase = ' Curso em Vídeo Python '
print(frase)
print(frase[3])
print(frase[3:13])
print(frase[:13])
print(frase[1:15:2])
print(frase[::2])
print("""Nessa aula, vamos aprender operações com String no Python.
As principais operações que vamos aprender são o Fatiamento de String,
Análise com len(), count(), find(), transformações com replace(), upper(),
lower(), capitalize(), title(), strip(), junção com join().""")
print(frase.count('o'))
print(frase.upper().count('O'))
print(len(frase))
print(len(frase.strip()))
print(frase.replace('Python', 'Android'))
frase = frase.replace('Python', 'Android')
print('Curso' in frase)
print(frase.find('Vídeo'))
print(frase.find('vídeo'))
print(frase.lower().find('vídeo'))
dividido = frase.split()
print(dividido[2][3])
| false |
90eac31f7a975d89e6aedf0b7a44e3f9fa3adb93 | gustavogattino/Curso-em-Video-Python | /Mundo 1 - Fundamentos/Aula08/aula08_1.py | 288 | 4.21875 | 4 | """Exemplos aula 08."""
# import math
from math import sqrt, floor
num = int(input('Digite um número: '))
# raiz = math.sqrt(num)
raiz = sqrt(num)
# print('A raiz de {} é igual a {:.2f}.'.format(num, math.floor(raiz)))
print('A raiz de {} é igual a {:.2f}.'.format(num, floor(raiz)))
| false |
b92b3348fa54343d7ee3a47c52ad10104292e99a | joshua-paragoso/PythonTutorials | /13_numpyArrays.py | 2,103 | 4.5625 | 5 | # Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are that
# they are fast, easy to work with, and give users the opportunity to perform calculations across entire
# arrays.
# In the following example, you will first create two Python lists. Then, you will import the numpy package
# and create numpy arrays out of the newly created lists.
# Create 2 new lists height and weight
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
# Import the numpy package as np
import numpy as np
# Create 2 numpy arrays from height and weight
np_height = np.array(height)
np_weight = np.array(weight)
print("1")
print(type(np_height))
#--Element-wise calculations--------
# Now we can perform element-wise calculations on height and weight. For example, you could take all 6 of
# the height and weight observations above, and calculate the BMI for each observation with a single
# equation. These operations are very fast and computationally efficient. They are particularly helpful
# when you have 1000s of observations in your data.
# Calculate bmi
bmi = np_weight / np_height ** 2
# Print the result
print("2")
print(bmi)
#---Subsetting----------
# Another great feature of Numpy arrays is the ability to subset. For instance, if you wanted to know which
# observations in our BMI array are above 23, we could quickly subset it to find out.
# For a boolean response
bmi > 23
# Print only those observations above 23
bmi[bmi > 23]
#--Excercise---------
# First, convert the list of weights from a list to a Numpy array. Then, convert all of the weights from
# kilograms to pounds. Use the scalar conversion of 2.2 lbs per kilogram to make your conversion. Lastly,
# print the resulting array of weights in pounds.
weight_kg = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
import numpy as np
# Create a numpy array np_weight_kg from weight_kg
np_weight_kg = np.array(weight_kg)
# Create np_weight_lbs from np_weight_kg
np_weight_lbs = np_weight_kg * 2.2
# Print out np_weight_lbs
print(np_weight_lbs) | true |
89b4791ec2c77af0224a9970b5c2f093a9e2a3a9 | AnkitaTandon/NTPEL | /python_lab/sum_of_cubes.py | 254 | 4.34375 | 4 |
'''
Q3 (Viva) : Write a Python program for finding cube sum of first n natural numbers.
'''
sum=0
n=int(input("Enter the value of n: "))
for i in range(1,n+1):
sum += (i*i*i)
print("The sum of the cubes of first n natural numbers = ", sum)
| true |
edb4f262aa8eca2abf3754958c29ad3eade451e6 | AnkitaTandon/NTPEL | /python_lab/1b.py | 245 | 4.1875 | 4 | '''
Lab Experiment 1b: Write aprogram which accepts the radius of a circle
from the user and computes it's area.
'''
num=int(input("Enter the radius of the circle: "))
a=3.14*num*num
print("Area of the circle = ",a)
| true |
32d593104fa5ca8d27dcda20491664a5a60f59bc | AnkitaTandon/NTPEL | /python_lab/add_set.py | 392 | 4.125 | 4 | '''
Lab Experiment 6b: Write a program to add members in a set.
'''
s=set({})
n=int(input("Enter the number of elements to add to a new set:"))
print("Enter the elements-")
for i in range(n):
s.add(int(input()))
print(s)
n=int(input("Enter the number of elements to update to a set:"))
print("Enter the elements-")
for i in range(n):
s.update([int(input())])
print(s)
| true |
c862d7b2ed1835580cccd4768cc7703b6a79d6e1 | nothingtosayy/Strong-Number-in-python | /main.py | 349 | 4.1875 | 4 | def StrongNumber(x):
sum = 0
for i in str(x):
fact = 1
for j in range(1,int(i)+1):
fact = fact*int(j)
sum = sum + fact
return sum
number = int(input("Enter a number : "))
if number == StrongNumber(number):
print(f"{number} is a strong number")
else:
print(f"{number} is not an strong number")
| true |
fcbf5e0b09aa329d4f5e092990d344290c2b9206 | frappefries/Python | /Assignment/ex1/prg7.py | 696 | 4.40625 | 4 | #!/usr/bin/env python3
"""Program to create a list with 10 items in it and perform the below
operations
a) Print all the elements
b) Perform slicing
c) Perform repetition with * operator
d) Concatenate with other list
Usage: python3 prg7.py
"""
def init():
"""Perform operations on the list object and display the results"""
x = [1, 231, 14, 61, 56, 85, 23, 87]
x.append(100)
x.append(91)
print("Items in the list:")
print(x)
print("Slicing elements from 5 to 8")
print(x[4:8])
print("Repetition with * operator")
print(x * 2)
y = [1, 2, 3]
print("Concatenation with another list %s" % y)
print(x + y)
if __name__ == '__main__':
init()
| true |
e838153c9ffe71dcd43b77bd2b78d198d2c14193 | frappefries/Python | /Assignment/ex1/prg6.py | 1,073 | 4.46875 | 4 | #!usr/bin/env python3
"""Program to read a string and print each character separately.
also do
a) slice the string using [:]operator to create subtstrings
b) repeat the string 100 times using the * operator
c) read the second string and concatenate it with the first string using
+ operator
Usage: python3 prg6.py
"""
def init():
"""Fetch strings and display the results of the operations listed"""
str = get_statement()
print("Characters in string:\n")
for char in str:
print(char)
print("Slicing text using [:] operator: (from start of the string till 3 characters)")
print(str[0:3])
print("\nRepeat the string 100 time using * operator")
print(str * 100)
print("\nConcatenation with second string:")
b = get_statement()
print(str + b)
def get_statement():
"""Fetch an input statement from user at runtime
Returns:
Statement inputted by user
"""
statement = input("Please enter the string:\n")
return statement
if __name__ == '__main__':
init()
| true |
5bc62025f4a8731214f840073dbfd5a980678449 | frappefries/Python | /Assignment/ex1/prg17.py | 1,038 | 4.53125 | 5 | #!/usr/bin/env python3
"""Program to find the biggest and smallest of N numbers (use functions to find
the biggest and smallest numbers)
Usage: python3 prg17.py
"""
def init():
"""Fetch 5 numbers and display the smallest and biggest number"""
num = []
print("Enter 5 numbers:")
for item in range(5):
num.append(int(input()))
print("Biggest number: %d"% get_biggest_number(num))
print("Smallest number: ", get_smallest_number(num))
def get_biggest_number(num):
"""Find the biggest number in the list
Args:
list of numbers
Returns:
biggest number in the list
"""
big = 0
for item in num:
if item > big:
big = item
return big
def get_smallest_number(num):
"""Find the smallest number in the list
Args:
list of numbers
Returns:
smallest number in the list
"""
small = num[0]
for item in num:
if small > item:
small = item
return small
if __name__ == '__main__':
init()
| true |
feef9f3d26f617fefd95cd910c2ae481f9ba8386 | jenniferjqiai/Python-for-Everybody | /Chapter 8/Exercise 4.py | 649 | 4.3125 | 4 | #Exercise 4: Download a copy of the file www.py4e.com/code3/romeo.txt.
# Write a program to open the file romeo.txt and read it line by line. For each line,
# split the line into a list of words using the split function. For each word,
# check to see if the word is already in a list. If the word is not in the list, add it to the list.
# When the program completes, sort and print the resulting words in alphabetical order
fhand = open('atestfile.txt')
wordlist=list()
for line in fhand:
words = line.split()
wordlist.extend(words)
for word in words:
if True: continue
words=words+[word]
wordlist.sort()
print(wordlist) | true |
de6b6981980fad37774192df2b7bab67f773511b | atmilich/DaltonPython | /hw2.py | 2,081 | 4.125 | 4 | def convertScoreToGrade(n):
grade = ""
if(99 <= int(n) <= 100):
print("true")
grade = "A+"
elif(96 <= int(n) <= 98):
grade = "A"
elif(93 <= int(n) <= 95):
grade = "A-"
elif(90 <= int(n) <= 92):
grade = "B+"
elif(87 <= int(n) <= 89):
grade = "B"
elif(84 <= int(n) <= 86):
grade = "B-"
elif(81 <= int(n) <= 83):
grade = "C+"
elif(78 <= int(n) <= 80):
grade = "C"
elif(75 <= int(n) <= 77):
grade = "C-"
elif(70 <= int(n) <= 74):
grade = "D"
else:
grade = "F"
print(grade)
#exercise 2: splits the string at the space and returns as a list, uses built in string.split function
def listOfWords(s):
print(str(s).split())
#exercise 3: 1) isPrime returns true or false if the integer input is prime/not prime
def isPrime(n):
j = 1
while(j <= int(n)-1):
import pdb
pdb.set_trace()
print(" ")
j+=1
print(j)
if(int(n)%j == 0):
print("False")
return False
#if(j == int(n)):
# print("True")
def listOfPrimes(n):
i = 0
while(i < int(n)):
if(isPrime(int(n)) == True):
print(str( isPrime(int(n))))
i+=1
def isPalindrome(n):
rev = n[::-1]
if(rev == n):
print("True")
else:
print("False")
def nextPalindrome(n):
rev = n[::-1]
while(str(n) != rev):
n = int(n)+1
rev = str(n)[::-1]
print(n)
exercise = 0
print("which exercise would you like to use")
exercise = raw_input()
#asks for input to ConvertScore
if(exercise == "1"):
print("enter the score")
score = raw_input()
convertScoreToGrade(score)
#input for listOfWords
elif(exercise == "2"):
print("enter the sentence")
sen = raw_input()
listOfWords(sen)
elif(exercise == "3"):
print("enter the number to 1. see if it is prime and 2. get the list of prime numbers until that number.")
number = raw_input()
isPrime(number)
listOfPrimes(number)
#elif(exercise == "4"):
#well spaced prime fact.
elif(exercise == "5"):
print("enter a number to see if it's a palindrome")
number = raw_input()
isPalindrome(number)
elif(exercise == "6"):
print("enter a number to find its next palindrome")
number = raw_input()
nextPalindrome(number)
| true |
f3fddc03d0ba3399490a014e3bbcae93a411cf62 | EarthenSky/Python-Practice | /misc&projects/ex(1-5).py | 1,154 | 4.28125 | 4 | # This is a built in python library that gives access to math functions
import math
# Uses pythagorean theorm to find the hypotenuse of a triangle
def find_hypotenuse(a, b):
return math.sqrt(a ** 2 + b ** 2)
# Inital statement
print "This is a right triangle hypotenuse calculator."
# Define Global input parameters
g_a = 0
g_b = 0
# If the equality statement returns a True value the loop will repeat code inside it.
# Query user input with a try catch in a while loop
valid_input = False
while valid_input == False:
# try catch statements (in this case try exerpt statements) will run specific
# code if a error is caught.
try:
# raw_input() returns user typed input while printing a mesage at the same time.
g_a = float(input("Input the length of side A: "))
g_b = float(input("Input the length of side B: "))
valid_input = True
except ValueError:
print "Oops! That was not a valid NUMBER. Try again... \n"
valid_input = False # keep the loop repeating because the value was not valid
print "The length of the hypotenuse (side C) is: {}".format(find_hypotenuse(g_a, g_b))
| true |
8da15a787b0276cae157b598910d8eadbc809ee0 | EarthenSky/Python-Practice | /misc&projects/ex(1-4).py | 1,314 | 4.3125 | 4 | # Initial print statements
print "Name: Gabe Stang"
print "Class: Magic Number 144"
print "Teacher: Mr. Euclid \n"
# "def" is how you define a function / method.
# A function in python may or may not have a return value.
# Outputs a string detailing what numbers were added and the solution
def string_sum(num1, num2):
return "{} + {} = {}".format(num1, num2, num1 + num2)
# Outputs a string detailing what numbers were multiplied and the solution
def string_mul(num1, num2):
return "{} * {} = {}".format(num1, num2, num1 * num2)
# Outputs a string detailing what numbers were divided and the solution
def string_div(num1, num2):
return "{} / {} = {}".format(num1, num2, num1 / num2)
# Outputs a string detailing what number was squared and the solution
def string_sqr(num1):
return "{}^2 = {}".format(num1, num1 ** 2)
# Problem answers using string.format()
print "1. {}".format(string_sum(144, 144))
print "2. {}".format(string_sum(144, -19))
print "3. {}".format(string_mul(144, 9))
print "4. {}".format(string_div(144, 12))
print "5. {}".format(string_sqr(144))
print "6. {}".format(string_sum(144, 24))
print "7. {}".format(string_sum(144, -45))
print "8. {}".format(string_mul(144, 11))
print "9. {}".format(string_div(144, 70))
"""I think that the spacing makes it easier to read"""
| true |
0437d19e719d4ae83939d6f2507f95290ff8ee46 | OneTesseractInMultiverse/python-class-group-1 | /s-clase2/variables.py | 771 | 4.1875 | 4 | print("Hola, esto es una clase sobre variables en Python")
print("-----------------------------------------")
# Esto es un comentario de una sola línea
"""
A continuación vamos a crear un programa que nos permite
calcular un discriminante. El discriminante se puede
calcular de la siguente manera:
dicriminante = (bˆ2) - 4(a)(c)
"""
# primero declaramos las variable a, b, c
a = 1
b = 8
c = 5
#(xˆ2) + 8x + 5
# ahora calculamos el discriminanto usando
# la formula anterior y los operadores
# aritméticos
discriminante = (b ** 2) - 4*a*c
print("El discriminante es: " + str(discriminante))
print("------------------------------------------")
numero_por_verificar = 122
es_par = (numero_por_verificar % 2) == (0)
print("El número es par: " + str(es_par)) | false |
dcecd97b65c9cffa90b45aa04186619d0b8f791e | Cherchercher/magic | /answers/flatten_array.py | 407 | 4.46875 | 4 | def flatten_array_recursive(a):
"""
recursively flattened nested array of integers
Args:
a: array to flatten which each element is either an integer or a (nested) list of integers
Returns:
flattened array
"""
result = []
for i in a:
if type(i) == list:
result += flatten_array_recursive(i)
else:
result.append(i)
return result
| true |
5b60b8daede4884824ec4652dd1e35b1099b18a5 | league-python-student/level0-module1-RedHawk1967 | /_03_if_else/_5_shape_selector/shape_selector.py | 1,083 | 4.40625 | 4 | import turtle
from tkinter import messagebox, simpledialog, Tk
# Goal: Write a Python program that asks the user whether they want to
# draw a triangle, square, or circle and then draw that shape.
if __name__ == '__main__':
window = Tk()
window.withdraw()
# Make a new turtle
my_turtle = turtle.Turtle()
# Ask the user what shape they want to draw and store it in a variable
shape = simpledialog.askstring(title="",prompt="Enter a common shape")
# Draw the shape requested by the user using if-elif-else statements
if shape == "circle":
for i in range(360):
my_turtle.forward(1)
my_turtle.right(1)
if shape == "square":
for i in range(4):
my_turtle.forward(90)
my_turtle.right(90)
if shape == "rhombus":
for i in range(2):
my_turtle.right(45)
my_turtle.forward(50)
my_turtle.right(135)
my_turtle.forward(50)
# Call the turtle .done() method
window.mainloop() | true |
cd52330ace48dffaf87384d281d9585b82fa2172 | AK-171261/python-datastructures-programs | /sort_dict.py | 996 | 4.3125 | 4 | '''
Ways to sort list of dictionaries by values in Python – Using lambda function/Using itemgetter
'''
lis = [{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]
# Method-1
for obj in sorted(lis, key=lambda x: (x["age"], x["name"])):
print(obj)
# {'name': 'Nikhil', 'age': 19}
# {'name': 'Manjeet', 'age': 20}
# {'name': 'Nandini', 'age': 20}
# Method-2
res = sorted(lis, key=lambda x: (x["age"], x["name"]))
print(res)
# [{'name': 'Nikhil', 'age': 19}, {'name': 'Manjeet', 'age': 20}, {'name': 'Nandini', 'age': 20}]
# Method-3
from operator import itemgetter
res = sorted(lis, key=itemgetter('age', 'name'), reverse=True)
print(res)
# [{'name': 'Nandini', 'age': 20}, {'name': 'Manjeet', 'age': 20}, {'name': 'Nikhil', 'age': 19}]
'''
Ways to sort dictionaries by values in Python – Using lambda function
'''
dict1 = {1: 1, 2: 9, 3: 4}
res = sorted(dict1.items(), key=lambda x: x[1])
print(res)
# [(1, 1), (3, 4), (2, 9)]
| false |
436a5a72ec807c80d379373be7f619e982a7f663 | edufreitas-ds/Datacamp | /01 - Introduction to Python/03 - NumPy/12 - Average versus median_adapted.py | 1,142 | 4.1875 | 4 | """
You now know how to use numpy functions to get a better feeling for your data. It basically comes down to importing
numpy and then calling several simple functions on the numpy arrays:
import numpy as np
x = [1, 4, 8, 10, 12]
np.mean(x)
np.median(x)
The baseball data is available as a 2D numpy array with 3 columns (height, weight, age) and 1015 rows.
The name of this numpy array is np_baseball. After restructuring the data, however, you notice that some height values
are abnormally high. Follow the instructions and discover which summary statistic is best suited if you're dealing with
so-called outliers.
"""
import numpy as np
height = np.round(np.random.normal(1.75, 0.20, 5000), 2)
weight = np.round(np.random.normal(60.32, 15, 5000), 2)
age = np.round(np.random.normal(20, 5, 5000), 0)
np_baseball = np.column_stack((height, weight, age))
# Create numpy array np_height_in that is equal to first column of np_baseball.
np_height_in = np_baseball[:, 0]
# Print out the mean of np_height_in.
print(np.mean(np_height_in))
# Print out the median of np_height_in.
print(np.median(np_height_in)) | true |
1a719ddedba620ec08f18633c1730f50cfc3d0e9 | the-carpnter/algorithms | /towers_of_hanoi.py | 565 | 4.1875 | 4 | def hanoi(n, rod0, rod1, rod2):
# This is the base case, we just have to move the 1 remaining plate to the target plate
if n == 1:
print('Plate 1 from {} to {}'.format(rod0, rod2))
return
# We have to first move n-1 plates to the auxiliary rod
hanoi(n-1, rod0, rod2, rod1)
# Moving the largest plate from first rod to the target rod
print('Plate {} from {} to {}'.format(n, rod0, rod2))
# Placing n-1 rods on top of the largest rod
hanoi(n-1, rod1, rod0, rod2)
if __name__ == '__main__':
hanoi(3, 'A', 'B', 'C')
| true |
c81a139f48b30116760c3710f5778fedcac40def | gmoore016/Project_Euler | /Complete/Problem009.py | 1,306 | 4.25 | 4 | """
Gideon Moore
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def main():
# Solutions are defined by pairs of a and b since the pair
# defines only one possible value for c
# a is defined to be less than b
# Given a < b < c, a < 333; if a = 333, b + c = 667
# If this is so, c >= 334 as c > b, but this means b <= 333
# This implies b == a, which is a contradiction. Thus, a < 333.
#
# Further, a is a natural number, so a >= 1
for a in range(1, 333):
# As b is greater than a, we can start with a + 1
#
# Further, as b < c, we know b < 1000 - 2a
# This is because a + b + c = 1000 -> b = 1000 - a - c
# -> b < 1000 - 2a since a < c
for b in range(a + 1, 1000 - 2 * a):
# An (a, b) pair allow only one possible c
c = 1000 - a - b
# If a2 + b2 = c2, then we're done!
if a * a + b * b == c * c:
# Find product as desired by prompt
product = a * b * c
print(a, b, c)
print(product)
return product
main()
| true |
7e46412e2ebbc5927203136c852039fb3067da7e | ofhellsfire/python-notes | /lectures/02-intermediate/06-iterables-iteration/example/multiply_table.py | 642 | 4.28125 | 4 | # Nested Comprehension Example
TABLE_SEPARATOR = '|'
FORMAT = f'{TABLE_SEPARATOR} {{:>2}} '
def get_table_length(table, frmt):
return len([rows for rows in table]) * len(frmt.format('')) + 1
def print_row_separator(length, sep='-'):
print(sep * length)
def main():
mul_table = [[x * y for x in range(1,10)] for y in range(1,10)]
table_len = get_table_length(mul_table, FORMAT)
for row in mul_table:
print_row_separator(table_len)
for col in row:
print(FORMAT.format(col), end='')
print(TABLE_SEPARATOR)
print_row_separator(table_len)
if __name__ == '__main__':
main()
| false |
2d5f0fa53d224128c6c6730cbd317decf614f72a | yashlad27/MAC-Python-basics-Jun21 | /Tuples01.py | 1,165 | 4.6875 | 5 | # TUPLE: it is a collection which is ordered and unchangeable
# tuples are written with round brackets
thisTuple = ("apple", "banana", "cherry")
print(thisTuple)
# 1. tuple items are ordered, unchangeable, and allow duplicate values
# first item has index [0] and the second item has index [1]
# 2. tuples have a defined order and that order cannot be changed
# 3. tuples are unchangeable, we cannot add or remove items after the tuple has been created
# 4. Allow Duplicates:
# tuples are indexed, they can have items with the same value
Tuple1 = ("apple", "banana", "cherry", "apple", "cherry")
print(Tuple1)
# Tuple Length:
Tuple2 = ('horse', 'dog', 'rabbit')
print(len(Tuple2))
# Create a Tuple with one item:
# You have to add a comma after the item, otherwise python will not recognise it as a tuple
Tuple3 = ('apple',)
print(type(Tuple3))
# Tuple Items - Data Types:
T1 = ('apple', 'banana', 'cherry') # tuple made of strings
T2 = (1, 3, 5, 9, 2, 3) # tuple made of integers
T3 = (True, False) # tuple made of booleans
MixedTuple = ('mango', True, 123, False, 4.55)
# Tuple type() :
mytuple = ('apple', 'uganda', 'Strawberry')
print(type(mytuple)) | true |
75b576265e6714bc87460fadd1891797cc5bbcad | yashlad27/MAC-Python-basics-Jun21 | /tupleUnpack.py | 896 | 4.75 | 5 | # UNPACKING A TUPLE:
# When we creat a tuple, we normally assign values to it. This is called "packing" tuple.
fruitsT = ("apple", "cherry", "orange")
# but in Python we are allowed to extract the values back into variables.
# this is called unpacking
(green, yellow, red) = fruitsT
print(green)
print(yellow)
print(red)
# USING ASTERISK *
# if the number of var is less than the number if values, you can add an * to the variable name and t
# the values will be assigned to the variables list:
fruitsT1 = ("apple", "orange", "horse", "dog", "rasberry", "chicken")
(fawn, violet, *magenta) = fruitsT1
print(fawn)
print(violet)
print(magenta)
# if the asterisk is added to another variable name than the last, python will assign values to the variable
# until the number of values left matches the number of variables left
(fawn, *violet, magenta) = fruitsT1
print(fawn, violet, magenta)
| true |
5c96164b29472c96a0ba028c64f5e21cdeeea9c8 | yang1127/school-test | /数据管理与方法/用户.py | 292 | 4.15625 | 4 | name = input("请输入您的姓名:")
gender = input("请输入您的性别:")
age = input("请输入您的年龄:")
# 通过字典设置参数
dic = {"name":name, "gender":gender, "age":age}
print("您的姓名是: {}, {}, 年龄{}岁".format(dic["name"], dic["gender"], dic["age"]))
| false |
c6518e553b8f94585b1fe98f6b82f70ea450d88f | duanwandao/PythonBaseExercise | /Day02(分支及循环)/Test04.py | 1,115 | 4.3125 | 4 | """
分支:
单分支
if 表达式:
表达式成立执行的代码...
双分支
多分支
分支的嵌套
循环:
while
语法:
while 表达式:
表达式成立执行的代码...
迭代(趋向终止)
for
"""
# 将HelloWorld输出10遍
# print('HelloWorld\n'*10)
# i = 0
# while i < 10:
# print("HelloWorld i = %d"%i)
# i = i + 1
# i = 1
# while i <= 100:
# print('i = %d'%i)
# # i = i+1
# i += 1
# 求 1 + 2 + 3 + .....+ 100的和
# sum = 0 sum += 1 sum += 2 sum += 3...sum += 100
# j = 1
# # 用来记录总和
# sum = 0
# while j <= 101:
# sum += j
# j += 1
# print("和为:%d"%sum)
import random
i = 0
while i < 10:
cmp_num = random.randint(0, 2)
print("计算机准备完毕")
your_num = int(input("该你了 0:石头 1:剪刀 2:布\n"))
if (your_num == 0 and cmp_num == 1) or (your_num == 1 and cmp_num == 2) or (your_num == 2 and cmp_num == 0):
print("你赢了")
elif your_num == cmp_num:
print("平局")
else:
print("你输了")
i += 1
| false |
b4f462b12b36781b009255fed1f4274cddee6217 | duanwandao/PythonBaseExercise | /Day11(面向对象3)/Test06.py | 419 | 4.28125 | 4 | """
多继承中属性的处理:
"""
class A():
def __init__(self,a,aa):
self.a = a
self.aa = aa
class B():
def __init__(self,b):
self.b = b
class C(A,B):
def __init__(self,a,b,c):
super().__init__(a,b)
self.c = c
#
# c = C(1,2)
# print(c.a)
# print(c.aa)
# print(c.b)
c = C(1,2,3)
# print(c.a)
print(c.a)
print(c.aa)
print(c.c)
print(C.mro())
print(C.__mro__) | false |
6ff16bbe8fd5433d4d4287801962ee7b036982fd | duanwandao/PythonBaseExercise | /Day13(异常及模块的使用)/Test06.py | 894 | 4.1875 | 4 | """
1.包是什么?
包:(文件夹)
package
python3中可以不使用__init__.py模块
__init__.py 初始化
python2中一定要有
2.如何创建一个包
new->package
直接创建一个文件夹
3.包的作用
1.方便管理
2.不同的包中,允许存在同名类
4.如何引入指定包中的指定模块
import package1.Test00
from package1.Test00 import *
引入某个包中的任何一个模块,该包中的__init__.py会先执行
在init中一般执行导入当前包里的其他模块
"""
# import package1.Test00
# print(package1.Test00.PI)
# from package1.Test00 import *
# import package1
# print(package1.Test00.PI)
# from package2 import Test00
# from package1 import Test00
# print(Test00.PI)
#使用以下两种方式:
# from package1 import *
# print(PI)
import package1
print(package1.PI)
| false |
80fd335569f5cd677e7cc9968fd6a39a04c8e291 | duanwandao/PythonBaseExercise | /Day09(面向对象1)/Test05.py | 685 | 4.28125 | 4 | """
创建对象,拥有默认属性:
__init__()方法的使用
"""
class Driver():
#增加一个方法
def __init__(self,id,name):
print("我是init方法")
# 给自己加属性
self.id = id
self.name = name
def drive_car(self):
print("工号:%d %s为您服务"%(self.id,self.name))
print("1、踩离合")
print("2、打火")
print("3、挂档")
print("4、松离合给油")
print("滴滴滴,一起去嗨皮")
# 创建对象
driver1 = Driver(1001,'黄师傅')
# 2.让对象开车走 调用对象的方法
driver1.drive_car()
driver2 = Driver(1002,'于师傅')
driver2.drive_car()
| false |
3acfc2b29d25fc139abe71e875c8baef909c90af | duanwandao/PythonBaseExercise | /Day12(设计模式及异常处理)/Test03.py | 838 | 4.28125 | 4 | """
设计模式:
单例模式:
全局对象唯一
__new__()
作用: 分配内存空间
__init__()
作用: 初始化
初始化唯一性
"""
class Data():
#定义一个私有的类属性
__single = None
def __new__(cls, *args, **kwargs):
print("new方法")
if cls.__single == None:
cls.__single = super().__new__(cls)
return cls.__single
def __init__(self):
# self.data = list()
print("init方法")
self.students = []
# def saveData(stu):
# data = Data()
# data.students.append(stu)
# def showData():
# data = Data()
# print("qqq")
# for stu in data.students:
# print(stu)
data1 = Data()
data2 = Data()
data3 = Data()
#id(对象)
print(id(data1))
print(id(data2))
print(id(data3)) | false |
94583feac92b4d55a2b1be598de7aadebc4a7276 | duanwandao/PythonBaseExercise | /Day07(递归及文件处理)/Test05.py | 1,187 | 4.375 | 4 | """
匿名函数
关键字
lambda
lambda 参数...: 表达式
注意:
1.匿名函数中可以存在0,1,多个参数
2.匿名函数中不能存在return语句
3.匿名函数运算完之后,只能得到一个值(返回值)
思考:
一般函数可以存在几个返回值?
一个还是多个?
返回值可以存在1个或者多个
如果函数返回多个值,接受的方式有两种:1. 只有一个接受 2.个数匹配
"""
def get_sum(a,b):
return a + b
# test = lambda :print("哈哈哈")
#匿名函数中不能存在return关键字
# test = lambda :return 1
#
# get_sum1 = lambda a,b:a + b
# print(type(get_sum1))
# print(get_sum1)
#
# print(get_sum(10,20))
# print(get_sum1(10,20))
# # test()
#测试多个返回值的问题
# def testReturnValue():
# return 1,2
#
# result = testReturnValue()
# print(type(result))
# print(result)
# v1,v2 = testReturnValue()
# print(type(v1))
# print(type(v2))
# print(v1,v2)
def testReturnValue1():
return 1,2,3
a,b,c = testReturnValue1()
print(type(a))
print(type(b))
print(a)
print(b)
print(lambda x,y:x**y)
print(get_sum)
str | false |
c38533f21096e3481670b9da2aa42525c648b59a | duanwandao/PythonBaseExercise | /Day19(高级特性)/Test05.py | 699 | 4.3125 | 4 | """
一个函数拥有多个装饰器的问题:
装饰器用来装饰函数
如果一个函数有多个装饰器,那么,装饰顺序取决于离函数的远近距离(近的先装)
《》
"""
def add_out1(func):
print("装饰器开始装饰1")
def add_in1():
return '《' + func() + "》"
return add_in1
def add_out2(func):
print("装饰器开始装饰2")
def add_in2():
return '*' + func() + "*"
return add_in2
@add_out1
#book_name = add_out1(book_name)
@add_out2
#book_name = add_out2(book_name)
def book_name():
return '7个男人与1个女人的故事'
# book_name = add_out1(book_name)
# print(book_name())
print(book_name()) | false |
ebf86e745c08079f18e418c017f5015c4f3bc051 | duanwandao/PythonBaseExercise | /Day10(面向对象2)/Test03.py | 2,253 | 4.1875 | 4 | """
练习:
面向对象的封装练习:
回合制游戏:
大话西游、梦幻西游、问道...
角色:
Hero:
属性:
名字、生命值、伤害值(浮动随机值)
方法:
攻击方法
Boss:
属性:
名字、生命值、伤害值(浮动)
方法:
攻击方法
Hero
Boss
while True:
if Hero.活着:
Hero.攻击(Boss)
if Boss.生命值 <= 0:
print(“You Win”)
break
if Boss.没挂:
Boss.反击(Hero)
if Hero.生命值 <= 0:
print(“Boss Win”)
break
"""
import random
import time
class Hero():
def __init__(self,name,hp,damage):
self.name = name
self.hp = hp
self.damage = damage
#英雄攻击boss的方法,boss做参数,传进来
def attack_boss(self,boss):
# 伤害值增加随机浮动伤害值
rand_damge = random.randint(1,99)
boss.hp -= (self.damage+rand_damge)
print("英雄:%s 攻击Boss:%s 伤害值:%d Boss剩余生命值:%d"
%(self.name,boss.name,self.damage+rand_damge,boss.hp))
class Boss():
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
# 英雄攻击boss的方法,boss做参数,传进来
def attack_hero(self, hero):
rand_damge = random.randint(1, 35)
hero.hp -= (self.damage+rand_damge)
print("Boss:%s 攻击英雄:%s 伤害值:%d 英雄剩余生命值:%d"
% (self.name, hero.name, self.damage+rand_damge, hero.hp))
count = 1
#创建英雄
hero1 = Hero('至尊宝',1000,20)
#创建Boss
boss1 = Boss('白晶晶',3000,5)
while True:
print("------------------【round%d】-----------------"%count)
if hero1.hp > 0:
hero1.attack_boss(boss1)
if boss1.hp <= 0:
print("至尊宝获胜")
break
if boss1.hp > 0:
boss1.attack_hero(hero1)
if hero1.hp <= 0:
print("晶晶获胜")
break
count += 1
time.sleep(0.8)
print('\n'*5) | false |
fa2728ce4877a73cfd46ad3dbc1ab76aba2cce5c | khabib-habib/week3 | /exercises.py | 294 | 4.15625 | 4 | phrase = input("Enter the phrase: ")
# return the vowels used in the phrase
vowels = ['e', 'u', 'i', 'o', 'a']
result = []
for letter in phrase:
if letter in vowels:
result.append(letter)
print(result)
print("".join(result))
result2 = {'e':0, 'u':0, 'i':0, 'o':0, 'a':0}
| true |
71761cf997e5ddb9fbb89a5a7e5d72906461dcb3 | mehul-clou/turtle_race | /main.py | 1,130 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_guess= screen.textinput(title="Make your bet", prompt="Which Turtle Will Win the race? Enter a race")
print(user_guess)
color = ["red", "yellow", "green", "orange", "brown", "pink", "blue"]
y_position= [-70, -40, -10, 20, 50, 80]
all_turtle = []
for turtle_index in range(6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.color(color[turtle_index])
new_turtle.goto(x=-240, y=y_position[turtle_index])
all_turtle.append(new_turtle)
if user_guess:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() >= 220:
winning_color = turtle.pencolor()
if winning_color == user_guess:
print(f"you are win ! The {winning_color} turtle is win the race")
else:
print(f"you lose! The {winning_color} turtle win is winner")
is_race_on = False
rand_distance = random.randint(1,10)
turtle.forward(rand_distance)
screen.exitonclick()
| true |
53eac1a63bbd7eae0395d4320c0d4e521aa3cd5c | lotlordx/CodeGroffPy | /type_conversion_exception_handling.py | 764 | 4.21875 | 4 | def divide_numbers(numerator, denominator):
"""For this exercise you can assume numerator and denominator are of type
int/str/float.
Try to convert numerator and denominator to int types, if that raises a
ValueError reraise it. Following do the division and return the result.
However if denominator is 0 catch the corresponding exception Python
throws (cannot divide by 0), and return 0"""
try:
num = int(numerator)
dim = int(denominator)
try:
division = num / dim
return division
except:
return ZeroDivisionError('division by zeros')
except:
raise ValueError("Values passed can't be converted to an interger")
print(divide_numbers(4, 0)) | true |
1afba2447fa497eae562f3edde3f9bce1aecef15 | MDCGP105-1718/portfolio-s189385 | /xp11.py | 291 | 4.21875 | 4 | low_value = int(input("please input the lowest value"))
high_value = int(input("please input the highest value"))
for i in range(low_value,high_value):
if i % 3 == 0 and i % 5 == 0:
print("FIZZBUZZ")
elif i % 3 == 0:
print("FIZZ")
elif i % 5 == 0:
print("BUZZ")
else:
print(i)
| false |
147d74d2301bf83acae626f93d0ade6d920c7eb5 | Bivekrauniyar/my-calculator | /main.py | 445 | 4.125 | 4 | print("welcome to my calculator\n made by bivek" )
print("enter your operator",
"+","-","*","/","%")
n1=input()
print("enter first number")
n2=input()
print("enter second number")
n3=input()
if n1=="+":
print(int(n2)+int(n3))
elif n1=="-":
print(int(n2)-int(n3))
elif n1=="*":
print(int(n2)*int(n3))
elif n1=="/":
print(int(n2)/int(n3))
elif n1=="%":
print(int(n2)%int(n3))
print("thanks")
| false |
3c532b716e5c8f9616e9ee644dca1269f1aecafc | davidebuglione/esercizi-in-classe | /esercizio_31.py | 552 | 4.25 | 4 | numero_decimale=int(input("inserire il numero decimale che si desidera trasformare in binario"))
funzione_python=bin(numero_decimale)
numeri_binari=[]
numeri_binari.append(numero_decimale%2)
while numero_decimale!=1:
numero_decimale//=2
resto=numero_decimale%2
numeri_binari.append(resto)
numeri_binari.reverse()
print("Il numero trasformato in binario è:")
for number in numeri_binari:
print(number,end="")
print(" per dimostrarti che il mio risultato è corretto ecco ciò che dice la funzione bin di python:")
print(funzione_python) | false |
bc0226c18442d8117ac9caae0070b818e987af74 | davidebuglione/esercizi-in-classe | /scheda_3.py | 725 | 4.125 | 4 | linguaggio_svizzero=input("inserire una parola o una frase in rovarspraket da tradurre")
lista_linguaggio_svizzero=[]
for lettera in linguaggio_svizzero:
lista_linguaggio_svizzero.append(lettera)
vocali=["a","e","i","o","u"]
for lettera2 in lista_linguaggio_svizzero:
index_consonante=lista_linguaggio_svizzero.index(lettera2)
if lettera2 not in vocali and lista_linguaggio_svizzero[index_consonante+1]=="o":
lista_linguaggio_svizzero.remove(lista_linguaggio_svizzero[index_consonante+1])
lista_linguaggio_svizzero.remove(lista_linguaggio_svizzero[index_consonante])
print("la parola o frase tradotta è:")
for lettera3 in lista_linguaggio_svizzero:
print(lettera3,end="")
print() | false |
fc58262858ac1531f14a0dda380c02c7d48d431a | muremwa/Simple-Python-Exercises | /exercise_6C_text_processing.py | 1,644 | 4.125 | 4 | # Q6c) Find the maximum nested depth of curly braces
#
# Unbalanced or wrongly ordered braces should return -1
#
# Iterating over input string is one way to solve this, another is to use regular expressions
import re
def max_nested_braces(string_):
braces = []
nesting = 0
# eliminate empty braces
if re.search(r'{}', string_):
return -1
for char in string_:
if char == '{' or char == '}':
braces.append(char)
# unbalanced eliminated
if len(braces) % 2 != 0:
return -1
# wrongly ordered eliminated
half = braces[:int(len(braces)/2)]
if half.count('}') > half.count('{'):
return -1
# try to follow this logic
total_ride = len(braces) / 2 # the total distance of the list 'braces' we shall travel
ball_gum = 0
while total_ride > 0:
char = braces[ball_gum]
ball_gum += 1
if char == '{':
# if it's an opening curly brace increment nesting depth
nesting += 1
# total ride decremented only when it's a '{'
total_ride -= 1
elif char == '}':
# if it closes decrement depth by 1 and leave total ride the same!
nesting -= 1
return nesting
print(max_nested_braces('a*b'))
# 0
print(max_nested_braces('{a+2}*{b+c}'))
# 1
print(max_nested_braces('{{a+2}*{{b+{c*d}}+e*d}}'))
# 4
print(max_nested_braces('a*b+{}'))
# 1
print(max_nested_braces('}a+b{'))
# -1
print(max_nested_braces('a*b{'))
# -1
# bonus: empty braces, i.e {} should return -1
print(max_nested_braces('a*b+{}'))
# -1
print(max_nested_braces('a*{b+{}+c*{e*3.14}}'))
# -1
| true |
a08b1d9406425a7a7955eea2ba2160a58cd5ffe9 | muremwa/Simple-Python-Exercises | /exercise_1_variables_and_print.py | 506 | 4.28125 | 4 | # Ask user information, for ex: name, department, college etc and display them using print function
def main():
name = input('Enter your name: ')
college = input('Enter your college: ')
department = input('Enter your department: ')
print('\n')
print('-'*35)
print('Name' + ' '*(len('department')-len('name')), ': ', name)
print('College' + ' '*(len('department') - len('college')), ': ', college)
print('Department : ', department)
if __name__ == '__main__':
main()
| false |
932bae627c6a763a94ab7822ad3b7c1edf668a95 | VartikaPandey1303/first_repository | /if_1.py | 515 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 13 17:03:41 2019
@author: user
"""
#grades to be printed
day=int(input('enter a digit between 1 to 7 '))
if (day==1):
print('It is monday')
elif (day==2):
print('It is tuesday')
elif (day==3):
print('It is wednesday')
elif (day==4):
print('It is thursday')
elif (day==5):
print('It is friday')
elif (day==6):
print('It is saturday')
elif (day==7):
print('It is sunday')
else:
print('error') | false |
7728d8b1f32f2c697b3a9a72bc219c7481f5df6c | Abdirahman136896/python | /areaofcircle.py | 267 | 4.4375 | 4 | #Write a Python program which accepts the radius of a circle from the user and compute the area.
import math
radius = int(input("Enter the radius of the circle: "))
x= math.pi
#area = ((22/7) * pow(radius, 2))
area = (math.pi * pow(radius, 2))
print(area) | true |
df4ee5f6f227c883f6ee5295bebab3ccb0fafb57 | Abdirahman136896/python | /tuples.py | 418 | 4.21875 | 4 | #create tuple
coordinates = (4,5)
#prints all the values in the tuple
print(coordinates)
#prints values of the tuple at a specific index
print(coordinates[0])
print(coordinates[1])
#coordinates[1] = 6 returns an error tuple object not supporting assignment because tuples are immutable
list_coordinates = [(4,5),(6,7),(8,9)]
print(list_coordinates)
list_coordinates.insert(0,(0,1))
print(list_coordinates)
| true |
d68b9d4137ae3b1c74c5dea1fa34d4f9527a857c | jeneferjene/guvi_set1 | /odd.py | 248 | 4.15625 | 4 | ch = input("")
if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
print("invalid")
elif(ch >= '0' and ch <= '9'):
num=int(ch)
if (num % 2) == 0:
print("Even")
else:
print("Odd")
else:
print("invalid")
| false |
8b2f89d9739db319d3744bc3388829240417d3a1 | badlydrawnrob/python-playground | /anki/unused/bitwise.py | 1,032 | 4.34375 | 4 | '''
Bitwise | Introduction to bitwise operators
'''
print(5 >> 4) # Right Shift
print(5 << 1) # Left Shift
print(8 & 5) # Bitwise AND
print(9 | 4) # Bitwise OR
print(12 ^ 42) # Bitwise XOR
print(~88) # Bitwise NOT
# Numbers
# =======
# 8's bit 4's bit 2's bit 1's bit
# 1 0 1 0
# 8 + 0 + 2 + 0 = 10
print(0b1), # 1
print(0b10), # 2
print(0b11), # 3
print(0b100), # 4
print(0b101), # 5
print(0b110), # 6
print(0b111) # 7
print("******")
print(0b1 + 0b11)
print(0b11 * 0b11)
# The bits go up like so
# ======================
# | 2**0 | = 1 |
# | 2**1 | = 2 |
# | 2**2 | = 4 |
# | 2**3 | = 8 |
# | 2**4 | = 16 |
# | 2**5 | = 32 |
# | 2**6 | = 64 |
# | 2**7 | = 128 |
# | 2**8 | = 256 |
# | 2**9 | = 512 |
# | 2**10 | = 1024 |
a = 0b11101110
mask = 0b00010001
desired = a ^ mask
print(bin(desired))
# < 1
#
# 0 b 1 0 1
# 0 b 1 0 0 0 0 0 0 1 0
# - - - - - - - - - - - -
# 10 9 8 7 6 5 4 3 2 1
| false |
e3ab63a25d5169348149a7749270a1311e54342a | badlydrawnrob/python-playground | /anki/added/lists/indexes-06.py | 1,092 | 4.625 | 5 | #
# Indexes: Sort
# - List Capabilities and Functions (9)
## sort() method
################
animals = ["cat", "ant", "bat"]
animals.sort()
for animal in animals:
print animal
#### Q: What is `sort()` doing here?
#### - Explain what it defaults to (alphabetical)
#### - Note that .sort() modifies the list rather than returning a new list.
#### Q: Explain what we're doing in the `for` loop
## sort() v2
#############
# This is a little more complex, and includes a list and an empty list:
start_list = [5, 3, 1, 2, 4]
square_list = []
# Run the loop
for list in start_list:
list = list**2
square_list.append(list)
square_list.sort()
print square_list
#### Q: Explain how we create an empty list
#### Q: Explain what we're doing in the `for` loop
# - run through each item in `start_list`
# - create a new variable and calculate each `start_list` item
# by multiplying it: list*list (list to the power 2)
# - Append each newly created calculation to the empty `square_list`
#### Q: Explain again what `.sort()` does
#### Q: What will `print square_list` return?
| true |
a6d79d3a25e37f8ccaff2e47536d41a1ddbc0e86 | badlydrawnrob/python-playground | /flask-rest-api/05/tests/user_01.py | 2,014 | 4.15625 | 4 | '''
We're allowing the user class to interact
with sqlite, creating user mappings (similar
to the functions we created in `security.py`
`usename_mapping`, `userid_mapping`)
'''
import sqlite3
class User(object):
def __init__(self, _id, username, password):
self.id = _id
self.username = username
self.password = password
# Find user by username in database
# - Make this a class method as it's not an
# instance method
@classmethod
def find_by_username(cls, username):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
# Setup the query with a placeholder
query = "SELECT * FROM users WHERE username=?"
# Store the result
# - using a single tuple, 'username'
# - MUST be a tuple
result = cursor.execute(query, (username,))
# Return the first row out of
# `result` set
# -
row = result.fetchone()
# `row` will return `None` if no `result`
# so we need to check if exists
if row:
# 1. Instead of hardcoding the Class
# - User(row[0] ...
# We can use `cls` (Python convention)
#
# 2. Instead of row[0], row[1], row[2]
# - we can unpack the tuple `*row`
user = cls(*row)
else:
user = None
connection.close()
return user
# Create a class method exactly the same
# as the one above, but for the ID
# - Remember, we're using `_id` with an
# underscore to avoid naming conflicts with Python
@classmethod
def find_by_id(cls, _id):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query = "SELECT * FROM users WHERE id=?"
result = cursor.execute(query, (_id,))
row = result.fetchone()
if row:
user = cls(*row)
else:
user = None
connection.close()
return user
| true |
d6f82c716dbfd073f594b06f26dafed1cfdd440d | liyi54/python-refresher | /Functions.py | 2,556 | 4.25 | 4 | # import turtle
#
# __import__("turtle").__traceable__ = False
#
#
# # def draw_square(name, size):
# """This function draws a simple square of a given size"""
# # for i in range(4):
# # name.forward(size)
# # name.left(90)
#
#
# def draw_mult_square(name, size):
#
# """Make turtle name draw a multi-colored square of size"""
#
# for i in ["red", "blue", "orange", "hotpink"]:
# name.color(i)
# name.forward(size)
# name.left(90)
#
#
# name = input("What is the name of your Turtle?: ")
#
# size = int(input("What is the size of your square?: "))
#
# wn = turtle.Screen()
# wn.title(name+" meets a function")
# wn.bgcolor("lightgreen")
#
# name = turtle.Turtle()
# name.pensize(3)
#
# for j in range(15):
# draw_mult_square(name, size)
# size += 10
# name.forward(10)
# name.right(18)
#
# wn.mainloop()
#
# # name.color("blue")
# #
# # draw_square(name, size)
#
# wn.mainloop()
import turtle
# def compound_interest(p,r,n,t):
# """This function calculates compound interest"""
# answer = p*((1+r/n)**(n*t))
# return answer
#
#
# rate = 0.15
# times = 1
# toInvest = float(input("How much do you want to invest?: "))
# years = int(input("For how many years do you want to invest your money?: "))
#
# result = compound_interest(toInvest, rate, times, years)
#
# print("After ", str(years), " years, you will have ", str(round(result,2)), " Naira" )
def make_window(color, title):
wn = turtle.Screen()
wn.bgcolor(color)
wn.title(title)
# wn.mainloop()
return wn
def make_turtle(size, color, speed):
newTurtle = turtle.Turtle()
newTurtle.color(color)
newTurtle.shape("turtle")
newTurtle.pensize(int(size))
newTurtle.speed(speed)
newTurtle.forward(100)
return newTurtle
make_window("lightgreen","New Turtle")
alex = make_turtle(5,"blue",1)
# alex.forward(100)
#
# def make_window(colr, ttle):
# """
# Set up the window with the given background color and title.
# Returns the new window.
# """
# w = turtle.Screen()
# w.bgcolor(colr)
# w.title(ttle)
# # w.mainloop()
# return w
#
#
# def make_turtle(colr, sz):
# """
# Set up a turtle with the given color and pensize.
# Returns the new turtle.
# """
# t = turtle.Turtle()
# t.color(colr)
# t.pensize(sz)
# return t
#
#
# wn = make_window("lightgreen", "Tess and Alex dancing")
# tess = make_turtle("hotpink", 5)
# tess.forward(10)
# alex = make_turtle("black", 1)
# dave = make_turtle("yellow", 2) | false |
954e6f9ab4770826ad54bc799a054515b8ea85e2 | HashtagPradeep/python_practice | /control_flow_assignment/Assignment- Control Flow_Pradeep.py | 886 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ---
# ---
#
# <center><h1>📍 📍 Assignment: Control Flow 📍 📍</h1></center>
#
# ---
#
# ***Take 3 inputs from the user***
#
# - **What is your Age?** (Answer will be an Intger value)
# - **Do you eat Pizza?** (Yes/No)
# - **Do you do exercise?** (Yes/No)
#
# #### `Write the if else condition for the given flow chart.`
#
# 
# In[17]:
# What is your Age?
Age=int(input('What\'s your age?'))
# In[11]:
# Do you eat Pizza?
pizza=input('Do you eat pizza?')
# In[5]:
# Do you do exercise?
exercise=input('Do you exercise? ')
# In[18]:
if Age<30:
if (pizza=='yes'):
print('1.unfit')
else: print('1.fit')
else:
if (exercise=='yes'):
print('2.fit')
else: print('2.unfit')
# In[ ]:
# In[ ]:
# In[ ]:
| true |
7f60171c06620157ee51f79e34750848b7ade127 | AlexandruGG/project-euler | /22.py | 1,190 | 4.15625 | 4 | # Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file?
from string import ascii_uppercase
from typing import List
def read_names_file(filename: str) -> List[str]:
with open(filename, 'r') as file:
names_List: List[str] = file.read().replace('"', '').split(',')
names_List.sort()
return names_List
def get_name_score(name: str) -> int:
return sum(ascii_uppercase.index(c) + 1 for c in name)
def calculate_total_score(filename: str) -> int:
names_list: List[str] = read_names_file(filename)
return sum(index * get_name_score(name) for index, name in enumerate(names_list, start=1))
print(f"Score Total: {calculate_total_score('22-names.txt')}")
| true |
49c35742888364656b980820e7278e1634aaf576 | BioGeek/euler | /problem014.py | 914 | 4.15625 | 4 | # The following iterative sequence is defined for the set of positive integers:
#
# n -> n/2 (n is even)
# n -> 3n + 1 (n is odd)
#
# Using the rule above and starting with 13, we generate the following sequence:
#
# 13 40 20 10 5 16 8 4 2 1
#
# It can be seen that this sequence (starting at 13 and finishing at 1) contains
# 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
# that all starting numbers finish at 1.
#
# Which starting number, under one million, produces the longest chain?
def collatz(n):
"""generates iterative sequence (does not include the final 1)"""
while n != 1:
yield n
if not n%2:
n = n/2
else:
n = (3*n) + 1
print sorted([(i,len(list(collatz(i)))) for i in range(1,1000000)], key=lambda x: x[1])[-1][0]
# 837799
#
# real 0m47.068s
# user 0m37.220s
# sys 0m1.980s
| true |
c0d467d681edc97d6048ad6080f6ca57f7231bd7 | unaidelao/codewars-solutions | /8kyu/bin_to_decimal.py | 418 | 4.375 | 4 | # 8 kyu
# Bin to Decimal - Python
# Complete the function which converts a binary number (given as a string) to a decimal number.
def bin_to_decimal(inp):
return int(inp, 2)
print(bin_to_decimal("0")) # 0
print(bin_to_decimal("1")) # 1
print(bin_to_decimal("10")) # 2
print(bin_to_decimal("11")) # 3
print(bin_to_decimal("101010")) # 42
print(bin_to_decimal("1001001")) # 73
| false |
a30d28d0a0a0ab74bf73aae113bae31e1ae28bae | alf42pac/python1 | /less7_3.py | 807 | 4.15625 | 4 | # Lesson 7_3
class Cage:
def __init__(self, a):
self.a = a
def order(self, line):
return '\n'.join(['*' * line for i in range(self.a // line)]) + '\n' \
+ '*' * (self.a % line)
def __str__(self):
return self.a
def __add__(self, other):
return f'Сумма - {self.a + other.a}'
def __sub__(self, other):
return self.a - other.a if self.a - other.a > 0 else "Вычитание невозможно!"
def __mul__(self, other):
return f'Умножение - {self.a * other.a}'
def __truediv__(self, other):
return f'Деление - {round(self.a / other.a)}'
cage1 = Cage(33)
cage2 = Cage(44)
print(cage1 + cage2)
print(cage1 - cage2)
print(cage1 * cage2)
print(cage1 / cage2)
print(cage2.order(5))
| false |
ffa490bae900863d83963a5d68ef29a119852d71 | lukepeeler/lukepeeler.github.io | /docs/data_generator.py | 2,970 | 4.1875 | 4 | from graphics import *
from utility import *
import random
# Generates a random 2D points.
# meanX: mean of X-axis of the underlying normal distribution, type: int
# meanY: mean of Y-axis of the underlying normal distribution, type: int
# sigmaX: standard deviation on X-axis, type: int
# sigmaY: standard deviation on Y-axis, type: int
# RETURNS: x and y value of the random point, type: tuple containing two floats
def generatePoint(meanX, meanY, sigmaX, sigmaY):
x = random.gauss(meanX, sigmaX)
y = random.gauss(meanY, sigmaY)
xy = [x,y]
return (xy)
# Generates multiple random points using generatePoint() function.
# meanX: mean of X-axis of the underlying normal distribution, type: int
# meanY: mean of Y-axis of the underlying normal distribution, type: int
# sigmaX: standard deviation on X-axis, type: int
# sigmaY: standard deviation on Y-axis, type: int
# numPoints: how many number of points will be generated, type: int
# RETURNS: list of random points, type: list of tuples containing two floats
def generatePoints(meanX, meanY, sigmaX, sigmaY, numPoints):
rplist = []
for i in range(numPoints):
rplist.append(generatePoint(meanX, meanY, sigmaX, sigmaY))
return rplist
def main():
win = GraphWin("Data Collector", 500, 500)
# Ask user to click on window for meanX and meanY for blue samples
print("Click on window for meanX and meanY for blue samples")
point = win.getMouse()
meanX = point.getX()
meanY = point.getY()
# Ask user to input sigmaX and sigmaY for blue samples
sigmaX = eval(raw_input("Input sigmaX for blue samples: "))
sigmaY = eval(raw_input("Input sigmaY for blue samples: "))
# Ask user to input how many blue samples?
blue = eval(raw_input("Input number of blue samples: "))
# Generate blue samples with given information
bpoints = generatePoints(meanX, meanY, sigmaX, sigmaY, blue)
# Plot these blue samples on window using utility functions
plotPoints(bpoints, win, "Blue")
# Write these blue samples on blues.txt using utility functions
savePoints(bpoints, "blues.txt")
# Ask user to click on window for meanX and meanY for red samples
print("Click on window for meanX and meanY for red samples")
point = win.getMouse()
meanX = point.getX()
meanY = point.getY()
# Ask user to input sigmaX and sigmaY for red samples
sigmaX = eval(raw_input("Input sigmaX for red samples: "))
sigmaY = eval(raw_input("Input sigmaY for red samples: "))
# Ask user to input how many red samples?
red = eval(raw_input("Input number of red samples: "))
# Generate red samples with given information
rpoints = generatePoints(meanX, meanY, sigmaX, sigmaY, red)
# Plot these red samples on window using utility functions
plotPoints(rpoints, win, "Red")
# Write these red samples on reds.txt using utility functions
savePoints(rpoints, "reds.txt")
win.getMouse()
win.close()
main()
| true |
3e0644d2a2e4c28aa63219ce205d7d67d4af2130 | PickertJoe/algorithms-data_structures | /Chapter3_Basic_Data_Structures/palindrome_checker.py | 1,234 | 4.15625 | 4 | # A program to verify whether a given string is a palandrome - Miller and Ranum
from pythonds.basic import Deque
def main():
while True:
print("~~~Welcome to the Python Palindrome Checker!~~~")
palindrome = input("Please enter the string you'd like to test: ")
tester = palchecker(palindrome)
if tester is True:
print("Your input " + palindrome + " is a palindrome!")
else:
print("Your input " + palindrome + " is not a palindrome!")
repeat = input("Would you like to test another?(Y/N)")
if repeat.title() == 'Y':
pass
else:
break
def palchecker(aString):
chardeque = Deque()
for ch in aString:
# Removes all spaces from the user's input to ensure that palindrome is detected
if ch == ' ':
pass
else:
chardeque.addRear(ch)
stillEqual = True
while chardeque.size() > 1 and stillEqual:
first = chardeque.removeFront()
last = chardeque.removeRear()
# Ensures palindromes are detected regardless of user capitalization
if first.title() != last.title():
stillEqual = False
return stillEqual
main()
| true |
e2118826da7fd3917370b40d00f0c4199dbd93bd | PickertJoe/algorithms-data_structures | /Chapter5_Searching_Sorting/bubble_sort.py | 367 | 4.25 | 4 | # A simple function to perform a bubble sort algorithm to order a numeric list. Sourced from Miller & Ranum
def bubbleSort(alist):
for iteration in range(len(alist) - 1, 0, -1):
for i in range(iteration):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
| true |
10e1be03e36e97d938f05566b1e464a0d2e3890e | PickertJoe/algorithms-data_structures | /Chapter3_Basic_Data_Structures/unordered_list_test.py | 2,693 | 4.25 | 4 | # A program to test the function of the unordered list class
import unittest
from unordered_list import UnorderedList
class ULTestCase(unittest.TestCase):
"""Ensures proper functioning of unordered list methods"""
def test_UL_empty(self):
"""Ensures Unordered List returns correct boolean re: existance of contents"""
empty_list = UnorderedList()
self.assertEqual(True, empty_list.isEmpty())
def test_UL_add(self):
"""Ensures that add & search methods function properly"""
add_list = UnorderedList()
add_list.add(5)
self.assertEqual(True, add_list.search(5))
def test_UL_remove(self):
"""Ensures that remove method funcitons properly"""
remove_list = UnorderedList()
for number in range(0, 9):
remove_list.add(number)
self.assertEqual(False, remove_list.search(9))
def test_UL_length(self):
"""Ensures that length method functions properly"""
length_list = UnorderedList()
for number in range(0, 5):
length_list.add(1)
self.assertEqual(5, length_list.length())
def test_UL_pop(self):
"""Ensures that pop function works both with and without argument"""
pop_list = UnorderedList()
for number in range(1, 10):
pop_list.add(number)
self.assertEqual(1, pop_list.pop())
self.assertEqual(5, pop_list.pop(3))
def test_UL_index(self):
"""Ensures that index method works properly"""
index_list = UnorderedList()
for number in range(1, 10):
index_list.add(number)
self.assertEqual(3, index_list.index(4))
def test_UL_append(self):
"""Ensures that append and pop methods function properly"""
append_list = UnorderedList()
for number in range(1, 10):
append_list.add(number)
append_list.append(11)
self.assertEqual(11, append_list.pop())
def test_UL_insert(self):
"""Ensures that the insert method functions properly"""
insert_list = UnorderedList()
for number in range(1, 10):
insert_list.add(number)
insert_list.insert(12, 5)
self.assertEqual(12, insert_list.pop(6))
def test_UL_remove_notfound(self):
"""Ensures that the remove function can handle the situation in which a user requests to
remove a value that is not in the list
Message should print in addition to test pass/fail"""
rm_notfound_list = UnorderedList()
for number in range(0, 9):
rm_notfound_list.add(number)
self.assertEqual(False, rm_notfound_list.remove(15))
unittest.main()
| true |
bf2accb1d629c86bbd82f9f6ca7f7e1aa0cb550a | t6nesu00/python-mini-projects | /guessNumber.py | 739 | 4.1875 | 4 | # number guessing game
import random
guess = 0
computers_number = random.randint(0, 9)
print(computers_number)
condition = True
while condition:
user_guess = input("Guess the number (0-9) or exit: ")
if user_guess == "exit":
print("Hope to see you again.")
condition = False
elif computers_number == int(user_guess):
guess += 1
print("Congratulation! You guessed correct number in", guess, "tries.")
condition = False
elif computers_number < int(user_guess):
print("Too high!")
guess += 1
elif computers_number > int(user_guess):
print("Too low!")
guess += 1
else:
print("Sorry! Something went wrong.")
# created by Suman Nepali May, 2019
| true |
6f68500287c37a8c41121dba41b4ace190e8460c | cyxorenv/Test | /Numbers.py | 686 | 4.40625 | 4 | # In python there is three types of numbers:
# =----------------------------------------=
# 1) x = 1 int (Integer)
# 2) y = 1.1 float (a decimal point)
# 3) z = 1 + 2j (Complex numbers)
# Standart arithmetic in python - (and any outher programming languige).
# Addition
print(10 + 3)
# Sustruction
print(10 - 3)
# Multiplication
print(10 * 3)
# Division
print(10 / 3) # Here you get a float resaults
# 2nd Devision
print(10 // 3) # Here you get a int resaults.
# Mudulus
print(10 % 3) # The remainder of Devision.
# Exponent
print(10 ** 3) # 10 * 10 * 10 = 1000
# Augmented assignment operator.
# you can use all operation above.
x = 10
x += 3 # Same as (x = x + 3)
print(x)
| true |
e782dec2b7611e67f0c732cb21fc82c077d0f81f | rajiv25039/love-calculator | /main.py | 1,073 | 4.1875 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
combined_name = name1 + name2
combined_name_in_lower_case = combined_name.lower()
t = combined_name_in_lower_case.count("t")
r = combined_name_in_lower_case.count("r")
u = combined_name_in_lower_case.count("u")
e = combined_name_in_lower_case.count("e")
count_true = t + r + u + e
l = combined_name_in_lower_case.count("l")
o = combined_name_in_lower_case.count("o")
v = combined_name_in_lower_case.count("v")
e = combined_name_in_lower_case.count("e")
count_love = l + o + v + e
love_score = int(str(count_true) + str(count_love))
if love_score < 10 or love_score > 90:
print(f"Your love score is {love_score}, you go together like coke and mentos.")
elif love_score > 40 and love_score < 50:
print(f"Your love score is {love_score}, you are alright together.")
else:
print(f"Your love score is {love_score}.")
| true |
0b4e6205d0c646eb976e18ff1bbc97c52a018a5a | Takate/hangman | /hangman_0.1.py | 2,953 | 4.125 | 4 | import random
rerun = "Yes"
while rerun == "Yes" or "Y" or "yes" or "YES":
listOfWords = ["test"]
guessWord = random.choice(listOfWords)
guessWordList = list(guessWord)
#print(guessWordList)
letterIs = []
board = [" * " for char in guessWord]
difficulty = input("\n easy - 15 tries \n medium - 10 tries \n hard - 5 tries \n Please select difficulty: ")
if difficulty == "easy":
i = 15
print(" You choose easy difficulty!")
if difficulty == "medium":
i = 10
print(" You choose medium difficulty!")
if difficulty == "hard":
i = 5
print(" You choose hard difficulty!")
print("-" * 60)
print(" The word has {0} letters\n".format(len(guessWord)))
print(" "+" * " * len(guessWord))
print("-" * 60)
while i > 0:
print("\n You still have {0} lives!".format(i))
letter = input(" Please, insert a letter: ")
if len(letter) == 1:
if letter in guessWord and letter in letterIs:
print(" Sorry, you have already guessed the letter!")
print("-" * 60)
print(" " + board)
print("-" * 60)
print(" Already used words")
print("".join(letterIs))
if letter in guessWord and letter not in letterIs:
print(" You guessed the letter correctly!\n")
board = [char if char == letter or char in letterIs else " * " for char in guessWord]
#print(board)
if board == guessWordList:
print("_" * 60)
print("\n Congratulations! You guessed the word {0}!".format(guessWord))
print("_" * 60)
rerun = input("Wanna play again? (Yes/No): ")
if rerun == "Yes" or "Y" or "yes" or "YES":
print("\n Nice! Restarting the game! :) Good luck ;)")
break
if rerun == "No" or "N" or "no" or "NO":
print("\n Thanks for playing! :)")
break
board = "".join(board)
print("-" * 60)
print(" " + board) # display board
print("-" * 60)
print(" Already used words")
letterIs.append(letter) # for checking already said letters
print("".join(letterIs))
if letter not in guessWord:
print(" Bad luck!")
i -= 1
board = "".join(board)
print("-" * 60)
print(" " + board)
print("-" * 60)
print(" Already used words")
print("".join(letterIs))
else:
print(" Please write only one letter!")
| true |
b3002a921b6eccc3c318b66b5e242279b853c02b | kvssea/Python-Challenges | /palindrome.py | 845 | 4.5 | 4 | '''Create a program, palindrome.py, that has a function that takes one string argument and prints a sentence indicating if the text is a palindrome. The function should consider only the alphanumeric characters in the string, and not depend on capitalization, punctuation, or whitespace.
If your string is a palindrome it should print:
It’s a palindrome!
If it is not a palindrome, it should print:
It’s not a palindrome! '''
#palindrome.py
def palindrome(word):
word = word.replace(" ", "").lower()
new_dict = {}
for letter in word:
new_dict.update({letter : word.count(letter)})
odd_count = 0
for item in new_dict.values():
if item % 2 != 0:
odd_count += 1
if odd_count > 1:
print("It's not a palindrome!")
else:
print("It's a palindrome")
| true |
2df2ddc83610a326d4e5adbc825e12351a4cd630 | a200411044/Python_Crash_Course | /name.py | 278 | 4.21875 | 4 | #This show how to format your name in Python!
name = "simon law"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "simon"
last_name = "law"
full_name = first_name + " " + last_name
print(full_name)
msg = "Hello, " + full_name.title() + "!"
print(msg)
| true |
049d58de078d51cbd6f07ec4f9f6db77ce41842a | Ayetony/python-parallel-training | /basic/futures_executor.py | 1,718 | 4.21875 | 4 | """
线程池和进程池是用于优化和简化线程或者进程的使用。
通过池提交任务给executor
池由两部分组成,一个是内部的队列,存放着执行的任务,另一部分是一些列的进程或者线程,用于执行
这些任务。池的的主要目的是为了重用。
"""
import concurrent.futures
import time
number_list = [1, 2, 3, 4, 5, 6, 7, 7, 9]
def evaluate_item(x):
result_item = count(x)
return result_item
def count(number):
for i in range(0, 10000000):
i = i + 1
return i + number
if __name__ == '__main__':
start_time = time.time()
for item in number_list:
print(evaluate_item(item))
print('Sequential execution in ' + str(time.time() - start_time), 'seconds')
start_time_two = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(evaluate_item, item) for item in number_list]
for future in concurrent.futures.as_completed(futures):
print(future.result())
print('Thread pool execution in' + str(time.time() - start_time_two), "seconds")
start_time_three = time.time()
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(evaluate_item, item) for item in number_list]
for future in concurrent.futures.as_completed(futures):
print(future.result())
print('Process pool execution in ' + str(time.time() - start_time_three), 'seconds')
"""
ThreadPoolExecutor 和 ProcessPoolExecutor都是executor并行执行任务,但是ProcessPoolThread使用了多核处理的模块
让我们可以不受GIL的限制,大大缩短时间。
"""
| false |
7a2eaecdf76a8a44963109bd8fc595f5e660b7aa | mslok/SYSC3010_Michael_Slokar | /Lab-3/lab3-database-demo.py | 1,095 | 4.125 | 4 | #!/usr/bin/env python3
import sqlite3
#connect to database file
dbconnect = sqlite3.connect("mydatabase");
#If we want to access columns by name we need to set
#row_factory to sqlite3.Row class
dbconnect.row_factory = sqlite3.Row;
#now we create a cursor to work with db
cursor = dbconnect.cursor();
#execute insetr statement
#cursor.execute('''insert into temps values ('2020-10-04', time('now'), "kitchen", 19.6)''');
#cursor.execute('''insert into sensors values ('1', "door", "kitchen")''');
#cursor.execute('''insert into sensors values ('2', "temperature", "kitchen")''');
#cursor.execute('''insert into sensors values ('3', "door", "garage")''');
#cursor.execute('''insert into sensors values ('4', "motion", "garage")''');
#cursor.execute('''insert into sensors values ('5', "tmeperature", "garage")''');
#dbconnect.commit();
#execute simple select statement
cursor.execute('SELECT * FROM sensors');
#print data
for row in cursor:
if row['type'] == "door" or row['zone'] == "kitchen":
print(row['sensorID'], row['type'], row['zone']);
#close the connection
dbconnect.close(); | true |
f656fe862e4c13070c21cf18ecf10ea973e78681 | Ausduo/Hello_World | /french toast.py | 329 | 4.125 | 4 | print ("french toast")
bread = input ("enter bread size - thick or thin?")
bread = bread.lower ()
if bread == "thick":
print ("dunk the bread a long time")
elif bread == "thin":
print ("dunk the bread quickly")
else:
print ("don't do anything with it then")
print ("Thanks for following the help guide") | true |
e3aed22a599977ea2b46f1f86b1c30241ae3b236 | pablosq83/Pruebas3 | /filtrar_palabras.py | 998 | 4.28125 | 4 | #!usr/bin/python
# -*- coding: utf -8 -*-
"""
Función que recibe como parámetros una lista de palabras y un entero, devolverá una lista de palabras cuya longitud sea mayor o igual al número entero pasado como parámetro. La función hará un filtrado de palabras de longitud n.
Autor: Pablo Sulbarán (psulbaran@cenditel.gob.ve)
Fecha: 28-02-2018
"""
listap= []
tam= int(raw_input("Tamaño de la lista de palabras "))
i=0
for i in range(tam):
aux= raw_input("Introduzca una palabra ")
listap.append(aux)
n= int(raw_input("Introduzca una longitud de palabras n "))
def filtrar (listap, n, tam): # Se añadió como parámetro el tamaño de la lista de palabras para reducir líneas de código
palabrasgrandes= []
i=0
for i in range(tam):
pal= listap[i]
if (len(pal)>=n):
palabrasgrandes.append(pal)
return palabrasgrandes
filtrar (listap, n, tam)
print "\n"
print "Lista de palabras de longitud mayor a igual a n"
print "\n"
print filtrar(listap, n, tam)
| false |
31f648d3a317b0c5a37d1147f04ac636121a653b | DracoNibilis/pands-problem-sheet | /weekday.py | 367 | 4.4375 | 4 | # Program that outputs whether or not today is a weekday.
# Author: Magdalena Malik
#list with weekend days
weekendDays = ["Saturday", "Sunday"]
#input for day
givenDay = input("enter a day: ")
#if statement that checking if day is weekday or weekend
if givenDay in weekendDays:
print("It is the weekend, yay!")
else:
print("Yes, unfortunately today is a weekday.") | true |
228d2c3eeb296e07345ebf6304165ecfd8210593 | hclife/code-base | /lang/python/practices/fibo.py | 438 | 4.125 | 4 | #!/usr/bin/python
#Fibonacci numbers module
def fib1(n):
'''Print a Fibonacci series up to n.'''
a,b=0,1
while b<n:
print(b,end=' ')
a,b=b,a+b
print('')
def fib2(n):
'''List with a Fibonacci series up to n.'''
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
if __name__ == "__main__":
import sys
fib1(10)
res=fib2(10)
print(res)
| false |
e2c211c9354e0d90ca724b4cbb5ea9d466148f29 | hclife/code-base | /lang/python/practices/var.py | 245 | 4.25 | 4 | #!/usr/bin/env python3
i=5
print(i)
i=i+1
print(i)
print('Value is',i)
s='''This is a multi-line string.
This is the second line.'''
print(s)
t='This is a string. \
This continues the string.'
print(t)
width=20
height=5*9
print(width*height)
| true |
7fa4b69da07c842f00fa2598fabaf52908d44c81 | frazierprime/articles-and-papers | /project_euler/euler_nine.py | 790 | 4.5 | 4 | #!/usr/bin/env python3
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
MAX_VALUE = 1000
def is_pythagorean_triplet(a, b, c):
if a**2 + b**2 == c**2:
return True
else:
return False
def find_pythagorean_triplets_in_range(max_range):
for i in range(max_range):
for j in range(i + 1, max_range):
for k in range(i + 2, max_range):
if i + j + k == MAX_VALUE:
if is_pythagorean_triplet(i, j, k):
print('found the magical tiplet')
return i * j * k
else:
pass
if __name__ == "__main__":
product = find_pythagorean_triplets_in_range(500)
print(product) | false |
d744e8a5c0a5316d4690bee342c6a1ab1382d357 | QuinteroSantiago/OOP_Projects | /Learning/python_projects/bmi_app.py | 411 | 4.1875 | 4 | def bmi_app():
h = input('How tall are you?(cm)')
w = input('How much do you weigh?(kg)')
bmi = int(w)/((int(h)/100)**2)
print('Your bmi is {}'.format(round(bmi, 2)))
if bmi < 18.5:
print('You\'re underweight. Try to gain weight')
if bmi >= 18.5 and bmi <= 24:
print('You\'re in a healthy weight range')
else:
print('You\'re overweight. Try to lose weight')
bmi_app()
input('Press ENTER to exit') | false |
ffddaecc11fb57681fa5ce9fa520e16c0c5c86c1 | gitter-badger/python_me | /hackrankoj/ErrorAndException/incorrectregex.py | 780 | 4.28125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
You are given a string S.
Your task is to find out whether S is a valid regex or not.
Input Format
The first line contains integer , the number of test cases.
The next lines contains the string .
Constraints
Output Format
Print "True" or "False" for each test case without quotes.
Sample Input
2
.*\+
.*+
Sample Output
True
False
'''
import re
for _ in range(int(input())):
ans = True
try:
reg = re.compile(input())
except re.error:
ans = False
print(ans)
'''
re.error
https://docs.python.org/2/library/re.html
'''
import re
for _ in range(int(raw_input())):
try:
pattern = raw_input()
re.compile(pattern)
except:
print 'False'
else:
print 'True'
| true |
177988f87f1086e04fe5120ce23f80d6899847ef | gitter-badger/python_me | /hackrankoj/strings/capitalize.py | 1,534 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
'''
Sample Input
hello world
Sample Output
Hello World
原以为很简单,print ' '.join([s.capitalize() for s in raw_input().split()])
但是就是错在 ' '这里,不一定每个单词之间只有一个空格。
例如hello world lol这种。
'''
"""
s=raw_input()
new_s=''
for i in range(len(s)):
if i == 0 or (s[i-1].isspace() and s[i].isalnum()):
new_s = new_s + s[i].capitalize()
else:
new_s = new_s + s[i]
print new_s
"""
print ' '.join(word.capitalize() for word in raw_input().split(' '))
#这个和我的那个只有一个区别,split(' '),里面的参数给的是' ',我没有给。
#str.split([sep[, maxsplit]])
#Return a list of the words in the string, using sep as the delimiter string.
#If maxsplit is given, at most maxsplit splits are done
#(thus, the list will have at most maxsplit+1 elements).
#If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
"""
s='hello world lol'
s.split()
['hello','world','lol']
============区别=============
s.split(' ')
['hello', '', '', '', 'world', '', '', 'lol']
"""
'''
Title and Capitalise are different in function as:
'abcd'.title()
results in 'Abcd' but
'12abcd'.title()
results in '12Abcd'. This is not what we want.
'''
'''
第三种思路
我只是要改变每个单词的首字母,其它不变。找到,直接改replace
s = input()
for x in s[:].split():
s = s.replace(x, x.capitalize())
print(s)
'''
| false |
be8529d67a52b67b19aaad17a5db59c203ab94d9 | gitter-badger/python_me | /hackrankoj/collections/namedtuple.py | 2,422 | 4.15625 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
'''
namedtuple
Code 01
>>> from collections import namedtuple
>>> Point = namedtuple('Point','x,y')
>>> pt1 = Point(1,2)
>>> pt2 = Point(3,4)
>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
>>> print dot_product
11
就是给一个tuple 比如(1,2)赋予实际的意义,然后建立一个类,每一个元素对应一个属性,这里建立的是Point类,两个元素分别对应x,y
然后tuple中访问元素时就可以不用t[0]这种integer indices, 而像类属性那样的访问名字t.x就可以了
Code 02
>>> from collections import namedtuple
>>> Car = namedtuple('Car','Price Mileage Colour Class')
>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
>>> print xyz
Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y
这里主要说明了
classname = namedtuple(typename, field_names, verbose=False, rename=False)
1、field_names 的给值可以由字符串空格隔开的形式给出,也可以字符串逗号形式,统一csv格式。也可以list等迭代的
2、建立namedtuple的时候使用classname建立,不是typename
当打印一个namedtuple类的时候显示typename。
'''
'''
Task
Dr. John Wesley has a spreadsheet containing a list of student's IDs,Marks , Name and Class.
Your task is to help Dr. Wesley calculate the average marks of the students.
TESTCASE 01
5
ID MARKS NAME CLASS
1 97 Raymond 7
2 50 Steven 4
3 91 Adrian 9
4 72 Stewart 5
5 80 Peter 6
TESTCASE 02
5
MARKS CLASS NAME ID
92 2 Calum 1
82 5 Scott 2
94 2 Jason 3
55 8 Glenn 4
82 2 Fergus 5
Sample Output
TESTCASE 01
78.00
TESTCASE 02
81.00
输入的时候
MARKS的位置不一定!!!这对于不用这个方法是一个难点。
'''
from collections import namedtuple
all = int(raw_input())
student = namedtuple('student',raw_input())
score = 0
for _ in range(all):
s=student(*(raw_input().split()))
score+=int(s.MARKS)
print score/float(all)
'''
'''
from collections import namedtuple
N = int(input());student = namedtuple('student',input().strip().split())
print(sum(float(student(*input().strip().split()).MARKS) for _ in range(N))/N)
| false |
cf3dc601aa03d39564d83b37a82b7fce8ab453ea | gitter-badger/python_me | /GUI/component/scrollbar.py | 2,558 | 4.34375 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
# File Name: scrollbar.py
# Created Time: Thu Mar 2 20:08:59 2017
__author__ = 'Crayon Chaney <mmmmmcclxxvii@gmail.com>'
from Tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack(side = RIGHT,fill = Y)
#如果没有fill=Y的话,右边只显示了一段小框,但是没有滚动条,fill大概意思就是整条Y都填充
scrollbar_x = Scrollbar(root,orient = 'horizontal')
"""
I presume you want the "x" scrollbar to be horizontal rather than vertical. If that is true, you must tell tkinter that by using the orient option:
scrollbar_x = Scrollbar(root, orient="horizontal")
"""
scrollbar_x.pack(side = BOTTOM,fill = X)
"""
side;定义停靠在父组件的哪一边上,top(default),bottom,left,right
fill: 填充x(y)方向上的空间,当属性side="top"或者"bottom"的时候填充x方向,当left或right的时候填充y方向,expand选项
为yes,填充父组件的剩余空间
expand: 当值为yes时,side选项无效。组件显示在父配件中新位置???
"""
mylist = Listbox(root,xscrollcommand = scrollbar_x.set,yscrollcommand = scrollbar.set)
"""
To connect a scrollbar to another widget w, set w's xscrollcommand or yscrollcommand to the scrollbar's set() method. The arguments have the same meaning as the values returned by the get() method.
其实是因为scrollbar是双向communication,当我鼠标在listbox里面滚动的时候,这时候scrollbar也要跟着动,就要set它
"""
for line in range(100):
mylist.insert(END,("this is line number"+str(line))*100)
mylist.pack(side = LEFT,fill=BOTH)
#这里参数中有没有fill=BOTH不一样在于,自己看
scrollbar.config(command = mylist.yview)
scrollbar_x.config(command = mylist.xview)
"""
这两句什么意思???
mylist.yview
Query and change the vertical position of the view
????
为什么底部没有显示滑动条???
"""
"""
Scrollbars require two-way communication. The listbox needs to be configured to know which scrollbar to update when it has been scrolled, and the scrollbar needs to be configured such that it knows which widget to modify when it is moved.
When you do scrollbar.config(command=mylist.yview) you are telling the scrollbar to call the function mylist.yview whenever the user tries to adjust the scrollbar. The .yview method is a documented method on the Listbox widget (as well as a few others). If you do not set the command attribute of a scrollbar, interacting with the scrollbar will have no effect.
"""
print root.pack_slaves()
mainloop()
| false |
9e4dbeae2f401eecfb50daa6f60f33ed8d53f7c7 | varun-va/Python-Practice-Scripts | /GeeksforGeeks/majority_element.py | 1,009 | 4.21875 | 4 | '''
Given an array arr[] of size N and two elements x and y, use counter variables to find which element appears most in the array, x or y.
If both elements have the same frequency, then return the smaller element.
Note: We need to return the element, not its count.
Example 1:
Input:
N = 11
arr[] = {1,1,2,2,3,3,4,4,4,4,5}
x = 4, y = 5
Output: 4
Explanation:
frequency of 4 is 4.
frequency of 5 is 1.
Example 2:
Input:
N = 8
arr[] = {1,2,3,4,5,6,7,8}
x = 1, y = 7
Output: 1
Explanation:
frequency of 1 is 1.
frequency of 7 is 1.
Since 1 < 7, return 1.
'''
def getMajority(arr, x, y):
c1 = arr.count(x)
c2 = arr.count(y)
print('c1: ', c1)
print('c2: ', c2)
if c1 > c2:
return x
elif c1 == c2:
if x < y:
return x
else:
return y
else:
return y
arr1 = [1,1,2,2,3,3,4,4,4,4,5]
x1 = 4
y1 = 5
arr2 = [1,2,3,4,5,6,7,8]
x2 = 1
y2 = 7
arr = [5, 22, 29, 12, 32, 69, 1, 75]
x = 29
y = 96
print(getMajority(arr, x, y))
| true |
7f7c3d62a0a66664b05773bcde7c450291ad06d8 | jem441/OOP | /final.py | 1,140 | 4.34375 | 4 | print("Today we will play a number game.") #Beginning of the game.
print("You will take a guess at a number and if you are correct, you win!")
from textblob import TextBlob #importing the TextBlob Python Library
inpt = input("Enter a number between 0-10:") #giving the user the option to guess a number
text = TextBlob(inpt) #using TextBlob for the input
import random #Here we input random to randomize a number 1 through 10
t = random.randint(1,10)
#The following is the else if loop for the game.
if t == 0:
print("Too low, haha.")
elif t == 1:
print("Too low, haha.")
elif t == 2:
print("Too low, haha.")
elif t == 3:
print("You almost had it.")
elif t == 4:
print("Very close buddy.")
elif t == 5:
print("You got it right!")
elif t == 6:
print("Very close buddy.")
elif t == 7:
print("You almost had it.")
elif t == 8:
print("Too low, haha.")
elif t ==9:
print("Too low, haha.")
elif t == 10:
print("Too low, haha.")
if inpt == t: #Telling the player whether or not they guessed right or not
print("You got it!")
else:
print("Gameover")
| true |
d2d92bb0c527585152f1e211ed3f68c669b12dd7 | Cole-Black/HW2 | /main.py | 1,101 | 4.1875 | 4 | # Author: Cole Black-Stallard cdb5655@psu.edu
# Collaborator: N/A *Solo*
def getGradePoint(Gin):
if Gin == "A":
grade = 4.0
elif Gin == "A-":
grade = 3.67
elif Gin == "B+":
grade = 3.33
elif Gin == "B":
grade = 3.0
elif Gin == "B-":
grade = 2.67
elif Gin == "C+":
grade = 2.33
elif Gin == "C":
grade = 2.0
elif Gin == "D":
grade = 1.0
else:
grade = 0.0
return grade
def run():
mark1 = input("Enter your course 1 letter grade: ")
GPA1 = getGradePoint(mark1)
C1 = float(input("Enter your course 1 credit: "))
print(f"Grade point for course 1 is: {GPA1}")
mark2 = input("Enter your course 2 letter grade: ")
GPA2 = getGradePoint(mark2)
C2 = float(input("Enter your course 2 credit: "))
print(f"Grade point for course 2 is: {GPA2}")
mark3 = input("Enter your course 3 letter grade: ")
GPA3 = getGradePoint(mark3)
C3 = float(input("Enter your course 3 credit: "))
print(f"Grade point for course 3 is: {GPA3}")
GPA = (GPA1 * C1 + GPA2 * C2 + GPA3 * C3) / (C1 + C2 + C3)
print(f"Your GPA is: {GPA}")
if __name__ == "__main__":
run() | false |
c07c8066bcd2b2a86c329f68d8c107e54a285dba | NiumXp/Algoritmos-e-Estruturas-de-Dados | /src/python/insertion_sort.py | 1,607 | 4.3125 | 4 | """Implementação do algoritmo insertion sort iterativo e recursivo."""
def insertion_sort_iterativo(vetor):
"""
Implementação do algoritmo de insertion sort iterativo.
Args:
vetor (list): lista que será ordenada.
Returns:
Retorna a lista ordenada.
"""
for i in range(1, len(vetor)):
chave = vetor[i]
aux = i - 1
while aux >= 0 and vetor[aux] > chave:
vetor[aux + 1] = vetor[aux]
aux -= 1
vetor[aux + 1] = chave
return vetor
def insertion_sort_recursivo(vetor, indice):
"""
Implementação do algoritmo de insertion sort recursivo.
Args:
vetor (list): lista que será ordenada.
indice (int): índice do elemento a ser ordenado na lista.
Returns:
Retorna a lista ordenada.
"""
aux = indice
while vetor[aux] < vetor[aux - 1]:
temp = vetor[aux]
vetor[aux] = vetor[aux - 1]
vetor[aux - 1] = temp
aux -= 1
if aux == 0:
break
if indice < len(vetor) - 1:
insertion_sort_recursivo(vetor, indice + 1)
return vetor
if __name__ == '__main__':
lista_nao_ordenada = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6]
print('Lista não ordenada:')
print(lista_nao_ordenada)
lista_nao_ordenada = insertion_sort_iterativo(lista_nao_ordenada)
print('Lista ordenada com insertion sort iterativo:')
print(lista_nao_ordenada)
lista_nao_ordenada = insertion_sort_recursivo(lista_nao_ordenada, 1)
print('Lista ordenada com insertion sort recursivo:')
print(lista_nao_ordenada)
| false |
8a22aa66c7dcef600900898ee2f46bdc3cc4662b | NiumXp/Algoritmos-e-Estruturas-de-Dados | /src/python/busca_sequencial_recursiva.py | 696 | 4.21875 | 4 | """ Implementaçao do algoritmo de busca sequencial com recursão """
def busca_sequencial(valor, lista, index):
"""Busca sequencial recursiva.
Returns:
Retorna o indice do valor na lista.
Se nao encontrar retorna -1.
"""
if len(lista) == 0 or index == len(lista):
return -1
if lista[index] == valor:
return index
return busca_sequencial(valor, lista, index + 1)
if __name__ == '__main__':
uma_lista = [1, 9, 39, 4, 12, 38, 94, 37]
for indice, valor_na_lista in enumerate(uma_lista):
print('Testando valor {} no indice {}'.format(valor_na_lista, indice))
assert busca_sequencial(valor_na_lista, uma_lista, 0) == indice
| false |
1a2b9a0f8c147f10f8e376c1c70d76c4f9a4c8c0 | david2999999/Python | /Archive/PDF/Sequences/Dictionaries.py | 2,674 | 4.84375 | 5 | def main():
# When you first assign to menus_specials , you ’ re creating an empty dictionary with the curly braces.
# Once the dictionary is defined and referenced by the name, you may start to use this style of
# specifying the name that you want to be the index as the value inside of the square brackets, and the
# values that will be referenced through that index are on the right side of the equals sign. Because
# they ’ re indexed by names that you choose, you can use this form to assign indexes and values to the
# contents of any dictionary that ’ s already been defined.
menus_specials = {}
menus_specials["breakfast"] = "Canadian Ham"
menus_specials["lunch"] = "tuna surprise"
menus_specials["dinner"] = "cheeseburger deluxe"
# When you ’ re using dictionaries, the indexes and values have special names. Index names in
# dictionaries are called keys, and the values are called, well, values . To create a fully specified
# (or you can think of it as a completely formed) dictionary — one with keys and values assigned at the
# outset — you have to specify each key and its corresponding value, separated by a colon, between the
# curly braces. For example, a different day ’ s specials could be defined all at once:
menus_specials2 = {
"breakfast" : "Sausage and eggs",
"lunch" : "split pea soup and garlic bread",
"dinner" : "2 hot dogs and onion rings"
}
print(menus_specials)
print(menus_specials2)
print("%s" % menus_specials["breakfast"])
print("%s" % menus_specials["lunch"])
print("%s" % menus_specials["dinner"])
# If a key that is a string is accidentally not enclosed in quotes when you try to use it within square
# brackets, Python will try to treat it as a name that should be dereferenced to find the key. In most
# cases, this will raise an exception — a NameError — unless it happens to find a name that is the same
# as the string, in which case you will probably get an IndexError from the dictionary instead!
hungry = menus_specials.keys()
print(list(hungry))
starving = menus_specials2.values()
print(list(starving))
# Although you did not get an error, there is still a mistake in your code. When
# you typed in the second key named “ breakfast ” , Python replaced the value in the first key with the
# same name, and replaced the value of the second key with the same name.
menu2 = {
"breakfast": "spam",
"breakfast": "ham",
"dinner": "spam with a side of spam"
}
print(menu2)
if __name__ == "__main__":
main() | true |
241558933826203ee70c021dfb647c7d0fc07a35 | david2999999/Python | /Archive/PDF/Objects/Object-Basic.py | 2,414 | 4.34375 | 4 | # The methods that an object makes available for use are called its interface because these methods are
# how the program outside of the object makes use of the object. They ’ re what make the object usable.
# The interface is everything you make available from the object. With Python, this usually means that
# all of the methods and any other names that don ’ t begin with one or more underscores are your
# interfaces; however, it ’ s a good practice to distinguish which functions you expect to have called by
# explicitly stating what methods can be used, and how they ’ re used, in the class ’ s docstring:
def main():
class fridge:
"""This class implements a fridge where ingredients can be added and removed individually,
or in group. The fridge will retain a count of every ingredient added or removed, and will
raise an error if a sufficient quantity of an ingredient isn't present
Methods:
has(food_name [, quantity]) - checks if the string food_name is in the
fridge. Quantity will be set to 1 if you don’t specify a number.
has_various(foods) - checks if enough of every food in the dictionary is in
the fridge
add_one(food_name) - adds a single food_name to the fridge
add_many(food_dict) - adds a whole dictionary filled with food
get_one(food_name) - takes out a single food_name from the fridge
get_many(food_dict) - takes out a whole dictionary worth of food.
get_ingredients(food) - If passed an object that has the __ingredients__
method, get_many will invoke this to get the list of ingredients."""
def __init__(self, items={}):
"""Optionally pass in an initial dictionary of items"""
if type(items) != type({}):
raise TypeError("Fridge requires a dictionary but was given %s" % type(items))
self.items = items
return
if __name__ == "__main__":
main()
# Take a moment to look at the __init__ and (self) part of the code above. These are two very important
# features of classes. When Python creates your object, the __init__ method is what passes the object its
# first parameter. The (self) portion is actually a variable used to represent the instance of the object. | true |
150b28dfc4fc10f049ae0c4cbbf4387e3fa85801 | david2999999/Python | /Archive/PDF/Basic/String.py | 926 | 4.1875 | 4 | # When you type a string into Python, you do so by preceding it with quotes. Whether these quotes are
# single ( ' ), double( '' ), or triple( " " " ) depends on what you are trying to accomplish. For the most part, you
# will use single quotes, because it requires less effort (you do not need to hold down the Shift key to
# create them). Note, however, that they are interchangeable with the double and even triple quotes.
def main():
print("Hello World. You will never see this")
print("This text really won't do anything")
print("Hello, how are you?")
print("1+1")
print("@#@^#@@")
print("This is a string with double quote")
print('This is a string with single quote')
print("""This is a string with tripe quotes""")
print("I said, \"Don’t do it\"")
print("John" + "Everyman")
print("John" "Everyman")
print("John " "Everyman")
if __name__ == "__main__":
main() | true |
5aac6daec9b8beb2115fd5923584f8c1a506529c | david2999999/Python | /Archive/PDF/Decision/Comparison.py | 2,401 | 4.53125 | 5 | def main():
# Equality isn ’ t the only way to find out what you want to know. Sometimes you will want to know
# whether a quantity of something is greater than that of another, or whether a value is less than
# some other value. Python has greater than and less than operations that can be invoked with the >
# and < characters, respectively. These are the same symbols you are familiar with from math books, and
# the question is always asking whether the value on the left is greater than ( > ) or less than ( < ) the value
# on the right .
print(5 < 3)
print(10 > 2)
# The number on the left is compared to the number on the right. You can compare letters, too. A few
# conditions exist where this might not do what you expect, such as trying to compare letters to
# numbers. (The question just doesn ’ t come up in many cases, so what you expect and what Python
# expects is probably not the same.) The values of the letters in the alphabet run roughly this way: A
# capital “ A ” is the lowest letter. “ B ” is the next, followed by “ C ” and so on until “ Z ” . This is followed
# by the lowercase letters, with “ a ” being the lowest lowercase letter and “ z ” the highest. However, “ a ”
# is higher than “ Z ” :
print("a" > "b")
print("A" > "b")
print("A" > "a")
print("b" > "A")
print("Z" > "a")
# If you want to compare two strings that are longer than a single character, Python will look at each
# letter until it finds one that ’ s different. When that happens, the outcome will depend on that one
# difference. If the strings are completely different, the first letter will decide the outcome:
print("Zebra" > "aardvark")
print("Zebra" > "Zebrb")
print("Zebra" < "Zebrb")
# You can avoid the problem of trying to compare two words that are similar but have differences in
# capitalization by using a special method of strings called lower , which acts on its string and returns a
# new string with all lowercase letters. There is also a corresponding upper method. These are available
# for every string in Python:
print("Pumpkin" == "pumpkin")
print("Pumpkin".lower() == "pumpkin".lower())
print("Pumpkin".lower())
print("Pumpkin".upper() == "pumpkin".upper())
if __name__ == "__main__":
main() | true |
addd83aecdb01324615304c312abed1698ce99f4 | david2999999/Python | /Archive/PDF/Function/Docstring.py | 1,651 | 4.3125 | 4 | # If you place a string as the first thing in a function, without referencing a name to the string, Python will
# store it in the function so you can reference it later. This is commonly called a docstring , which is short for
# documentation string .
# Documentation in the context of a function is anything written that describes the part of the program
# (the function, in this case) that you ’ re looking at. It ’ s famously rare to find computer software that is well
# documented. However, the simplicity of the docstring feature in Python makes it so that, generally,
# much more information is available inside Python programs than in programs written in other
# languages that lack this friendly and helpful convention.
# The text inside the docstring doesn’t necessarily have to obey the indentation rules that the rest of the
# source code does, because it ’ s only a string. Even though it may visually interrupt the indentation, it ’ s
# important to remember that, when you ’ ve finished typing in your docstring, the remainder of your
# functions must still be correctly indented.
def main():
def in_fridge():
"""This is a function to see if the fridge has a food.
fridge has to be a dictionary defined outside of the function.
the food to be searched for is in the string wanted_food"""
try:
count = fridge[wanted_food]
except KeyError:
count = 0
return count
fridge = {'apple': 10, 'oranges': 3, 'milk': 2}
wanted_food = 'apple'
print("%d" % in_fridge())
print("%s" % in_fridge.__doc__)
if __name__ == "__main__":
main() | true |
4e7a9a3efd57c5866681b9a110af532252113c63 | Blak3Nick/MachineLearning | /venv/mulitple_linear_regression.py | 2,548 | 4.125 | 4 | # Multiple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""
#encoding the categories
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 3]= labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features=[3])
X = onehotencoder.fit_transform(X).toarray()
#Avoiding the Dummy variable trap-remove one of the dummy variables
"""most libraries do this automatically"""
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
#Fitting the Multiple Linear Regression t othe Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#Predicting the Test set results
Y_pred = regressor.predict(X_test)
#Building the optimal model using backward elimination
"""
Step 1 -Select a significance level to stay: i.e. SL = .05
Step 2 -Fit the model with all possible predictors
Step 3 -Consider the rpedictor with the highest P-value: If P > SL go to Step 4, else finished
Step 4 -Remove the predictor
Step 5 -Fit model without this variable, re-run from Step 3
"""
import statsmodels.formula.api as sm
#adding a 50 by 1 matrix of ones to the begining of X, this signifies Xsub 0
X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1)
#use only the optimal variables
X_opt = X[:, [0, 1, 2, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#remove X2 since it has highest P-value, and is > SL= .05
X_opt = X[:, [0, 1, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#remove X1
X_opt = X[:, [0, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#remove x4
X_opt = X[:, [0, 3, 5]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary()
#X5 is SL=.06 very close but will remove
X_opt = X[:, [0, 3]]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
regressor_OLS.summary() | true |
45728d1d9df3c4df2a2a5c9c2ed33272c4576839 | brucez082/Car_rental | /Car_rental.Achieved.py | 2,575 | 4.25 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Bruce Zhang
#
# Created: 06/09/2021
# Copyright: (c) Bruce Zhang 2021
# Licence: <your licence>
#-------------------------------------------------------------------------------
def car_prices(cars_list):
print("These are the prices for our cars....")
count = 0
while count < len(cars_list):
print(int(count/2+1), " ", cars_list[count], "$", cars_list[count + 1])
count += 2
print("*" * 20)
def car_booking(cars_list):
confirmed_booking = []
car_number = int(input("Which number car would you like to book? (1 - 9)"))
car_number = car_number * 2 -2
car_days = int(input("How many days would you like the {} for?".format(cars_list[car_number])))
first_name = str(input("Please enter your first name"))
last_name = str(input("Please enter your last name"))
car_cost = cars_list[car_number + 1] * car_days #calculates the cost of the booking
confirmed_booking.append(cars_list[car_number]) #this adds all of the variables to confirm booking list
confirmed_booking.append(cars_list[car_number + 1])
confirmed_booking.append(car_cost)
confirmed_booking.append(first_name)
confirmed_booking.append(last_name)
print("*** Confirmed Booking***")
print("Car model: {}".format(confirmed_booking[0]))
print("The daily hire cost of the {} is ${}".format(confirmed_booking[0], confirmed_booking[1]))
print("The total hire cost will be ${}".format(confirmed_booking[2]))
print("First name: {}".format(confirmed_booking[3]))
print("Last name: {}".format(confirmed_booking[3]))
print("*** End of the Confirmed Booking ***")
def main_menu():
import time
global cars_list
cars_list = ["Fiesta", 100, "Focus", 130, "Mondeo", 180, "Falcon", 230, "Territory", 280, "XR6 Ute", 250, "F150 Truck", 300, "Mustang", 350, "Van", 230]
print("Welcome to Speedy Car Rentals")
choice = 99
while choice != 0:
print("Please select from one of the following options: ")
print("Press 0 to exit")
print("Press 1 for the price list")
print("Press 2 to make a booking")
choice = int(input("Please enter your choice: \n 1 for prices \n 2 for a booking \n 0 to quit"))
if choice == 1:
car_prices(cars_list)
if choice == 2:
car_booking(cars_list)
print("PROGRAM ENDS******")
#Call the function
main_menu() | true |
8d4de53103ef5ea2eceddc64eb3ddd7e1e6b3b3f | arianacabral/Introduction-to-Python | /Atividade 5/Q19.py | 422 | 4.1875 | 4 | # Escreva um programa que leia números até o usuário digitar -1. Ao final, informe quantos números foram lidos.
def conta_numeros(number):
cont = 1
while number != -1:
number = float(input("Informe um número:"))
cont += 1
return cont
input0 = float(input("Informe um número:"))
n = conta_numeros(input0)
print("A quantidade de números digitados foi {}".format(n))
| false |
83f2011c420c5044dcc1eb7d31113d6f909547b5 | harrifeng/Python-Study | /Interviews/Coin_Change.py | 788 | 4.1875 | 4 | """
#####From [Geeksforgeeks](http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/)
Similar to CC150, just allow coin with 1, 3, 5 right now
Several ways to ask
1. How many ways?
2. What are the ways?
3. Minimum coin number?
"""
# This is same to Combination Sum I
def coin_change(value):
res = [0, 0, 0] # [num_5, num_3, num_1]
ret = []
coin_change_helper(0, value, res, ret)
return ret
def coin_change_helper(cur_face_value, rest_value, res, ret):
if rest_value == 0:
ret.append(res[:])
for i in range(cur_face_value, 3):
if rest_value - [5, 3, 1][i] < 0:
continue
res[i] += 1
coin_change_helper(i, rest_value - [5, 3, 1][i], res, ret)
res[i] -= 1
print coin_change(5)
| true |
7453a346480da9046278fb4f146b14c87bd9efa3 | Triballian/simprad | /src/main.py | 2,935 | 4.1875 | 4 | '''
Created on Mar 19, 2016
insprired by Curious Cheetah and Sergio
http://curiouscheetah.com/BlogMath/simplify-radicals-python-code/
http://stackoverflow.com/questions/31217274/python-simplifying-radicals-not-going-well
@author: Noe
'''
from math import modf
from math import sqrt
#from os import system
#Establish input
class Sqrtinput():
def __init__(self):
pass
def nsqrrt(self, a):
answer = False
A = a
#check to see if the answer is an integer
# sepsquared = squared seporated into integer and decimal parts
squared = sqrt(A)
fractional, integral = modf(squared)
if fractional == 0:
print("The answer is "+ u'\u221a' +str(int(squared)))
else:
if A < 8:
print 'The answer is ' + u'\u221a' + str(A)
else:
# print A
#Here we build a for loop ranged from 2 to spesquared[1] The devide into A .
# for number in range(2,int(integral)):
#may have to stake that if integral < 3 then integral +=1 may have to run a while loop here
answer = ''
for number in range(2,int(integral)+1):
print number
rem = A%number**2
if not rem:
answer = 'The answer is ' + str(number) + u'\u221a' + str(A/number**2)
if not answer:
print('The answer is '+ u'\u221a' + str(A))
else:
print answer
def getsqrt(self, a):
A=a
# A = int(raw_input("Enter the number under the radical:"))
#Input taken, setup math
B = (A + 1)
C = sqrt(B)
#seperate parts
#comment added by Noe. Fractial is the fraction portion of the number Integral is the Integer
Fractional, Integral = modf(C)
Fractional1, Integral1 = modf(A / (Integral**2))
def Intg(Integral):
while Fractional == Fractional1:
if Fractional1 == 0 and (A / (Integral**2)) == 1:
print (Integral)
return Integral
else:
Integral = (Integral - 1)
if Integral == 1:
print (A / (Integral**2))
elif not Integral ==1 or (Fractional1 == 0 and (A / (Integral**2)) == 1):
print Integral, (A / (Integral**2))
if __name__ == '__main__':
while True:
# system('cls')
# print('\x1b[2J')
a = int(raw_input("Enter the number under the radical:"))
ssqrrt = Sqrtinput()
# ssqrrt.getsqrt(a)
ssqrrt.nsqrrt(a)
pass
| true |
5b0fd08acefba8f2d7d2a934a1dcba2d34aa0cf0 | deepcloudlabs/dcl162-2020-sep-09 | /module02-functional.programming.in.python/exercise05.py | 369 | 4.125 | 4 | numbers = [3, 5, 7, 9, 4, 8, 15, 16, 23, 42]
is_there_any_odd_number = False
is_odd = lambda num: num % 2 == 1
def fun(num):
print(f"fun({num})")
return num % 2 == 1
for num in numbers:
if is_odd(num):
is_there_any_odd_number = True
break
print(is_there_any_odd_number)
# print(any(map(is_odd, numbers)))
print(all(map(fun, numbers)))
| false |
ad1dad840114284987b3e4a9f3aadaf8aa3b1c97 | managorny/python_basic | /homework/les04/file1.py | 834 | 4.25 | 4 | """
1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
"""
from sys import argv
def func(a, b, c):
try:
salary = (float(a) * float(b)) + float(c)
except ValueError:
print("Не верный параметр")
except TypeError:
print("Не верный параметр")
return salary
_, x, y, z = argv
print(func(x, y, z))
| false |
a863fd271a218cd39128ad624985bf64cc22c7b1 | rogerlinh/MindXSchool.github.io | /Teachingteam/Gen12X/VuongTranLuc_8/q6.py | 351 | 4.25 | 4 | # Add number at the end of a list
numberList = [1, 2, 3, 4,5]
print('Hi there, this is our sequences: ')
for number in numberList:
print(number, end=' ')
print()
newNumber = int(input('what do you want to add: '))
numberList.append(newNumber)
print('This is our new sequence: ')
for number in numberList:
print(number, end=' ')
print() | true |
1b9e709c6242628f43f892a6ed12e260f35dcfad | dishantsethi1/python-practise | /regularexpression.py | 885 | 4.125 | 4 | import re
s="take 5 one 1-13-2020 idea .one idea 2 5 at a time"
#result=re.search(r'o\w\w',s) #\w means any character means after o any two characters
#print(result.group()) #re.search shows only first one
result=re.findall(r'o\w\w',s) #re.findall will shoe every ehich starts with this
print(result)
res=re.match(r't\w\w\w',s) #only search at starting
print(res.group()) #\w+ means one or more \w* 0 or more
resu=re.split(r'\d+',s) #d means digits
print(resu) #\w{1} means one only \w{1,3} means one to three
#res1=re.sub(r'one','two',s) #replace
#print(res1)
res1=re.findall(r'\d{1,2}-\d{1,2}-\d{4}',s) #for dates
print(res1)
#special character
res2=re.search(r'^t\w*',s) #^ means at the starting
print(res2.group())
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.