blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6fbdc31f21536837f43ab7524c02d784ed3d2105 | sherzyang/learning_python3_the_hard_way | /Python/ex33.py | 1,012 | 4.3125 | 4 | #
# Author: Cristian E. Nuno
# Purpose: Exercise 33: While Loops
# Date: March 5, 2019
#
# a while-loop will keep executing the code block under it as long as a
# Boolean expression is True.
#
# What they do is simply do a test like an if-statement, but instead of
# running the code block once, they jump back to the 'top' where the while-
# loop starts and repeats the logic. A while-loop runs until the expression
# is False.
#
# Rules:
#
# 1. Make sure that you use while-loops sparingly.
# Usually a for-loop is better.
#
# 2. Review your while statements and make sure that the
# Boolean test will become False at some point.
#
# 3. When in doubt, print out your test variable at the top and bottom
# of the while-loop to see what it's doing.
#
i = 0
numbers = []
while i < 6:
print(f"At the top, i is {i}")
numbers.append(i)
i += 1
print("Numbers now: ", numbers)
print(f"At the bottom, i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
# end of script #
| true |
640da6ea164315675252f7976ab44a4a5cff4084 | sherzyang/learning_python3_the_hard_way | /Python/ex23.py | 1,188 | 4.1875 | 4 | #
# Author: Cristian E. Nuno
# Purpose: Exercise 23: Strings, Bytes, and Character Encodings
# Date: February 24, 2019
#
# Using a list of humang languages to demonstrate a few concepts:
#
# 1) How modern computers store human languages to display and processing
# and how Python 3 calls this 'strings'
# 2) Need to 'encode' and 'decode' Python's strings into a type called 'bytes'
# 3) How to handle errors in your string and byte handling
# 4) How to read code and understand it even if you've never seen it before
#
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
# without this if statement, the loop would continue forever
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors = errors)
cooked_string = raw_bytes.decode(encoding, errors = errors)
print(raw_bytes, "<===>", cooked_string)
languages = open("raw_data/languages.txt", encoding = "utf-8")
main(languages, input_encoding, error)
# end of script #
| true |
bb7987d8a58d8f85f3e699cf886dcedf7b072f2a | sherzyang/learning_python3_the_hard_way | /Python/ex20.py | 840 | 4.125 | 4 | #
# Author: Cristian E. Nuno
# Purpose: Exercise 20: Functions and Files
# Date: February 23, 2019
#
from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
# first line
current_line = 1
print_a_line(current_line, current_file)
# second line
# note: += adds another value with the variable's value and
# assigns the new value to the variable
current_line += 1
print_a_line(current_line, current_file)
# third line
current_line += 1
print_a_line(current_line, current_file)
# end of script #
| true |
74cae1e9a37124e6c75a5a11fa8deaaea3d2d694 | iamdeepakram/AllDataStructure | /linked_list.py | 1,118 | 4.46875 | 4 | # We Create linked list
#Create class node
class Node:
# Initiallize method
def __init__(self, data=None, next= None):
self.data = data
self.next = next
# basic mechanism for displaying the string type
def __str__(self):
return str(self.data)
#--- Assigning Nodes here ---#
NodeA = Node(2)
NodeB = Node(3)
NodeC = Node(4)
NodeD = Node(5)
#--- Linking Nodes ---#
# First node refer to second node
NodeA.next = NodeB
# Seond node refer to third node
NodeB.next = NodeC
# Third node refer to fourth node
NodeC.next = NodeD
#--- For Testing ---#
# Print Nodes
# print(NodeA)
#--- Print / Traversal of Linked list ---#
# Print linked list
def PrintLinkedList(head):
if head is not None:
current = head
ListSize = 1
while current is not None:
print(current.data)
current = current.next
ListSize += 1
return print("List Size is : ", ListSize , end=" ")
else:
return print("Head has no value")
PrintLinkedList(NodeA)
# Insert element in linked list
# Remove element in linked list | true |
f2ab249887a33bd3423ea93f5a40141a62dd0953 | lesleyfon/cs-module-project-algorithms | /moving_zeroes/moving_zeroes.py | 922 | 4.34375 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Your code here
'''
Naive Solution:
1 create a store to hold none 0 ints and 0 digits
2. loop though it and remove every element from the array and add to their respective arrays
3. Concat the zero array to the none zero array.
5. Concat every thing in the none_zero array into the arr and return it
'''
zero_store = []
none_zero = []
while len(arr) > 0:
if arr[0] == 0:
zero_store.append(arr.pop(0))
else:
none_zero.append(arr.pop(0))
pass
none_zero.extend(zero_store)
arr.extend(none_zero)
return arr
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
| true |
4adc78bbba01383e9b56c25d66cc9281adb9fa0d | Rafaheel/Curso-de-Python | /9-exercicio.py | 825 | 4.21875 | 4 | # faca um programa que leia um numero inteiro qualquer e mostre na tela sua tabuada.
n = int(input("Digite um numero para a sua tabuada: "))
print("-" * 45)
print(f"O numero é {n}, e sua tabuada é: 1 X {n} = {1 * n}")
print(f"O numero é {n}, e sua tabuada é: 2 X {n} = {2 * n}")
print(f"O numero é {n}, e sua tabuada é: 3 X {n} = {3 * n}")
print(f"O numero é {n}, e sua tabuada é: 4 X {n} = {4 * n}")
print(f"O numero é {n}, e sua tabuada é: 5 X {n} = {5 * n}")
print(f"O numero é {n}, e sua tabuada é: 6 X {n} = {6 * n}")
print(f"O numero é {n}, e sua tabuada é: 7 X {n} = {7 * n}")
print(f"O numero é {n}, e sua tabuada é: 8 X {n} = {8 * n}")
print(f"O numero é {n}, e sua tabuada é: 9 X {n} = {9 * n}")
print(f"O numero é {n}, e sua tabuada é: 10 X {n} = {10 * n}")
print("-" * 45)
| false |
6c43dac9edfa008791d4c3d5fcd7840873ec9bd3 | Rafaheel/Curso-de-Python | /11-exercicio.py | 500 | 4.1875 | 4 | # Faça um programa que leia a largura, a altura de uma parede em metros calcule sua area e aquantidade de tinta necessaria para pinta-lá, saabendo que cada litro de tinta pinta uma area de 2metros quadrados.
largua = float(input("Informe a largura: "))
altura = float(input("Informe a altura: "))
area = largua * altura
lata_tinta = 2
print(f"A largura é {largua}, a altura é {altura}, então sua area é de {area}m, \nassim sendo será necessario {area / lata_tinta} litros de tinta")
| false |
641c2e97bc483a469959c4922823cea628a6f036 | JLMarshall63/myGeneralPythonCode_B | /Triangles.py | 1,759 | 4.84375 | 5 | # Directions: Complete the functions below. The first one is done for you. The tests at the bottom
#should run and print out values you'd expect.
# Geog 565 2016 Assignment 6 Part 1
# Name: John Marshall
# Date: 7/25/2017
# This script creates and test 3 functions
# the triangle fucntion takes in 3 numbers and returns the type of triangle
def triangle(a, b, c):
if a == b == c:
return "equilateral"
elif (a != b and a != c and b != c):
return "none"
else:
return "isosceles"
# the absolutevalue function takes in an integer and returns the absolute value of that integer
# you can assume there will only be integers as input
# the absolute value of a number is always positive
# for example: the absolute value of 5 is 5; the absolute value of -5 is 5
def absolutevalue(num):
# your code here
x = abs(num)
return x
# the absolutevalues function takes in a list of integers and returns a list of the absolute values
#of the original list this is similar to the absolutevalue function except you need to loop through
#the input list and return a list.append
list = []
def absolutevalues(numlist):
for x in numlist:
list.append(abs(x))
return list
# Tests - do not remove. These will help you know your functions are working. Feel free to add more!
# triangle tests
print "Triangle Tests: "
print triangle(2,2,2)
print triangle(2,2,5)
print triangle(1,2,3)
# absolutevalue tests
print "Absolute Value Tests: "
print absolutevalue(-5)
print absolutevalue(10)
# absolutevalues tests
print "Absolute Values Tests: "
print absolutevalues([1,2,-2,-5])
print absolutevalues([-11,-12,2,-5])
print absolutevalues([-67,-99,10,123])
| true |
228ccabc94e6626774f3c8d46377776bbf843bc0 | JLMarshall63/myGeneralPythonCode_B | /ListSlice.py | 981 | 4.59375 | 5 | '''
List Slicing
Sometimes, you only want to access a portion of a list.
letters = ['a', 'b', 'c', 'd', 'e']
slice = letters[1:3]
print slice
print letters
In the above example, we first create a list called letters.
Then, we take a subsection and store it in the slice list. We
start at the index before the colon and continue up to but not
including the index after the colon.
Next, we print out ['b', 'c']. Remember that we start counting
indices from 0 and that we stopped before index 3.
Finally, we print out ['a', 'b', 'c', 'd', 'e'], just to show that
we did not modify the original letters list.
'''
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
middle = suitcase[2:4] # Third and fourth items (index two and three)
last = suitcase[4:6] # The last two items (index four and five)
print first
print middle
print last
print suitcase
| true |
debb19dbb436bffd311d28005da1986b13d6f61c | choucurtis987/CS-131b-Labs | /acronym_creator.py | 444 | 4.53125 | 5 | # 2-9-19
# creates an acronym based on all capital letters in word
def capital_acronym(word):
answer = ''
# the for loop loops through all the letters in word:
for letter in word:
# the .isupper() method is a bool that determines if letter is uppercased:
if letter.isupper():
# if letter is uppercased, it will add letter to the blank string "answer":
answer += letter
return answer
| true |
c53a5e6cbfeaebc9f3b35a4a3eb65da3fb2b934a | r-chaudhary/Learning-Python | /Introduction-To-Python/Code 11/Code_11.py | 254 | 4.3125 | 4 | # Introduction to Python
# Programmer : Rahul Chaudhary
# Email : r.chaudhary@outlook.in
# Code : 11
# Python Program to print list element less than 5.
list = [1,1,2,3,5,8,13,21,34,55,89]
print("less than 5")
for i in list:
if i < 5:
print(i, end = " ")
| false |
b72cdb03d67725f88177efc8debd4cb5ac318eff | r-chaudhary/Learning-Python | /Introduction-To-Python/Code 10/Code_10.py | 423 | 4.375 | 4 | # Introduction to Python
# Programmer : Rahul Chaudhary
# Email : r.chaudhary@outlook.in
# Code : 10
# Python Program to check whether string is Pangram.
def pangram(stirng):
alpha = []
for i in string.lower():
if i not in alpha:
alpha.append(i)
if len(alpha) < 26:
print("%s is not an pangram"%string)
else:
print("%s is an pangram"%string)
string = input("Enter String : ")
pangram(string)
| false |
0648831b6a6c39fc9ed97c6a15478e6fbca99524 | octaviomontano/lps_compsci | /class_samples/5-1_files/haikuGenerator2.py | 1,685 | 4.46875 | 4 | # importing the random program to choose a random line from the list I've created
import random
randomLine = ['Baby don\'t hurt me','Once upon a time','A fast potato','To infinity and beyond','To who it concerns','Oh mathematics']
# displays options and prompts choice
print 'Welcome to the Haiku generator!'
print 'Would you like to write your haiku from scratch or get a randomized first line?'
print '(1) I\'ll write it from scratch'
print '(2) Start me with a random line'
choice = input()
# conditional statements that run certain tasks based on user input
if choice == 1:
# saves lines and text file names to variables
print 'Provide the first line of your haiku:'
firstL = raw_input()
print 'Provide the second line of your haiku:'
secondL = raw_input()
print 'Provide the third line of your haiku:'
thirdL = raw_input()
print 'What file would you like to write your haiku to?'
name = raw_input()
if choice == 2:
# randomly chooses a number that determines the randomly chosen line, then prompts for 2 more lines
print 'All right, here\'s your first line:'
num = random.randint(0,6)
firstL = randomLine[num]
print firstL + '\n'
print 'Provide the second line of your haiku:'
secondL = raw_input()
print 'Provide the third line of your haiku:'
thirdL = raw_input()
print 'What file would you like to write your haiku to?'
name = raw_input()
print 'Done! To view your haiku, type \'cat\' and the name of your file at the command line.'
# uses variables to create the new file with lines for the haiku
haiku = open(name, 'w')
haiku.write(firstL + '\n')
haiku.write(secondL + '\n')
haiku.write(thirdL + '\n')
haiku.close()
| true |
e1690e297bf66eff2ac751dee1a0ac997ea1db5d | rohith-22/Test-project | /cspp1 Assignments/module 7/Functions - Assignment-2/assignment2.py | 2,072 | 4.34375 | 4 | """# Assignment-2 - Paying Debt off in a Year
# Now write a program that calculates the minimum fixed monthly payment needed
in order pay off a credit card balance within 12 months.
# By a fixed monthly payment, we mean a single number which does not change each month,
but instead is a constant amount that will be
# paid each month.
# In this problem, we will not be dealing with a minimum monthly payment rate.
# The following variables contain values as described below:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal
# The program should print out one line: the lowest monthly payment that
will pay off all debt in under 1 year, for example:
# Lowest Payment: 180
# Assume that the interest is compounded monthly according tothe balance at the end of the month
(after the payment for that month is made).
# The monthly payment must be a multiple of $10 and is the same for all months.
Notice that it is possible for the balance to become
# negative using this payment scheme, which is okay. A summary of the required math is found below:
# Monthly interest rate = (Annual interest rate) / 12.0
# Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
# Updated balance each month = (Monthly unpaid balance)
+(Monthly interest rate x Monthly unpaid balance)"""
def paying_debtoffinayear(bal_ance, annualinterest_rate):
"""defining paying function"""
var_bal = bal_ance
var_pay = 0
while True:
i = 12
var_bal = bal_ance
while i != 0:
var_ubal = var_bal - var_pay
var_bal = var_ubal + ((annualinterest_rate / 12.0) * var_ubal)
i -= 1
if var_bal > 0:
var_pay += 10
else:
break
return var_pay
def main():
""" main"""
data = input()
data = data.split(' ')
data = list(map(float, data))
print("Lowest Payment: " + str(paying_debtoffinayear(data[0], data[1])))
if __name__ == "__main__":
main()
| true |
24850c6d452d0de2f7bdf8a75ed9d64e41e4349e | suvajitsarkar/python_tutorial | /maptest.py | 214 | 4.125 | 4 | # Example of using map function
# Get L and R from the input
L, R = map(int, input().split())
# Write here the logic to print all integers between L and R
for i in range(L,R+1):
print(i, end=" ")
print("")
| true |
7cdfcaeb2e0b84aa0c79e4ffc7234924297478d0 | grb2015/university_course_teaching | /华师大_python/turtle/offical_example/simple/6_peace.py | 1,545 | 4.65625 | 5 | """
学习基本的移动,角度。
turtle-example-suite:
tdemo_peace.py
A simple drawing suitable as a beginner's
programming example. Aside from the
peacecolors assignment and the for loop,
it only uses turtle commands.
"""
from turtle import *
def main():
peacecolors = ("red3", "orange", "yellow",
"seagreen4", "orchid4",
"royalblue1", "dodgerblue4")
reset()
Screen()
#up() ### penup()
goto(-320,-195)
width(70) ### 设置粗线!
#goto(100,-195) ## 可以试试这个
## 1.画不同颜色的粗横线
for pcolor in peacecolors:
color(pcolor)
#down() ## pendown()
forward(640)
#up()
backward(640) ## 画完之后要返回来
left(90)
forward(66) ## 画完之后,要向上移动一段,以便画上面的线
right(90)
## 2.画图形
## step1 将光标移动到(0,-170)
width(25)
color("white")
goto(0,-170)
#down()
## step2 画圆圈
circle(170)
## step3 画向上的横线
left(90)
forward(340)
## step4 ... 向下移动170 回到圆心
left(180)
forward(170)
## step5 向左下移动170
right(45)
forward(170)
## step6 backward 170回到圆心,然后向右下移动170
backward(170)
left(90)
forward(170)
#goto(0,300) # vanish if hideturtle() is not available ;-)
return "Done!"
if __name__ == "__main__":
main()
mainloop()
| false |
c8219085f7b539569c9cd1775b14f9da0644c641 | jeenuv/algos | /shell_sort.py | 770 | 4.5625 | 5 | #!/usr/bin/python3
import sort_utils as su
from insertion_sort import insertion_sort
def shell_sort(array):
def find_h(n):
"""
For a given 'n', find an largest h such that (3*h + 1) < n
"""
h = 0
while h < n:
t = h
h = (3 * t) + 1
return t
# Shell sort is repeated insertion sort, but peformed with decreasing values
# of stride, h. We first start with the largest h that's less that the total
# number of elements. The repeat the sort with h/3 and so on
n = len(array)
h = find_h(n)
while h > 0:
array = insertion_sort(array, stride=h)
h = h // 3
return array
if __name__ == "__main__":
su.test_sort(shell_sort, 20)
# vim: set tw=80 sw=4:
| true |
f6b8dd82b33eafcead4d6cbece7ae3f2d4dd6952 | baocogn/self-learning | /big_o_coding/Green_06/day_3_quiz_7.py | 1,366 | 4.34375 | 4 | n = int(input())
a = [
[" " for _ in range(n)] for _ in range(n)
]
for i in range(n):
a[i][0] = "*" # left-most column
a[0][i] = "*" # top row
a[i][n-1] = "*" # right-most column
a[n-1][i] = "*" # bottom row
for i in range(n):
for j in range(n):
print(a[i][j], end="")
print()
for i in range(0, n):
for j in range(0, n):
if i == j: # This indicates the main diagonal
print("*", end="")
elif i + j == n - 1: # This indicates the extra diagonal
print("*", end="")
# This indicates the top row
elif i == 0:
# Usually the print() function will print the content with a new line.
# In order to do this problem, we need the `end` argument of the print() function.
# Basically, print("#", end="") means we just print out the single character '*'
# without entering a new line.
print("*", end="")
# This indicates the left-most column
elif j == 0:
print("*", end="")
# This indicates the lowest row
elif i == n - 1:
print("*", end="")
# This indicates the right-most column
elif j == n - 1:
print("*", end="")
else:
print(" ", end="")
print() # This will print a new line
| false |
23286c60ecc0d1e44e7db1cf902c578a73f71d02 | mossi1mj/RunSpeed | /RunSpeed.py | 1,213 | 4.4375 | 4 | # Program: Ch 1 Ex 46
# Author: Myron Moss
# Date: 08/07/2020
# Description: Calculates the time to run 5 miles, 10 miles, half marathon, and full marathon.
speed = int(input("Enter Running Speed(mph): "))
minutesPerMile = 60 // speed
print("It takes", minutesPerMile, "minutes to run a mile!")
print()
print("Calculation on Specific Distances")
print("=================================")
# TIME = (DISTANCE / SPEED) * 60
# Calculate for 5 Miles
time = (5 / speed) * 60 # Fill in the Formula to calculate TIME
hours = int(time / 60) # Divide TIME BY 60 to get HOURS
minutes = int(time % 60) # Remainder of Hours gives MINUTES
print("Five Miles:", hours, "hour(s),", minutes, "minutes")
# Calculate for 10 Miles
time = (10 / speed) * 60
hours = int(time / 60)
minutes = int(time % 60)
print("Ten Miles:", hours, "hour(s),", minutes, "minutes")
# Calculate for Half Marathon (13.1 Miles)
time = (13.1 / speed) * 60
hours = int(time / 60)
minutes = int(time % 60)
print("Half Marathon:", hours, "hour(s),", minutes, "minutes")
# Calculate for Full Marathon (26.2 Miles)
time = (26.2 / speed) * 60
hours = int(time / 60)
minutes = int(time % 60)
print("Full Marathon:", hours, "hour(s),", minutes, "minutes") | true |
96079c7521d4e7791be2420ca18d8f6558bf4cbe | lianghp2018/PycharmDemo | /继承/08_super()调用父类方法.py | 2,374 | 4.46875 | 4 | """
super(当前类名, self).函数名()
方法1,带参数,多层继承中继承关系为
--徒弟 继承 学校
--学校 继承 师父
当徒弟想调用所有父类(师父类,学校类)的同名方法时,
需要在同样继承了师父类的 学校类中 的同名方法中也添加带参数的super()代码语句
*该方法依旧没有解决函数名改变时程序员需要修改代码的工作量
方法2,无参数 super().函数名()
同上
学校类同名方法也需要带无参数super()代码语句
*该方法成功解决了上述问题
"""
# 师父类, 属性,方法
class Master(object):
def __init__(self):
self.kongfu = "独门技术"
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
# 学校类 继承师父类
class School(Master):
def __init__(self):
self.kongfu = "学校教授的技术"
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
# 方法2.1 带参数 super()
# super(School, self).__init__()
# super(School, self).make_cake()
# 方法2.2 无参数的super()
super().__init__()
super().make_cake()
return
# 徒弟类,继承师父类
class Prentice(School):
def __init__(self):
self.kongfu = "自己研究出的技术"
def make_cake(self):
# 如果先调用了父类的方法,kongfu属性会被父类覆盖
# 所以此处先调用自己的初始化方法
self.__init__()
print(f'运用{self.kongfu}制作煎饼果子')
def make_master_cake(self):
# 让父类的kongfu属性覆盖上一次调用的kongfu属性
# 方法1. 该方法代码冗余,父类名改变需要修改多处代码
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
# 让父类的kongfu属性覆盖上一次调用的kongfu属性
School.__init__(self)
School.make_cake(self)
def make_old_cake(self):
# 方法2.1 使用super(当前类名, self).函数名()
# 带参数
# super(Prentice, self).__init__()
# super(Prentice, self).make_cake()
# 方法2.2 无参数的super()
super().__init__()
super().make_cake()
daqiu = Prentice()
daqiu.make_old_cake()
| false |
30dae6f9ffb9cd1dfa75bbc9b434cd5926380e12 | GR3C0/Ecuaciones | /derivadas.py | 1,253 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# tipo_derivada = tp
from math import sqrt
print "¿Que derivada quieres? (funcion lineal, potencia, raiz cuadrada)"
tp = raw_input(":")
def funcion_lineal(a,b,c):
""" derivada de una funcion lineal """
print ""
print "f(x) =",a,b
def potencia(a,n):
""" derivada de una potencia, args la potencia y el número """
print ""
print "f(x) =",a,"**",n
print ""
print "Ahora tu derivada"
print n * a**(n - 1) * a
print ""
print "Y la formula"
print "f'(x) = n * a**(n - 1) * a"
print ""
def raiz_cuadrada(u):
""" derivada de una raiz cuadrada, args la raiz"""
print ""
print "f(x) = √", u
print ""
print "Ahora tu derivada"
print u/2*sqrt(u)
print ""
print "Y la formula"
print "f'(x) = u / 2 * √2"
print ""
#elección de tipo de formula
if tp == "funcion lineal": #cada condicional tiene una función y sus argumentos correspodientes
print "Dame los números"
print "a"
a = input(":")
print "b"
b = input(":")
funcion_lineal()
elif tp == "potencia":
print "Dame la base"
a = input(":")
print "Ahora el exponente"
n = input(":")
potencia(a,n)
elif tp == "raiz cuadrada":
print "Dame la raiz"
u = input(":")
raiz_cuadrada(u)
else:
print "¿Que quieres tio?" | false |
667453a7a089c37c5854e1b603fbcedc04357826 | jinicha/d32-automated-birthday-wisher | /challenge/birthday-wisher-normal-start/main.py | 2,866 | 4.1875 | 4 | ##################### Normal Starting Project ######################
# 2. Check if today matches a birthday in the birthdays.csv
# HINT 3: Use dictionary comprehension to create a dictionary from birthday.csv that is formated like this:
# birthdays_dict = {
# (birthday_month, birthday_day): data_row
# }
#Dictionary comprehension template for pandas DataFrame looks like this:
# new_dict = {new_key: new_value for (index, data_row) in data.iterrows()}
#e.g. if the birthdays.csv looked like this:
# name,email,year,month,day
# Angela,angela@email.com,1995,12,24
#Then the birthdays_dict should look like this:
# birthdays_dict = {
# (12, 24): Angela,angela@email.com,1995,12,24
# }
#HINT 4: Then you could compare and see if today's month/day tuple matches one of the keys in birthday_dict like this:
# if (today_month, today_day) in birthdays_dict:
# 3. If there is a match, pick a random letter (letter_1.txt/letter_2.txt/letter_3.txt) from letter_templates and replace the [NAME] with the person's actual name from birthdays.csv
# HINT 1: Think about the relative file path to open each letter.
# HINT 2: Use the random module to get a number between 1-3 to pick a randome letter.
# HINT 3: Use the replace() method to replace [NAME] with the actual name. https://www.w3schools.com/python/ref_string_replace.asp
# 4. Send the letter generated in step 3 to that person's email address.
# HINT 1: Gmail(smtp.gmail.com), Yahoo(smtp.mail.yahoo.com), Hotmail(smtp.live.com), Outlook(smtp-mail.outlook.com)
# HINT 2: Remember to call .starttls()
# HINT 3: Remember to login to your email service with email/password. Make sure your security setting is set to allow less secure apps.
# HINT 4: The message should have the Subject: Happy Birthday then after \n\n The Message Body.
import datetime as dt
import pandas as pd
import smtplib
import config
import os
import random
# get current month and day
now = dt.datetime.now()
month = now.month
day = now.day
# read data from csv file
data = pd.read_csv("birthdays.csv")
row = data[data.month == month]
if len(row) > 0:
data_day = row.day
if data_day.item() == day:
name = row.name.item()
email = row.email.item()
letter = random.choice(os.listdir("letter_templates"))
with open("letter_templates/" + letter, "r") as f:
filedata = f.read()
filedata = filedata.replace("[NAME]", name)
with open("letter_templates/" + letter, "w") as f:
f.write(filedata)
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=config.gmail, password=config.gmail_pw)
connection.sendmail(
from_addr=config.gmail,
to_addrs=email,
msg=f'Subject: Happy Birthday!\n\n{filedata}'
)
| true |
62272720522ea17bc448f6e9546e2d4fcf2cea6e | ecosaghae/Class-Attendance | /classOrganizer/ClassSchdule/main.py | 2,323 | 4.15625 | 4 | """
1. View all the students
2. Add students to class
3. Remove students from classes
4. Exit the program
"""
# Import sys provides functions and variables which are used to manipulate different parts of the Python Runtime
# Environment. It lets us access system-specific parameters and functions
'''
Whenever we call import logging it actually go to this package that comes with python. It saying all the functions
that are here 'website', make it accessible in our script so we can call these functions.
so for example, in order to track an event or tell us something is wrong, we use 'logging.warning()'
'''
import logging
# we are going to have a seperate file for our functions
from classFunctions.main import viewstudents, addstudent, removestudent
'''
To display the date and time of an event, place '%(asctime)s %(message)s'
this will tell us the date and time this event was logged
'''
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
# Let user know classFunctions is found
try:
from classFunctions import *
logging.debug("classFunctions.py imported successfully!")
except:
logging.critical("classFunctions.py is missing! Program will now exit!")
print("classFunctions.py is missing! Program will now exit!")
exit()
# Print out if import function found
'''
while true means loop forever. The while statement takes an expression and excutes the loop body while the expression
evaluates to (boolean) "true".
So as long as the condition is true, the condition will run indefinitely until something with the loop returns or breaks
'''
while True:
print('Welcome to my class organizer!')
print('*' * 50)
print('1. View students in classes')
print('2. Add students to classes')
print('3. Remove students from classes')
print('4. Exit the program')
# '\n' makes a new line
print('\nPick a number from above: ')
choice = input('> ')
# Print out students
if choice == '1':
# view students
viewstudents()
elif choice == '2':
addstudent()
elif choice == '3':
removestudent()
elif choice == '4':
print('Thank you for using my program!')
exit()
else:
print("That is not a valid number!")
| true |
0862423416d4904fd36e79cc90b47c4fe9da856b | adcGG/Lianxi | /Tuple.py | 851 | 4.125 | 4 | #Tuple 是不可变的序列,也是一种可以存储 各种数据类型 集合,用小括号表示元组的开始和结束,元素之间用逗号分隔
#这里不可变,包括不能对 元组对象进行增加元素、变换元素位置、修改元素、删除元素等操作。元组中每个元素提供对应的一个下标,从0开始
test = (1,2,2,'1','a')
test3 = ('OK',)#为了避免当成数学公式的括号 ,加个逗号 消除歧义
nameAge = 'tom',19
name,Age = 'Alice',20
print(nameAge,type(nameAge))
print(name,Age,'type(name)',type(name),'type(Age)',type(Age))
print(test[:3])
for get_num in test:
if get_num == '1':
print("'1'的下标是%d"%test.index('1'))
break
print('test中 2的数量',test.count(2))
test2 = (1,2,3)
print('用sum计算元组的和(为数字)',sum(test2))
test4 = test+test3
print('test4:',test4) | false |
c0732288b2532a290a7b7d0320a776955a79aebf | achisum94/projects | /portfolio/exam_pass_or_fail.py | 521 | 4.15625 | 4 | #get number of students who passed
passed=int(input('enter number of students that passed the exam: '))
#get number of students who failed
failed=int(input('enter number of students that failed in the exam: '))
#total number of students in the class
total=passed+failed
print('total of students: ',total)
# get percentages
pass_percentage=passed/total
fail_percentage=failed/total
print(format(pass_percentage, '%'),'of students passed in the class')
print(format(fail_percentage,'%'), 'of students failed in the class') | true |
d2fd50ab56a5862ed895ac47ecfc1cce401258fd | hong8240/OPS435 | /lab2/temp2.py | 242 | 4.125 | 4 | \count = 0
while count != 5:
print(count)
count = count + 1
print('loop has ended')
password = ''
while password != 'P@ssw0rd':
password = input("Type in a password: ")
print('Congratulations you guessed the correct password!')
| true |
53f4675c75612e8900860cfd91a88e165d8f2696 | iuliia-eagle/hometask | /Tasks/a0_my_stack.py | 755 | 4.15625 | 4 | """
My little Stack
"""
from typing import Any
stack = []
def push(elem: Any) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
global stack
stack.append(elem)
return None
def pop() -> Any:
"""
Pop element from the top of the stack
:return: popped element
"""
global stack
if stack:
elem = stack.pop(-1)
return elem
else:
return None
def peek(ind: int = 0) -> Any:
"""
Allow you to see at the element in the stack without popping it
:param ind: index of element (count from the top)
:return: peeked element
"""
global stack
elem = stack[-ind-1]
return elem
def clear() -> None:
"""
Clear my stack
:return: None
"""
while stack:
stack.pop()
return None
| true |
87762148a142529169a069d8b019bc302cee9f8a | fernandojrlabayo/Python-Tutorial-Notes | /1.py | 2,954 | 4.4375 | 4 | # Basic print statement
print("hello World")
print("Welcome to python tutorial")
# comments in Python
"""
I am a multiline comment
"""
# python variable(use to store data)
x=34 #x is an integer
y=3.5 # float variable
string= "ako si pogi"
# print (x,string,y)
"""
Rules for creatinf variable in python
1. It must start with a letter or an underscore
2. It cannot start with a number
3. It can only contain alphanumeric characters or an _
"""
string2="142"
# print(type(string2)) # type command so you know what data type is being display
a=34
b=3
#this is how you do operators in ptyhon
"""
print("the value of a+ b is",a+b)
print("the value of a-b is",a-b)
print("the value of a* b is",a*b)
print("the value of a/b is",a/b)
print("the value of a // b is",a//b)
3. It can only contain alphanumeric characters or an _
"""
#Python Collection (Arrays)
'''
There are 4 types of collection in pyhton:
1.list
2.tuple
3.set
4. dictionary
'''
# l1=[22,23,2,3,2,3,3]
# print("My first list is here: ",l1)
# print("My first value list is here: ",l1[0])
# l1.append(34) #add at the end
# l1.pop(2)
# l1.remove(25)
# l1.clear()
#tuples
# t1=(1,2,13,3,)
# values cannot be changed
# sets in python
# myset={1,2,23,3,33,13,123}
# print(myset)
myDictionary= { #the same as object in java key-value pair
"harry" : "Good boy",
"mac" : "Bad boy",
"sam" : "only boy",
"marks" : 1255
}
#syntax for getting value
# print(myDictionary["sam"])
# print(myDictionary.get("marks"))
# myDictionary["marks"]=15 # change value of a certain key
# If else condition in python
# d = input("Enter your name:") # if you enter any(string,number,float) input in the user it will be stored as string
# d = int(d)
"""
#typecasting convertd a data type into another data type
d = float(d)
d = str(d)
"""
# print(type(d))
'''
equals ==
greater >
less than <
less than or equal to <=
greater than or equal to >=
'''
"""
a=22
b=21
c=15
d=39
if(d>a):
print("d is greater")
elif (d==a):
print("d is equal")
else:
print("d is not greater ")
"""
#Loops in python
'''
i=0
while(i<20): #loop until the condition is met
print('hello')
i=i+1
'''
# for i in range(0,12): #range from 0 to 11
fruits =["Grapes","Guava","apple","Oranges"]
# for item in fruits:
# print("Hello " + item) # can only concat string to string
# if item =="Oranges":
# print("Oranges found")
# break #break can be used to if you want to get out of the loop in this case if the word is found get out of the loop
# continue #if you use continue in this case the last item will not be printed and it will just continue the condition
#function are something that performs an action
# def printList(List1,greet): #indent always so it will recognize
# print (greet) #what ever you right
# for item in List1:
# print("The value of the item is: ", item)
# printList(fruits,"Welcome I print you this items")
| true |
cf101a40e8160b54351be6cf34d43b1266403b41 | recvd/nets_clean | /largest_non_adjacent.py | 679 | 4.125 | 4 | def largest_non_adjacent(array):
if len(array) == 1:
return array[0]
if len(array) == 2:
return max(array)
else:
return max([array[-1], largest_non_adjacent(array[:-2])+array[-1], largest_non_adjacent(array[:-1])])
def largest_non_adjacent_it(array):
solution = [0] * len(array)
solution[0] = array[0]
solution[1] = max(array[:1])
for i, _ in enumerate(array):
solution[i] = max(array[i],
solution[i-2] + array[i],
solution[i-1])
return solution[-1]
test = [-2, 1, 3, -4, 5]
print(largest_non_adjacent(test))
print(largest_non_adjacent_it(test))
| false |
547e317b62326559d4ea3454c7beea9d92a4feb2 | DragonBuilder/Daily_Coding_Challenges | /day2.py | 993 | 4.25 | 4 | # This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
# Follow-up: what if you can't use division?
import unittest
def other_products(L):
prod = 1
for e in L:
prod *= e
res = []
for e in L:
res.append(prod // e)
return res
class TestOtherProducts(unittest.TestCase):
def setUp(self):
self.testcases = [
{
"input" : [1, 2, 3, 4, 5],
"expected" : [120, 60, 40, 30, 24]
}
]
def test_other_products(self):
L = [1, 2, 3, 4, 5]
expected = [120, 60, 40, 30, 24]
for testcase in self.testcases:
actual = other_products(testcase['input'])
self.assertEqual(testcase['expected'], actual)
if __name__ == '__main__':
unittest.main() | true |
48ae6ebfbef73071caaf73a0789941f06916c8eb | Anjitha-Sivadas/luminarpythonprograms | /Advance python/OOP/DEMO.py | 935 | 4.5 | 4 | #class design pattern
#object real world entity
#reference name that refers a memory location of a object
#referances to do operations on object, provide memory locations
#eg:
#class: tv
#object: samsung lg etc
#reference: remote
class Person: # first letter of a class name should be cap letter
def walk(self): # using fn we create methods self: it says t is inside the class(point to current instance)
print("person is walking") # variables using self is known as instance
#walk run jumping are methods
def run(self):
print("person is running")
def jumping(self):
print("person is jumping")
obj=Person() # reference name obj, we using reference by specifying class name
obj.walk() # using refe name we call methods
obj.run()
obj.jumping()
ab=Person() #2ndobject suing ab reference
ab.walk()
| true |
e9fae847ef32cc016ecf371a188424afe568e646 | Anjitha-Sivadas/luminarpythonprograms | /FUNCTION/demo.py | 1,333 | 4.40625 | 4 | #FUNCTIONS
#normal syntax
"""
def functionname(arguments):
function defination
function call #by using fn name
"""
#three methods
#1 Fn without an arguments and no return type.....................................
"""
def add():
num1=int(input("enter numb1"))
num2=int(input("enter a numb2"))
sum=num1+num2
print(sum)
add()
"""
"""
def sub():
num1=int(input("enter numb1"))
num2=int(input("enter numb2"))
sub=num1-num2
print(sub)
sub()
"""
"""
def mul():
num1=int(input("enter numb1"))
num2=int(input("enter numb2"))
mult=num1*num2
print(mult)
mul()
"""
#2 Fn with arguments and no return type....................................................
"""
def addition(num1,num2):
sum=num1+num2
print(sum)
addition(30,50) #give values of arguments
def substraction(num1,num2):
sub=num1-num2
print(sub)
substraction(20,10)
def multiN(num1,num2):
mult=num1*num2
print(mult)
multiN(2,2)
"""
#3 Fn with arguments and return type................................................................
"""
def sumN(num1,num2):
sum=num1+num2
return sum
data=sumN(50,25)
print(data)
def subN(num1,num2):
sub=num1-num2
return sub
data=subN(20,10)
print(data)
def mulN(num1,num2):
mul=num1*num2
return mul
data=mulN(5,5)
print(data)
""" | true |
a514f0d8f978c40127bf4ea3bf6790cefeec915f | Anjitha-Sivadas/luminarpythonprograms | /Advance python/OOP/inheritance/multiple inheritance.py | 867 | 4.4375 | 4 | #multiple inheritance--child class inherited from more than one parent class
# one child class can inherit from multiple parent classes.
class Parent:
parent_name = "Arun"
def m1(self, age):
self.age = age
print("my name is ", Parent.parent_name)
print("my age is", self.age)
class Mobile:
def mob(self):
print("i have one plus")
class Child(Parent,Mobile): # inheritance--while sung inheritance, we must give
# parent class name
def m2(self, cage):
self.cage = cage
print("my parent name is", Parent.parent_name)
print("my parent age is ", self.age)
print("child age is ", self.cage)
c = Child()
c.m1(23) # we must call m1 first and m2 next
c.m2(16) # as in python line by line interpretation,so we must give value first
c.mob() # then we can call | true |
d4042bb419c014fe827361b9fc0f861322ed186e | javiguajardo/interview-prep | /data_structures/review/quicksort.py | 789 | 4.21875 | 4 | def quicksort(arr):
quicksort_helper(arr, 0, len(arr) - 1)
def quicksort_helper(arr, left, right):
if left < right:
pivot = arr[(left + right) // 2]
partition_point = partition(arr, left, right, pivot)
quicksort_helper(arr, left, partition_point - 1)
quicksort_helper(arr, partition_point, right)
def partition(arr, left, right, pivot):
while left <= right:
while arr[left] < pivot:
left += 1
while arr[right] > pivot:
right -= 1
if left <= right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return left
if __name__ == "__main__":
arr = [2, 1, 4, 0, 0, -2, -4, 20, 5, 3, 3]
print(arr)
quicksort(arr)
print(arr)
| false |
4330fc61e994a84603d42335de00f63a845d179a | javiguajardo/interview-prep | /algorithms/backtracking/print_binary.py | 434 | 4.15625 | 4 | def print_binary(digits, prefix=''):
# print(f'print_binary({digits}, {prefix})')
'''
Print all permutations of the binary numbers with n digits.
2
00
01
10
11
'''
if digits == 0:
print(prefix)
else:
print_binary(digits - 1, prefix + '0')
print_binary(digits - 1, prefix + '1')
if __name__ == '__main__':
digits = int(input().strip())
print_binary(digits)
| true |
7cf148ac0ef58b362087bc8e5f18f056b1a8e15a | javiguajardo/interview-prep | /algorithms/quicksort/quicksort.py | 1,333 | 4.3125 | 4 | print('Import quicksort module')
def quicksort(arr):
"""
Sort a list of numbers using quicksort
Runtime: O(n log n)
O(log n) space
"""
if len(arr) < 2:
return arr
quicksort_helper(arr, 0, len(arr) - 1)
def quicksort_helper(arr, start, end):
"""
Run quicksort on each partition
Runtime: O(log n)
"""
if start >= end:
return
split_point = partition(arr, start, end)
quicksort_helper(arr, start, split_point - 1)
quicksort_helper(arr, split_point, end)
def partition(arr, start, end):
"""
Partition the array with elements smaller than the pivot to the left and elements greater than the pivot to the right
Runtime: O(n)
"""
pivot = arr[(start + end) // 2]
while start <= end:
while arr[start] < pivot:
start += 1
while arr[end] > pivot:
end -= 1
if start <= end:
swap(arr, start, end)
start += 1
end -= 1
return start
def swap(arr, index1, index2):
"""
Swap elements in list
Runtime: O(1)
"""
temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
if __name__ == "__main__":
arr = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(arr)
quicksort(arr)
print('sorted')
print(arr)
| true |
be5add42a96d07851c95620f75333cda291157a4 | FebLee/Algorithms | /Leetcode/7.py | 509 | 4.25 | 4 | # reverse integer ,given a 32-bit signed int, reverse digits of an int
def reverse(x):
''' input type: int
rtype: int
'''
is_nagative = 1
reverse_int = 0
if x < 0:
is_nagative = -1
x *= -1
while x > 0:
remainder = x % 10
x //= 10
reverse_int = reverse_int * 10 + remainder
reverse_int *= is_nagative
if reverse_int > 2 ** 31 - 1 or reverse_int < - 2 ** 31:
return 0
return reverse_int
| true |
783d54ab83f167c30fc8400cb20c378d667ed309 | garrethpb/GB_algorithms | /factorial.py | 264 | 4.34375 | 4 | def factorial(num):
product = 1
for i in range(2, num + 1):
product *= i
return product
print factorial(8)
# Challenge: Write a function that, given a number, calculates and returns the product of all positive integers from 1 up to the number (inclusive).
| true |
0ffa1f961664357f06bf0c9d3298976f171b36ff | PradeepaShri/Game-of-SET | /find_disjoint_sets.py | 940 | 4.28125 | 4 |
def find_disjoint(set_list):
"""
function to find disjoint SET's given a list of SET's
:rtype: int, list
:param set_list: list of SET's
"""
max_disjoint = []
for x in combine(set_list):
if len(x) > len(max_disjoint):
max_disjoint = x
return len(max_disjoint),max_disjoint
def combine(set_of_cards, current=None, list_of_sets=set()):
"""
function to find disjoint SET's by recursively combining them
:rtype: object
:param set_of_cards: list of SET's
:param current: list of current disjoint SET's
:param list_of_sets: list of disjoint SET's
"""
if current is None:
current = []
if current:
yield current
for index, elem in enumerate(set_of_cards):
if list_of_sets.isdisjoint(elem):
for element in combine(set_of_cards[index + 1:], current + [elem], list_of_sets | set(elem)):
yield element
| true |
337dcbab7079f96293eac47b0b94dc213e2043a1 | WesleyJGilsenan/CP1404practicals2018 | /Prac02/exceptions_demo.py | 858 | 4.53125 | 5 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur? When a non intger is entered into either numerator or denominator
2. When will a ZeroDivisionError occur? When Zero is entered as the denominator.
3. Could you change the code to avoid the possibility of a ZeroDivisionError? Add a If statement to check if it is a zero and if so, say it is invalid.
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
if denominator == 0:
print("That is a invalid input")
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.") | true |
5d7789e9560f26404fe8c99d2ad6b10daf8c111f | christopherhanke/-8-first-python | /secret.py | 1,286 | 4.25 | 4 | #####################################################
# #
# game of searching or guessing a secret number #
# v1.1 - added top-score #
# #
#####################################################
import random
secret = random.randint(1, 100)
guess = 0
attempts = 0
print("Hello. And welcome to secret number.")
with open("topscore.txt", "r") as score_file:
top_score = int(score_file.read())
print(f"Top player needed {top_score} attempts to guess it right.")
print("Now it's your turn. Guess a number between 1 and 100.")
while guess != secret:
if attempts == 0:
guess = int(input("Your guess: "))
else:
guess = int(input("Your next gues: "))
attempts += 1
if guess < secret:
print("Your guess is below the secret number.")
if guess > secret:
print("Your guess is above the secret number.")
print("Yeah. You found it. The secret number is " + str(secret) + ".")
print("You used " + str(attempts) + " guesses to get it right.")
if attempts < top_score:
print("You were better and got on top.")
with open("topscore.txt", "w") as score_file:
score_file.write(str(attempts))
| true |
cc7c76af8a8636f1fb4b4e1ef8fa668701d76918 | IngvarRed/circle_python_2019 | /decesar/decesar _fr.py | 2,232 | 4.28125 | 4 | '''
open a file to read,
such as 'story.txt'
read text
pick up punctuation
split by ' '
set the key
convert word
find the word in the dictionary 'words.txt'
change the key rating
the highest rated key is the correct one
decode text
'''
import string
import sys
import operator
def key_to_dict(key): # create encryption dictionary
str_arr = string.ascii_lowercase
str_arr2 = string.ascii_lowercase[key:] + string.ascii_lowercase[:key]
str_arr += string.ascii_uppercase
str_arr2 += string.ascii_uppercase[key:] + string.ascii_uppercase[:key]
cliper_dict = {}
for k, v in zip(str_arr, str_arr2):
cliper_dict[k] = v
return cliper_dict
def decript_text(decr_dict, encr_text): # decrypt text
decr_text = ''
for letter in encr_text:
if letter in decr_dict:
decr_text += decr_dict[letter]
else:
decr_text += letter
return decr_text
# open a file to read
# args = sys.argv
args = ['a', 'story.txt']
try:
file_name = args[1]
with open(file_name, 'r') as file_text:
original_text = file_text.read()
except IndexError:
print("""
Usage: decesar_fr.py file_name
file_name -- is a file for read
""")
exit(1)
except IOError as e:
print("There is no file ")
exit(2)
except Exception as e:
print("Error is ", e)
exit(3)
# pick up 'spaces'
text = original_text.strip()
# pick up punctuation
for symbol in string.punctuation:
text = text.replace(symbol, "")
# split by ' '
words = text.split()
with open('words.txt', 'r') as wl:
word_file = wl.read()
# split by ' '
word_list = word_file.split()
# set the key
new_dict = {}
key_rate = {}
for n_key in range(0, 27):
rate = 0
new_dict = key_to_dict(n_key)
# convert word
for word in words:
# convert word
decr_word = decript_text(new_dict, word)
# find the word in the dictionary 'words.txt'
if decr_word.lower() in word_list:
rate += 1
# change the key rating
key_rate[rate] = n_key
# the highest rated key is the correct one
optimal = max(key_rate.keys())
# decode text
decode = decript_text(key_to_dict(key_rate[optimal]), original_text)
print(decode)
| true |
8370151a69e41583c1f65bb428768ccd6035bc9c | PacktPublishing/Clean-Code-in-Python | /Chapter07/generators_yieldfrom_1.py | 510 | 4.21875 | 4 | """Clean Code in Python - Chapter 7: Using Generators
> The ``yield from`` syntax: chain generators.
"""
def chain(*iterables):
"""
>>> list(chain("hello", ["world"], ("tuple", " of ", "values.")))
['h', 'e', 'l', 'l', 'o', 'world', 'tuple', ' of ', 'values.']
"""
for it in iterables:
yield from it
def _chain(*iterables):
for it in iterables:
for value in it:
yield value
def all_powers(n, power):
yield from (n ** i for i in range(power + 1))
| false |
69526b585ff4130ad4dcffd79845ec3d1a4966e6 | jdudley390/automation-and-practive | /Example's from book and video/Lists.py | 696 | 4.375 | 4 | #Multiple list inside of a list
list = [["cat", "bat"], [10,20,30,40]] #this is a list of 2 lists
print(list[0][1]) #this will print the 2nd item in the first list (remember start at 0 not 1 for index)
#assign new value to an item in a list
list1 = [10, 20, 30]
print(list1)
list1 [1] = 'Hello' ## will replace the number 20 with 'Hello'
list1[2:3] = [6, 8] #replaces 30 with 6 and adds 8 to index[3]
print(list1)
#if you use a number higher than the lists length with a slice it will add on to the list
'howdy' in ['hello', 'hi', 'howdy', 'hey'] #will evalute to true since value is in list
#not in operates the same way
'howdy' not in ['hello', 'hi', 'howdy', 'hey'] #will evaluate to false | true |
51d79bee28520b98ad1d8acd52627ace16006839 | linocondor/FizzBuzz_lc | /FizzBuzz.py | 507 | 4.3125 | 4 | # This program receives a number and then iterates with this rules: if the number(integer) is multiple of 3 print Fizz, if the number is multiple of 5 print Buzz, and if the number is multiple of 3 and 5 print FizzBuzz.
number = int(input("Please enter a number(integer): "));
for i in range(1, number + 1):
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)
| true |
b093a9909e007a603bd766e54df59e567c631715 | GabrielNagy/Year3Projects | /PE/Labs1-3/lab2.py | 1,749 | 4.125 | 4 | #!/usr/bin/env python3
# Exercises from Laboratory 2
def count_words(text):
counter = 0
for word in text.split():
counter += 1
return counter
def count_vowels(text):
counter = 0
vowels = "aeiouAEIOU"
for letter in text:
if letter in vowels:
counter += 1
return counter
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
if __name__ == "__main__":
text = """Now is the winter of our discontent
Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried."""
print("Number of words: %d" % count_words(text))
print("Number of vowels: %d" % count_vowels(text))
list = ['Monty', 'Python', 'and', 'the', 'Holy', 'Grail']
print(list[::-1])
string = input("Enter string: ")
if string == string[::-1]:
print("Entered string is palindrome.")
else:
print("Entered string is not a palindrome.")
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
list2 = [2, 4, 9, 11, 33]
list3 = []
for element in list1:
if element in list2:
list3.append(element)
print(list3)
divList = []
for i in range(1000, 2000):
if i % 5 and not i % 7:
divList.append(i)
print(divList)
number = int(input("Enter number to compute factorial: "))
print("The factorial of the number is %d" % factorial(number))
numberArray = [10, 20, 20, 30, 30, 56, 67, 75, 22, 10, 33]
numberArray = set(numberArray)
numberArray.remove(max(numberArray))
numberArray.remove(min(numberArray))
print(numberArray)
print(sum(numberArray) / float(len(numberArray)))
| true |
b2c172dc0479c38f1cc58ebe343e8ef8c27eea81 | itshuffy/CTI110 | /M3HW1_AgeClassifier_Huff.py | 406 | 4.15625 | 4 | # CTI-110
# M3HW1 - Age Classifier
# Jesse Huff
# 10/11/2017
#Get input
userAge = int(input("Please enter your age: "))
#string for all ages other than past 20
if userAge <= 1:
print("You are an Infant")
elif userAge < 13:
print("You are a child")
elif userAge < 20:
print("You are a teenager")
#Else statement for 20 and above
else:
print("You are an adult")
| false |
38c3f161021b49c2c18722aecf65a89fddfb5401 | itshuffy/CTI110 | /M3T1_AreasOfRectangles_JesseHuff.py | 706 | 4.15625 | 4 | #Jesse Huff
#9/18/2017
#CTI-110
#Get the rectangle sizes
recl1 = int(input('Enter the length of the first rectangle. '))
recw1 = int(input('Enter the width of the second rectangle. '))
recl2 = int(input('Enter the length of the second rectangle. '))
recw2 = int(input('Enter the width of the second rectangle. '))
#Calculate
area1 = (recl1 * recw1)
area2 = (recl2 * recw2)
#if statement
if area1 > area2:
print('The first rectangle is larger. ')
if area2 > area1:
print('The second rectangle is larger. ')
if area1 == area2:
print('The two rectangles are equal')
#Display the Sizes
print('The first rectangle is', area1)
print('The second rectangle is', area2)
| true |
7c87312e2e4816f14baa7364c51cc6d9f3a1eb1b | MikkelOerberg/sandbox | /oddName.py | 322 | 4.125 | 4 | """
Mikkel Hansen
"""
def main():
name = str(input("input your name: "))
for char in name:
print(char, char.isalpha())
if all(x.isalpha() or x.isspace() for x in name):
print("Only alphabetical letters and spaces: yes")
else:
print("Only alphabetical letters and spaces: no")
main()
| true |
256e0101bc3fbf351c4db64347f64b6292203ac4 | alsGitHub270/my-test-repo | /list_comprehension.py | 725 | 4.375 | 4 | '''
List comprehension allows us to build out lists using a
different notation. Think of it as essentially a one line loop
built inside brackets.
'''
l = []
for letter in 'word':
l.append(letter)
print l
lst = [letter for letter in 'word']
print "\nusing list comprehension: ", lst
lst = [x**2 for x in range(0,11)]
print lst
# check for even numbers
lst = [number for number in range(11) if number % 2 == 0]
print '\nlist of even numbers in a range: ', lst
print '\nconverts celcuis to farhrenheit'
celsius = [0,10,20,34.5, 44,100]
fahrenheit = [(temp * (9/5.0) + 32) for temp in celsius]
print fahrenheit
print '\nnested list comprehension'
lst = [x**2 for x in [x**2 for x in range(11)]]
print lst
| true |
94444cd545750f89abc5ca4ebaed15603866add6 | mave5/pmarp | /maxDepthBT.py | 804 | 4.34375 | 4 |
'''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path
from the root node down to the farthest leaf node.
'''
#%%
# Python program to find the maximum depth of tree
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxDepth(node):
if node is None:
return 0
return max(maxDepth(node.left),maxDepth(node.right))+1
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Height of tree is %d" %(maxDepth(root))
# Time Complexity: O(n), n number of nodes
| true |
1f6ef220bd97385b320539b1ae223a4194106aca | mgnhjkl/PrinciplesOfComputing | /project/week5/Word_Wrangler.py | 2,128 | 4.28125 | 4 | def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
if len(list1) == 0:
return list1
results = [list1[0]]
for item in list1:
if item != results[-1]:
results.append(item)
return results
def intersect(list1, list2):
"""
intersect should return a new sorted list that contains only
the elements that are in both input lists, list1 and list2.
"""
index1 = 0
index2 = 0
interlist = []
while index1 != len(list1) and index2 != len(list2):
if list1[index1] == list2[index2]:
interlist.append(list1[index1])
index1 += 1
index2 += 1
elif list1[index1] < list2[index2]:
index1 += 1
elif list2[index2] < list1[index1]:
index2 += 1
return interlist
def merge(list1, list2):
"""
merge should return a new sorted list that
contains all of the elements in either list1 and list2.
"""
merged_list = []
index1 = 0
index2 = 0
list_tmp1 = list1[:]
list_tmp2 = list2[:]
list_tmp1.append(float("inf"))
list_tmp2.append(float("inf"))
while index1 != len(list_tmp1) - 1 or index2 != len(list_tmp2) - 1:
if list_tmp1[index1] <= list_tmp2[index2]:
merged_list.append(list_tmp1[index1])
index1 += 1
else:
merged_list.append(list_tmp2[index2])
index2 += 1
return merged_list
def merge_sort(list1):
"""
merge_sort should return a new sorted list that
contains all of the elements in list1 sorted in ascending order.
"""
if len(list1) <= 1:
return list1
else:
return merge(merge_sort(list1[0:len(list1)/2]), merge_sort(list1[len(list1)/2:]))
def gen_all_strings(word):
"""
return all possible strings that
can be constructed from the letters in the input word.
"""
if len(word) == 0:
return [""]
first = word[0]
rest = word[1:]
rest_strings = gen_all_strings(rest)
new_strings = []
for rest_string in rest_strings:
for index in range(len(rest_string) + 1):
new_string = rest_string[:index] + first + rest_string[index:]
new_strings.append(new_string)
new_strings += rest_strings
return new_strings
| true |
926ab0604f0700e89aaa8ad27e15af10c641c6ff | LuccasTraumer/pythonRepositorio | /URI/Area.py | 797 | 4.125 | 4 | '''
a) a área do triângulo retângulo que tem A por base e C por altura.
b) a área do círculo de raio C. (pi = 3.14159)
c) a área do trapézio que tem A e B por bases e C por altura.
d) a área do quadrado que tem lado B.
e) a área do retângulo que tem lados A e B.
'''
valores = input().split(' ')
A = float(valores[0])
B = float(valores[1])
C = float(valores[2])
pi = 3.14159
# Area = b*h/2
area = A*C/2
# A = pi * r**2
A_Circulo = pi * C**2
# A = B+b*h/2
A_Trapezio = (A+B)*C/2
# Area_Quadrado A= b*b
A_Quadrado = B*B
# Area Retangulo A= b*h
A_Retangulo = A*B
print("TRIANGULO: {:.3f}".format(area))
print("CIRCULO: {:.3f}".format(A_Circulo))
print("TRAPEZIO: {:.3f}".format(A_Trapezio))
print("QUADRADO: {:.3f}".format(A_Quadrado))
print("RETANGULO: {:.3f}".format(A_Retangulo))
| false |
4f0cc7c108c82ad45e81c6de8ff4d58b9638b746 | LuccasTraumer/pythonRepositorio | /CursoPython/Exercicios/Ex042.py | 1,200 | 4.28125 | 4 | '''
Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
- EQUILÁTERO: todos os lados iguais
- ISÓSCELES: dois lados iguais, um diferente
- ESCALENO: todos os lados diferentes
'''
print('------- ANALISANDO TRIANGULO ---------')
n1 = float(input('Digite o Primeiro Segmento: '))
n2 = float(input('Digite o Segundo Segmento: '))
n3 = float(input('Digite o Terceiro Segmento: '))
if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('Os Segmentos \033[35m Formam \033[m uma Reta ')
if n1 == n2 and n1 == n3 and n2 == n3:
print('Triangulo EQUILATERO')
elif n1 != n2 and n1 != n3 and n2 != n3:
print('É uma Triangulo ECALENO')
elif n1 != n2 and n1 == n3:
print('Triangulo ISOSCELES')
elif n1 == n2 and n1 != n3:
print('Triangulo ISÓSCELES')
elif n2 != n1 and n2 == n3:
print('Triangulo ISÓSCELES')
elif n2 == n1 and n2 != n3:
print('Triangulo ISÓSCELES')
elif n3 != n1 and n3 == n2:
print('Triangulo ISOSCELES')
elif n3 == n1 and n3 != n2:
print('Triangulo ISOSCELES')
else:
print('\033[31m Nao Formam \033[m um Triangulo ')
| false |
15ea586d8ffa05182616cb0b29a37841d5b41311 | LuccasTraumer/pythonRepositorio | /CursoPython/Exercicios/Ex037.py | 869 | 4.15625 | 4 | '''Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. '''
print('-------------- \033[36m Conversor de Numero \033[m --------------------')
n1 = int(input('Digite um Numero Qualquer : '))
print('''Escolha uma das Bases de Conversão
[ 1 ] para \033[33m BINARIO \033[m
[ 2 ] para \033[34m OCTAL \033[m
[ 3 ] para \033[35m HEXADECIMAL \033[m''')
opcao = int(input('Escolha sua Opcão: '))
if opcao == 1:
print('O Numero {} em \033[33m BINARIO \033[m é {}'.format(n1,bin(n1)[2:]))
elif opcao == 2 :
print('O Numero {} em \033[34m OCTAL \033[m é {}'.format(n1,oct(n1)[2:]))
elif opcao == 3:
print('O Numero {} em \033[36m HEXADECIMAL \033[m é {}'.format(n1,hex(n1)[2:]))
else:
print('\033[31m Opção Invalida \033[m') | false |
fc6cc6aaf40e1967c7602db00f75baa95bdec30b | Jxio/dataStructureAndAlgorithm | /CountSquares.py | 637 | 4.1875 | 4 | # Write a function that gets the number of squares between two numbers
#method 1
def CountSquares(a, b):
cnt = 0 # initialize result
# Traverse through all numbers
for i in range (a, b + 1):
j = 1;
while j * j <= i:
if j * j == i:
cnt = cnt + 1
j = j + 1
i = i + 1
return cnt
# method2
# An Efficient Method to count squares between a
# and b
import math
def CountSquares(a, b):
return (math.floor(math.sqrt(b)) - math.ceil(math.sqrt(a)) + 1)
# Driver Code
a = 9
b = 25
print "Count of squares is:", int(CountSquares(a, b)) | true |
e9d1569d747d587e602fdf257b20bb02a99bb384 | black-christopher/PythonExercises | /Python for Beginners/usingand.py | 283 | 4.125 | 4 | # A student makes honour roll if their average is >= 85
# and their lowest grade is not below 70
gpa = float (input('What was your Grade Point Average? '))
lg = input('What was your lowest grade? ')
lg = float(lg)
if gpa >= .85 and lg >= .70:
print('You made the honour roll')
| false |
e13878ca85b83d910224191531b5855bcdf45db2 | saebido/FTW3-Day3 | /palindrome_checker.py | 258 | 4.1875 | 4 | #Palindrome Checker
x = int (input("Enter number to check if palindrome:"))
temp = x
y = 0
while (x > 0):
z = x%10
y = y*10+z
x = x//10
if (temp == y):
print ("It is a palindrome")
else:
print ("It is not a palindrome")
| true |
c0940fe6b6b3d09a7f0e466dc77a8f8f82947e77 | diogoabnunes/FPRO | /PEs/PE2/2.1. Find the Treasure.py | 964 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 24 14:36:29 2018
@author: diogo
"""
#1. Find the treasure
#The path to the treasure is given as a sequence of commands that are steps of length 1: up , left ,
#right or down . Write a function map(pos, steps) that takes a coordinate pos , which is a
#tuple with values x and y as (x,y), and a sequence of commands in a string steps , with the
#steps separated by a hyphen, and computes the final position in the map.
#For example:
#● map((0,0), "up-up-left-right-up-up") returns the tuple: (0,4)
#● map((0,4), "up-up-left-left-up-up") returns the tuple: (-2,8)
def map(pos,steps):
x = pos[0]
y = pos[1]
steps = steps.split("-")
for step in steps:
if step == "up": y += 1
if step == "down": y -= 1
if step == "right": x += 1
if step == "left": x -= 1
return x,y
print(map((0,0), "up-up-left-right-up-up"))
print()
print(map((0,4), "up-up-left-left-up-up")) | true |
24dfa46c57011c6b9b4a103c4c0323893f947353 | rzlatkov/Softuni | /Advanced/Functions_Advanced/Recursion_Palindrome.py | 494 | 4.1875 | 4 | # Recursion Palindrome
def palindrome(word, index):
if len(word) % 2 == 0:
middle = (len(word) % 2) - 1
else:
middle = len(word) // 2
if 0 < len(word) < 2:
return f"{word} is a palindrome"
if word[index] == word[-(index+1)] and index < middle:
return palindrome(word, index+1)
if index == middle:
return f"{word} is a palindrome"
return f"{word} is not a palindrome"
print(palindrome("abcba", 0))
print(palindrome("peter", 0))
| false |
565f404c6d03a2c61752cf2fb9b3a6a3a05d6a1f | Kl1060/Python-Projects | /SimpleCalcProject2.py | 375 | 4.125 | 4 | num1, op, num2 = input("Enter an equation\n").split()
num1 = int(num1)
num2 = int(num2)
if op == '+':
ans = num1 + num2
elif op == '-':
ans = num1 - num2
elif op == '*':
ans = num1 * num2
elif op == '/':
ans = num1 / num2
else:
print(op + "is not a valid operation")
# repr takes the ans and makes it into a string to print out
print("= " + repr(ans))
| false |
d7414f1603cca21421384666a1fc8e72554bbbb9 | wangzeyao/tutorials | /numpy_pandas/numpy/numpy索引.py | 523 | 4.1875 | 4 | import numpy as np
A = np.arange(3, 15)
print(A)
print(A[3])
A = A.reshape((3, 4))
print(A)
print(A[2])
print(A[2, 1]) # 两种方法一样
print(A[2][1])
print(A[2, :]) # 第三行的所有数
print(A[2, 1:3]) # 第三行,第二个到第三个数
for row in A: # 迭代矩阵中的行
print(row)
for col in np.transpose(A): # 并不能直接用for col in A: 用转置后的矩阵迭代行
print(col)
print('flatten()函数', A.flatten())
for item in A.flat: # 将矩阵变为一行
print(item)
| false |
aa0974cfac820246ab662dd09217966de727a7ae | Suraj-sati/programming-using-python | /interchange_first_and_last_element_in_a_list.py | 242 | 4.21875 | 4 | l=[]
s=int(input("enter the size of list :"))
for i in range(0,s):
m=input("enter the element in list:")
l.append(m)
print("list before :",l)
l[0],l[-1]=l[-1],l[0]
print("list after interchanging first and last element : ",l) | true |
f796757ff52a17329568e091723a9bd0066ac2ee | Alfinus/crash_course_in_python | /chapter_6/rivers.py | 422 | 4.21875 | 4 | # 6-5 Rivers
rivers = {'nile': 'egypt', 'mississippi': 'usa', 'amazon': 'brazil',}
for river, country in rivers.items():
print("\nThe " + river.title() + " is in " + country.title() + ".")
print("\nA list of Rivers found in this dictionary: ")
for river in rivers.keys():
print(river.title())
print("\nA list of countrys found in this dictionary: ")
for country in rivers.values():
print(country.title())
| false |
a7171171cdf1a99286b2b039e1d3ed9ba81bd3fa | BenSherry/PyProject | /Alpha/sorts/python/bubble_sort.py | 719 | 4.21875 | 4 | def bubble_sort(wait_sort):
length = len(wait_sort)
for i in range(length-1):
swapped = False
for j in range(length-i-1):
if wait_sort[j] > wait_sort[j+1]:
wait_sort[j], wait_sort[j+1] = wait_sort[j+1], wait_sort[j]
swapped = True
if not swapped:
break
return wait_sort
if __name__ == "__main__":
original_number = input("input numbers and divide by space\n").strip()
wait_sort = [int(item) for item in original_number.split(" ")]
'''
equal to
wait_sort = []
for item in original_number.split(" "):
wait_sort.append(int(item))
'''
print(bubble_sort(wait_sort))
| true |
2b0ef8b9a63762ff883c44d07dbd834e2be3cf92 | xiaojie-2016/leetcode | /python3/easy_35.py | 1,637 | 4.15625 | 4 | import unittest
from typing import List
class MyTestCase(unittest.TestCase):
"""
搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素
"""
def test_something(self):
self.assertEqual(2, self.searchInsert([1, 3, 5, 6], 5))
self.assertEqual(1, self.searchInsert([1, 3, 5, 6], 2))
self.assertEqual(4, self.searchInsert([1, 3, 5, 6], 7))
self.assertEqual(0, self.searchInsert([1, 3, 5, 6], 0))
@staticmethod
def searchInsert2(nums: List[int], target: int) -> int:
"""
执行用时 :64 ms, 在所有 Python3 提交中击败了25.88%的用户
内存消耗 :13.4 MB, 在所有 Python3 提交中击败了98.71%的用户
有些费时啊,排序数组用二分查找应该更快的
"""
for x in nums:
if x >= target:
return nums.index(x)
return len(nums)
@staticmethod
def searchInsert(nums: List[int], target: int) -> int:
"""
二分法查找
"""
length = len(nums)
if length == 0:
return 0
left = 0
right = length
while left < right:
mid = int((right + left) / 2)
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid
else:
left = mid + 1
return left
if __name__ == '__main__':
unittest.main()
| false |
259bdb581bad1b48070a9768fb9d98b11cc550a2 | sharnajh/csc101 | /python/chapter10/auto_repair_payroll.py | 2,082 | 4.21875 | 4 | # CSC 101
# Sharna Hossain
# Chapter 10 | Program 2
# auto_repair_payroll.py
# Named constant to represent the tax
TAX = 0.35
OVERTIME_CAP = 40
OVERTIME_RATE = 0.2
# Create class for employees that take in values for name
# and their rate of pay according to their position
class Employee:
# __init__ is the function that when executed
# will create a new instance of the class with
# the parameters as the data
def __init__(self, name, position, hours_worked):
# Format name so it is capitalized
self.name = name.title()
self.pay_rate = position
self.hours_worked = hours_worked
# Create dictionary for employees
employees = {}
# Using a for loop to generate 5 employee objects with data
# received from input funtions
for x in (range(1, 6)):
# get employee name
employee_name = input(f"What is employee {x}'s name?\t")
# get employee pay rate
employee_pay_rate = float(input(f"What is employee {x}'s pay rate?\t"))
# get employee hours worked
employee_hours_worked = float(
input(f"How many hours did employee {x} work?\t"))
# create new instane of Employee class with the received data
employees[employee_name] = Employee(
employee_name, employee_pay_rate, employee_hours_worked)
# Display the tax rate
print(f'The tax rate is {TAX*100}%')
# looping through employees dictionary to calculate the gross and netpay of each employee and display data
for x in employees.values():
# calculate gross pay
x.gross_pay = x.hours_worked * x.pay_rate
# calculate overtime hours
overtime = x.hours_worked - OVERTIME_CAP
# using if-statement to add OT to employee's gross pay
if (overtime > 0):
x.gross_pay += ((overtime * x.pay_rate) * OVERTIME_RATE)
# calculate net pay
x.net_pay = x.gross_pay - (x.gross_pay * TAX)
# printing all of the details of each employee
print(f'{x.name} has a pay rate of ${x.pay_rate}. After working {x.hours_worked} hours, they made a gross of ${format(x.gross_pay,",.2f")} and a net of ${format(x.net_pay,",.2f")}\n')
| true |
66e99699711e467e2b36c4a3cd90e9250c441e48 | sharnajh/csc101 | /python/chapter10/hit_the_target.py | 2,404 | 4.71875 | 5 | # CSC 101
# Sharna Hossain
# Chapter 10 | Program 9
# hit_the_target.py
# Hit the Target Game
import turtle
# Importing random module to generate random target position for
# each game
import random
# Allow user to choose color of turtle
color = input("What color should the turtle be?\t")
# Using if-elif-else statements to make program more interactive
if (color == "blue" or color == "pink"):
print(f"{color} is my favorite color! Nice choice!")
elif (color == "brown" or color == "yellow"):
print(f"{color} is my not favorite color, but to each their own...")
else:
print(f'{color} has been selected')
# Changing the turtle color and fill color
turtle.pencolor(color)
turtle.fillcolor(color)
# Named constants
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
TARGET_WIDTH = 25
FORCE_FACTOR = 30
PROJECTILE_SPEED = 1
NORTH = 90
SOUTH = 270
EAST = 0
WEST = 180
# I am using range() to place target in random coordinate
# on the screen
TARGET_LLEFT_X = random.randint(1,SCREEN_WIDTH/2)
TARGET_LLEFT_Y = random.randint(1,SCREEN_HEIGHT/2)
# Setup the window
turtle.setup(SCREEN_WIDTH,SCREEN_HEIGHT)
# Draw the target
turtle.hideturtle()
turtle.speed(0)
turtle.penup()
turtle.goto(TARGET_LLEFT_X,TARGET_LLEFT_Y)
turtle.pendown()
turtle.setheading(EAST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(NORTH)
turtle.forward(TARGET_WIDTH)
turtle.setheading(WEST)
turtle.forward(TARGET_WIDTH)
turtle.setheading(SOUTH)
turtle.forward(TARGET_WIDTH)
turtle.penup()
# Center the turtle.
turtle.goto(0,0)
turtle.setheading(EAST)
turtle.showturtle()
turtle.speed(PROJECTILE_SPEED)
# Get the angle and force from the user.
angle = float(input("Enter the projectile's angle:\t"))
force = float(input("Enter the launce force (1-10):\t"))
# Calculate the distance.
distance = force * FORCE_FACTOR
# Set the heading.
turtle.setheading(angle)
# Launch the projectile.
turtle.pendown()
turtle.forward(distance)
# Did it hit the target?
if (turtle.xcor() >= TARGET_LLEFT_X and
turtle.xcor() <= (TARGET_LLEFT_X + TARGET_WIDTH) and
turtle.ycor() >= TARGET_LLEFT_Y and
turtle.ycor() <= (TARGET_LLEFT_Y + TARGET_WIDTH)):
print('Target hit!')
else:
print('You missed the target.') | true |
07f94fdd88cfa32f88df264c909a5b36e14fb874 | tiantian123/Algorithm | /Python/LeetCodePractice/23_Merged_sorted_list.py | 1,298 | 4.28125 | 4 | #!/usr/bin/env python
# -** coding: utf-8 -*-
# @Time: 2020/4/27 0:12
# @Author: Tian Chen
# @File: 23_Merged_sorted_list.py
"""
23. Merge K sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists: return -1
n = len(lists)
return self.merge(lists, 0 , n-1)
def merge(self, lists, left, right):
if left == right:
return lists[left]
mid = left + ((right - left) >> 1)
list1 = self.merge(lists, left, mid)
list2 = self.merge(lists, mid + 1, right)
return self.merge2lists(list1, list2)
def merge2lists(self, lists1, lists2):
if not lists1: return lists2
if not lists2: return lists1
if lists1.val < lists2.val:
lists1.next = self.merge2lists(lists1.next, lists2)
return lists1
else:
lists2.next = self.merge2lists(lists2.next, lists1)
return lists2
| true |
401a15a3f4e3e597a369f5712e45f3a45b9a5881 | rbuerki/reference-code-python-programming | /algorithms/1_algorithmic_toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py | 1,928 | 4.125 | 4 | # Uses python3
import sys
def binary_search_recursive(a: list, x: int, i_mod: int = 0) -> int:
"""Return the index of the search item x, or -1 if not found.
No guarantees as to *which* index of the search item is returned,
if multiple exist.
Attention: In the recursive implementation, we have to keep track
of the orginial indices everytime we discard from the left.
Else we could not return the final original index of x!
"""
while len(a) > 0:
i_mid = len(a) // 2
if a[i_mid] == x:
return i_mid + i_mod
if a[i_mid] < x:
# Need to modify i_mod because discarding elements from left
return binary_search_recursive(a[i_mid + 1 :], x, i_mod + i_mid + 1)
elif a[i_mid] > x:
return binary_search_recursive(a[:i_mid], x, i_mod)
# If x is not found
return -1
def binary_search_iterative(a: list, x: int) -> int:
"""Return the index of the search item x, or -1 if not found.
No guarantees as to *which* index of the search item is returned,
if multiple exist.
"""
i_low, i_high = 0, len(a) - 1
while i_low <= i_high:
i_mid = i_low + (i_high - i_low) // 2 # can't overflow
# i_mid = (i_low + i_high) // 2 # may overflow
if a[i_mid] == x:
return i_mid
elif x < a[i_mid]:
i_high = i_mid - 1
else:
i_low = i_mid + 1
# If x is not found
return -1
def linear_search(a, x):
"""If the item is not found, return -1."""
for i in range(len(a)):
if a[i] == x:
return i
return -1
if __name__ == "__main__":
input = sys.stdin.read()
# input = "5 1 5 8 12 13 5 8 1 23 1 11"
data = list(map(int, input.split()))
n = data[0]
m = data[n + 1]
a = data[1 : n + 1]
for x in data[n + 2 :]:
print(binary_search_iterative(a, x), end=" ")
| true |
86a32918c2d82a435042553c90529198f6dabc58 | MARGARITADO/Mision_04 | /Triangulos.py | 1,388 | 4.25 | 4 | #Autor: Martha Margarita Dorantes Cordero
#Identificar tipo de triángulo
def identificarTipo(l1, l2, l3) :
#Función que realiza la operación requerida para identificar el tipo de triángulo con las medidas recibidas.
#Si todos los lados son iguales es un equilátero.
#Si dos de los lados son iguales es un isósceles.
#Si todos los lados son diferentes es un escaleno.
if((l1 == l2) and (l2 == l3)) :
return "equilátero"
elif((l1 == l2) or (l1 == l3) or (l2 == l3)) :
return "isósceles"
elif((l1 != l2) or (l1 != l3) or (l2 != l3)) :
return "escaleno"
else :
return "otro"
def main() :
#Función principal que solicita la longitud de cada uno de los lados de un triángulo y llama a la función
#previamente definida para identificar el tipo de triángulo.
#Si alguno de los lados tiene una longitud de 0 o negativa, se imprime la leyenda de que el triángulo no existe.
lado1 = float(input("\n Ingrese la longitud del primer lado del triángulo: "))
lado2 = float(input(" Ingrese la longitud del segundo lado del triángulo: "))
lado3 = float(input(" Ingrese la longitud del tercer lado del triángulo: "))
if((lado1 <= 0) or (lado2 <= 0) or (lado3 <= 0)) :
print("\n El triángulo con las medidas ingresadas no existe.")
else :
print('\n Las medidas ingresadas corresponden a un triángulo %s.'%(identificarTipo(lado1, lado2, lado3)))
main() | false |
42fec4904b190093af65cccac4427781abab3148 | hibalubbad/hiba.baddie | /asst4_hil00/guess.py | 507 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 2 14:56:40 2018
@author: misskeisha
"""
number = input("think of an integer between one and a thousand")
low = 1
high = 1000
while high >= low:
print("My number is less than or equal to" + str((high + low) // 2))
request = input()
if request == "True":
high = (high + low) // 2
else:
low = (high + low) // 2 + 1
if high == low:
print(" your number is:", high)
break
| true |
e1fec65598af301683a0c8c66fe3d42bdaae4445 | hibalubbad/hiba.baddie | /asst5_hil00/snowflake.py | 589 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 14 11:53:10 2018
@author: misskeisha
"""
import turtle
order = int(input())
length = int(input())
def fractal(order, length):
if order == 0:
turtle.forward(length)
else:
for i in [60, -120, 60,0]:
fractal(order-1, length/3)
turtle.left(i)
def snowflake(order, length):
fractal(order, length)
turtle.left(-120)
fractal(order, length)
turtle.right(120)
fractal(order, length)
turtle.speed(200)
snowflake(order, length) | false |
72080eeebb225bb825e4c5db80956e113b8fe28c | IkeHunter/Coding_Challenge_9-18 | /challenge_2.py | 950 | 4.5 | 4 | """
Create a program that contains a function that takes at least 3 parameters:
the maximum range and at least 2 other numbers.
The function needs to find the sum of all the numbers within
the max range and that are divisible by any of numbers
(or if there is more than one argument, the number has to be
divisible by any of them).
INPUT: ‘function_name(3, 5)’
OUTPUT: 233168
INPUT: ‘function_name(2, 3, 8)’
OUTPUT: 333167
"""
def sum_of_multiples(*args):
multiples = []
multiples_sum = 0
for arg in args:
for i in range(arg, 1000, arg):
if i not in multiples:
multiples.append(i)
for multiple in multiples:
multiples_sum += multiple
return multiples_sum
answer = sum_of_multiples(3, 5) # INPUT 1
print("Answer 1: " + str(answer)) # OUTPUT 1: 233168
second_answer = sum_of_multiples(2, 3, 8) # INPUT 2
print("Answer 2: " + str(second_answer)) # OUTPUT 2: 333167
| true |
3de0274b7ed80d504e253ea41b2f9c6fd81e24ab | MatthewKosloski/student-information-system | /utils/create_ordered_list.py | 439 | 4.21875 | 4 | '''
Creates an ordered list of items starting
at zero.
Example:
0. Uno
1. Dos
2. Tres
@param items {list}
@return output {str}
'''
def create_ordered_list(items):
output = ''
for item in items:
current_index = items.index(item)
output += str(current_index)
output += '. '
output += item
# Don't append a newline after the last list item
output += ('' if current_index == (len(items) - 1) else '\n')
return output | true |
7184f7606886ddd26bd63049d1bd5c7c7fb50a24 | robobyn/code-challenges | /travel-itinerary.py | 2,067 | 4.46875 | 4 | '''
Given a series of plane tickets, each showing a departure airport and destination,
print the itinerary for the given trip.
Trip is one way, no round trips. Assumption is that input is valid, and no
plane tickets are missing.
FROM->TO
Input:
SFO->NYC
HYD->HKG
NYC->LON
LON->HYD
Output:
SFO
NYC
LON
HYD
HKG
Print output to console
{SFO: [NYC],
HYD: [HKG],
NYC: [LON]....}
Check for data that is in keys, but not values of dict:
use a conditional that uses dict.keys() method and dict.values() method
loop through keys - for each key, is it in values? if not it is the starting travel destination
Loop starting at this special key, print key, then look up the value of 1st key print that, then continue the process until you reach an item that is not listed as a key.
'''
def print_itinerary(travel_tickets):
"""Print itinerary for trip given series of plane tickets.
Parameters: travel_tickets is a list of tuples. Index 0 of each tuple will
be departure airport, index 1 will be destination from current ticket.
Returns: None - prints travel points in sequence."""
travel_points = {}
# create dictionary of start and end points for fast lookup
# start points are keys, end points are values
for ticket in travel_tickets:
start_point = ticket[0]
end_point = ticket[1]
if start_point not in travel_points:
travel_points[start_point] = end_point
current = None
# search for first airport in trip
# if airport code is a start point, but not end point, it is first in trip
for airport in travel_points:
if airport not in travel_points.values():
current = airport
# print each airport code in sequence of trip
# stop looping when airport reached that is an end point but not start point
while True:
print current
if current in travel_points.keys():
current = travel_points[current]
else:
break
print_itinerary([('SFO', 'NYC'), ('HYD', 'HKG'), ('NYC', 'LON'), ('LON', 'HYD')])
| true |
9908f930ef7d52232e3ee9275eb22269e998c7a8 | robobyn/code-challenges | /btree-second-largest-value.py | 2,387 | 4.3125 | 4 | """Find the 2nd largest element in a binary search tree."""
class B_Tree_Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_left(self, value):
self.left = B_Tree_Node(value)
return self.left
def insert_right(self, value):
self.right = B_Tree_Node(value)
return self.right
def find_largest_element(root_node):
"""Function to find largest element in BST given root node.
Input: root_node should be from B_Tree_Node class.
Function assumes BST is valid and properly ordered.
Returns: Node with largest value in BST."""
current = root_node
while current.right:
current = current.right
return current
def find_2nd_largest_element(b_tree_node):
"""Function to find 2nd largest element in a BST.
Input: b_tree_node should be root node of BST from B_Tree_Node class.
Function assumes binary tree is valid and in correct order.
Returns: Node with 2nd largest value in tree."""
current = b_tree_node
# loop unless current node is None
while current:
# if there is no right node but there is a left node in the tree
# 2nd largest element will be the largest element of the left tree
if current.left and not current.right:
return find_largest_element(current.left)
# if current has a right node that is a leaf
# then current is the second largest element of tree
if current.right and not current.right.left and not current.right.right:
return current
# keep going right until 2nd largest element found
# no need to traverse entire tree if BST structured properly
current = current.right
root_node = B_Tree_Node(8)
six = B_Tree_Node(6)
ten = B_Tree_Node(10)
four = B_Tree_Node(4)
nine = B_Tree_Node(9)
seven = B_Tree_Node(7)
eleven = B_Tree_Node(11)
root_node.left = six
root_node.right = ten
six.left = four
six.right = seven
ten.left = nine
ten.right = eleven
print find_largest_element(root_node).value
print find_2nd_largest_element(root_node).value
unbalanced = B_Tree_Node(10)
five = B_Tree_Node(5)
six = B_Tree_Node(6)
two = B_Tree_Node(2)
unbalanced.left = five
five.right = six
five.left = two
print find_largest_element(unbalanced).value
print find_2nd_largest_element(unbalanced).value
| true |
d6de3e78580b6250fe66b26dbdf84e0c7df2018a | robobyn/code-challenges | /find-rotation.py | 2,199 | 4.21875 | 4 | """In a mostly alphabetical list of words - find the 'rotation point' where the
list jumps back to an earlier point in the alphabet."""
def find_rotation(alpha_words):
"""Finds rotation point in list of words.
Input: list of words that is mostly alphabetical but jumps back to an
earlier letter in alphabet at an arbitrary index of list.
Returns: Numerical index of list's rotation point. Returns None if no
rotation point found."""
for i in range(len(alpha_words) - 1):
current = alpha_words[i]
next_word = alpha_words[i + 1]
if current > next_word:
return i + 1
return None
print find_rotation([
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote', # <-- rotates here!
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
])
def logn_find_rotation(alpha_words):
"""Finds rotation point in list of words - same as find_rotation() but
uses binary search to do this in log(n) time."""
if not alpha_words:
return "No words in this list!"
high_index = len(alpha_words) - 1
low_index = 0
mid_index = len(alpha_words) / 2
while high_index > low_index:
current = alpha_words[mid_index]
prev_word = alpha_words[mid_index - 1]
next_word = alpha_words[mid_index + 1]
first_word = alpha_words[low_index]
if prev_word > current:
return mid_index
elif next_word < current:
return mid_index + 1
if current < first_word:
high_index = mid_index - 1
else:
low_index = mid_index + 1
mid_index = (high_index + low_index) / 2
return None
print logn_find_rotation([
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote', # <-- rotates here!
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
])
print logn_find_rotation([
'asymptote',
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
])
| true |
4248e430d38f3ecc4af14d3cf802b668b5a2c2ea | robobyn/code-challenges | /odd-int-even-index.py | 646 | 4.59375 | 5 | def odd_int_even_index(elements):
"""Return all odd integers and elements with even index from input list.
Args: List could contain elements other than ints.
Challenge: Must use a generator expression with one line of code.
>>> odd_int_even_index(["ball", 5, 1, "cat", 8, True, "no", 9, 4])
['ball', 5, 1, 8, 'no', 9, 4]
>>> odd_int_even_index([7, 1, 7, 8, 0, 2, 8, 3, 4, 6, 5])
[7, 1, 7, 0, 8, 3, 4, 5]
"""
return list(element for index, element in enumerate(elements) if (type(element) is int and element % 2 !=0) or index % 2 == 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
ba072599d7c6530338377f2a35f0734272b7556a | MishiCodes/Python | /shoppingl-list.py | 1,412 | 4.21875 | 4 | print ("Welcome to the Shopping List application")
"""Dictionary to get individual item details"""
current_item = {}
"""List to keep track of items"""
grocery_history = []
stop = False
"""iterates to get items details until user press 'n'"""
while not stop:
name = input("Enter item name: ")
quantity = int(input("Enter item quantity: "))
cost = float(input("Enter item cost: "))
"""Populating dictionary with item details"""
current_item = {
'item_name': name,
'item_quantity': quantity,
'item_cost': cost
}
"""Populating list with items"""
grocery_history.append(current_item)
"""Getting user response whether they need to continue adding items or quit"""
response = input(("Would you like to enter another item?\n Enter 'y' to continue and 'n' to exit: "))
if response == 'n':
stop = True
grand_total = 0
"""Iterating over grocery list to calculate each item total and total bill"""
for item in grocery_history:
item_total = item['item_quantity'] * item['item_cost']
grand_total += item_total
"""Printing item name with cost of each item and total for each item"""
print("%d %s for %.2f each %.2f" % (item['item_quantity'], item['item_name'], item['item_cost'], item_total))
print()
item_total = 0
print ('-' * 35)
"""Printing total bill"""
print("Total %.2f sek" % grand_total)
| true |
77afcc9fb12fe02000e8d16b90202821566d3ffb | jrrobedillo/Activities | /dictionary.py | 735 | 4.21875 | 4 | books = {
"Harry Potter" : "J.K Rowling",
"The Fault in Our Stars" : "John Green",
"The Hunger Games" : "Suzanne Collins",
"Divergent" : "Veronica Roth",
"Thirteen Reasons Why" : "Jay Asher",
"Percy Jackson" : "Rick Riordan",
"Throne of Glass" : "Sarah J. Maas",
"Red Queen" : "Victoria Aveyard",
"City of Bones" : "Cassandra Clare",
"The Hobbit" : "J.R.R Tolkien"
}
#prints all keys and values of the dictionary
for key,val in books.items():
print (key, ">>", val)
#adds elements in the dictionary
books['To Kill a Mockingbird'] = 'Harper Lee'
books['The Book Thief'] = 'Markus Zusak'
books['Ready Player One'] = 'Ernest Cline'
print ("-"*10)
#sorts elements in the dictionary
for key, value in sorted(books.items()):
print (key,">>", value)
| true |
e2c031e30bb4eaa3b0616f3a1f5780d9362f7fa8 | rapidtundra/hello-world | /calendar_calculator.py | 669 | 4.375 | 4 | import calendar
def calculate_weekday(year,month,day):
'''Given a year, month and day, returs back the weekday
>>> calculate_weekday(2016, 7, 29)
Friday
'''
if calendar.weekday(year,month,day) == 0:
print("Monday")
elif calendar.weekday(year,month,day) == 1:
print("Tuesday")
elif calendar.weekday(year,month,day) == 2:
print("Wednesday")
elif calendar.weekday(year,month,day) == 3:
print("Thursday")
elif calendar.weekday(year,month,day) == 4:
print("Friday")
elif calendar.weekday(year,month,day) == 5:
print("Saturday")
else:
print("Sunday")
| false |
d991d46a32172c80da16bba4e6b1b233b22f32f9 | n0thing233/n0thing233.github.io | /noodlewhale/verizon/multithreading/1188. Design Bounded Blocking Queue.py | 904 | 4.21875 | 4 | #只用lock实现的话,相当于同时只有一个thread可以操作这个queue,但事实上一个完美的实现是我们想让很多thread同时
#明显不能直接用queue,至少要自己实现一个blocking的logic
#从题目可以看出来要实现两个功能:1.bounded.2 blocking
from threading import Semaphore
from time import time
class BoundedBlockingQueue(object):
def __init__(self, capacity: int):
self.q = collections.deque()
self.capacity = capacity
self.count = 0
self.e_s = Semaphore(capacity)
self.d_s = Semaphore(0)
def enqueue(self, element: int) -> None:
self.e_s.acquire()
self.q.append(element)
self.d_s.release()
def dequeue(self) -> int:
self.d_s.acquire()
res = self.q.popleft()
self.e_s.release()
return res
def size(self) -> int:
return len(self.q)
| false |
50e051b00e26b4ac2b3acc0985c2c373dc046822 | EllieSky/PythonBC_Winter2021 | /tests/homework2_part2.py | 1,930 | 4.1875 | 4 | import unittest
'''
Part 2
A: Create the following functionality:
A school has following rules for grading system:
a. Below 45 - F
c. 45 to 50 - D
d. 50 to 60 - C
e. 60 to 80 - B
f. Above 80 - A
Create a function which takes a student's test score as input.
The function should determine the student's grade based on the score.
The function should respond with the letter which represents the student's grade.
'''
class StudentGradeTestCase(unittest.TestCase):
def test_get_grade(self):
self.assertEqual('A', get_grade(100))
self.assertEqual('A', get_grade(80.01))
self.assertEqual('B', get_grade(80))
self.assertEqual('B', get_grade(60))
self.assertEqual('C', get_grade(59.9))
self.assertEqual('C', get_grade(50.0))
self.assertEqual('D', get_grade(49.00))
self.assertEqual('D', get_grade(45.00))
self.assertEqual('F', get_grade(44))
self.assertEqual('F', get_grade(1))
self.assertEqual('F', get_grade(-11))
self.assertEqual('A', get_grade('100'))
self.assertEqual('A', get_grade('99.0'))
self.assertEqual('A', get_grade('99.99'))
self.assertRaises(TypeError, lambda: get_grade('SS.00'))
self.assertRaises(TypeError, lambda: get_grade('Ninety'))
def get_grade(test_score):
if type(test_score) == str:
test_score = test_score.split('.')[0]
if test_score.isdigit():
test_score = float(test_score)
else:
raise TypeError("test_score must be numerical")
elif type(test_score) != int and type(test_score) != float:
raise TypeError("test_score must be numerical")
if test_score < 45:
return 'F'
elif test_score > 80:
return 'A'
elif 50 > test_score >= 45:
return 'D'
elif 60 > test_score >= 50:
return 'C'
else:
return 'B'
if __name__ == '__main__':
unittest.main()
| true |
a93cdee55e15ab8c9262a9e1ae20c59ccbac5d78 | EllieSky/PythonBC_Winter2021 | /tests/loop_example.py | 2,110 | 4.25 | 4 | # reversed()
# list()
# tuple()
# range()
# enumerate()
# len()
alist = list("abcdefghijklmn")
for index, item in enumerate(alist):
print(index)
print("multiply letters:", item * index, sep="...")
for index in range(10):
print(index)
print("squared:", index * index, sep="...")
# exchange values
x = 12
y = 2
# solution
a = x
x = y
y = a
def count_odd_even(lst):
even_count = 0
odd_count = 0
for num in lst:
if type(num) is float or type(num) is int:
if num % 2 == 0:
even_count = even_count + 1
else:
odd_count = odd_count + 1
print("Total count of odd number:", odd_count)
print("Total count of even number:", even_count)
return {'odd': odd_count, 'even': even_count}
# count odd/even numbers in the list
count_odd_even([3, 6, 9, 4, 7])
count_odd_even([])
count_odd_even([1, 1, 1, 1, 1, 1])
count_odd_even([2, 0, 4, -2])
count_odd_even([None, None])
count_odd_even(['a', 'b', 1, 4, 2])
count_odd_even([False, True, 3, 5, 2])
lst = [3, 6, 9, 4, 7]
# if length is odd middle will be rounded down
# if length is even middle will be exact
middle = int(len(lst) / 2)
print("\nLIST:", *lst)
for index, item in enumerate(lst):
if index >= middle:
break
a = lst[index]
lst[index] = lst[-1-index]
lst[-1-index] = a
print("REVERSED:", *lst)
### VARIATION of reverse list
print("\nLIST:", *lst)
for index, item in enumerate(lst):
if index >= middle:
break
lst[index] = lst[-1-index]
lst[-1-index] = item
print("REVERSED:", *lst)
### ANOTHER VARIATION of reverse list
print("\nLIST:", *lst)
for index in range(middle):
a = lst[index]
lst[index] = lst[-1 - index]
lst[-1 - index] = a
print("REVERSED:", *lst)
## Christmas Tree Example:
## *
## ***
## *****
## *******
## |
def print_christmas_tree(height):
for less_space in range(height):
print(' '*(height - less_space) + '*' * (less_space * 2 + 1))
# the trunk
print(' '*height + '|')
# print_christmas_tree(3)
print_christmas_tree(7)
| false |
be02e95426b3e572b0565726916c106fd26c2eab | edwardhkm/PythonCrashCourse | /7-1.py | 1,629 | 4.15625 | 4 | # 7-1
car = input("What kind of car you like? ")
print(f"Let me see if I can find you a {car}")
# 7-2
num_people = int(input("How many people you have today? "))
if num_people >= 8:
print(f"You have to wait.")
else:
print(f"Your table is ready.")
# 7-3
num = int(input("Give me a number: "))
if num % 10 == 0:
print(f"It is divisible by 10.")
else:
print(f"It cannot divisible by 10.")
# 7-4
active = True
while active:
topping = input("Please input topping(Type quit to exit): ")
if topping == 'quit':
active = False
else:
print(f"Topping is: {topping}")
# 7-5
active = True
while active:
age = input("What is your age? ")
if age != 'quit':
if int(age) < 3:
print(f"Ticket is free.")
elif int(age) < 12:
print(f"Ticket is 10.")
else:
print(f"Ticket is 15")
else:
break
# 7-8
sandwich_orders = ['egg', 'becon', 'mixed', 'ham']
finished_sandwiches = []
for sandwich in sandwich_orders:
print(f"I made your {sandwich}.")
finished_sandwiches.append(sandwich)
for sandwich in finished_sandwiches:
print(f"{sandwich} sandwich made.")
# 7-9
finished_sandwiches = []
sandwich_orders = ['egg', 'becon', 'mixed', 'ham', 'pastrami', 'pastrami', 'pastrami']
print("Running out of pastrami sandwich. Please remove them.")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
for sandwich in sandwich_orders:
print(f"I made your {sandwich} sandwich.")
finished_sandwiches.append(sandwich)
for sandwich in finished_sandwiches:
print(f"{sandwich} sandwich made.") | true |
51f09a77704ef390ccda6613e0a329a871cddf9f | edwardhkm/PythonCrashCourse | /4-10.py | 831 | 4.40625 | 4 | # 4-10
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print(f"The first 3 items in the list are : {my_foods[:3]}")
print(f"Three items from the middle of the list are: {my_foods[3:]}")
print(f"The last three items in the list are: {my_foods[-3:]}")
# 4-11
pizzas = ['Hawaii', "Meat lover", "Vege", "tradition", "BBQ Meats Deluxe", "Garlic Chicken"]
friend_pizzas = pizzas[:]
pizzas.append("Alo")
friend_pizzas.append("Bacon")
print(f"My favorite pizzas are:")
for pizza in pizzas:
print(f'\t{pizza}')
print(f'My friend favorite pizzas are:')
for pizza in friend_pizzas:
print(f'\t{pizza}')
# 4-12
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
friend_foods.append("ice cream")
for food in my_foods:
print(food)
print("\n")
for food in friend_foods:
print(food)
| false |
6805b522b567519e30461af560ec2bb070c13672 | edwardhkm/PythonCrashCourse | /first_numbers.py | 225 | 4.3125 | 4 | for value in range(1,5):
print(value)
print("\n")
# if you want to print 1 to 5
for value in range(1,6):
print(value)
print("\n")
for value in range(6):
print(value)
numbers = list(range(1,6))
print(numbers)
| true |
894b5c5173ae36086a06b7d71dd5d83546b765ec | swapnilvishwakarma/100_Days_of_Coding_Challenge_Part-2 | /8.Flatten_Binary_Tree_to_Linked_List.py | 1,506 | 4.375 | 4 | # Given the root of a binary tree, flatten the tree into a "linked list":
# The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
# The "linked list" should be in the same order as a pre-order traversal of the binary tree.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: TreeNode):
"""
Do not return anything, modify root in-place instead.
"""
if root is not None:
self.flatten(root.left)
self.flatten(root.right)
if root.left is not None:
current = root.left
while current.right is not None:
current = current.right
current.right = root.right
root.right = root.left
root.left = None
return root
def printPreorder(root):
if root is None:
return
print(root.val)
printPreorder(root.left)
printPreorder(root.right)
# [1,2,5,3,4,null,6]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(None)
root.right.right = TreeNode(6)
sol = Solution()
sol.flatten(root)
print(printPreorder(root)) | true |
761ce311a5fb5e712c49cd09dcba598e97ec2f6a | tenrenjun/python_experimental-task | /Experimental task/CH2_Task6.py | 478 | 4.125 | 4 | # 新建字典
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])
# 添加元素
d['Adam'] = 67
print(d['Adam'])
d['Jack'] = 90
print(d['Jack'])
# 修改某个key对应的value
d['Jack'] = 88
print(d['Jack'])
# 3种方式判断'Thomas'是否为d的一个key
print('Thomas' in d)
print(d.get('Thomas')) # 如果字典不包含该key则返回None
print(d.get('Thomas', 1)) # 如果字典不包含该key则返回-1
# 删除元素
d.pop('Bob')
print(d) | false |
dc3916ee7deab51f5b5f761b60caafc504987d40 | aowens-21/python-sorts | /bubble.py | 370 | 4.34375 | 4 | def bubble_sort(list):
# This function will take in a list and sort it in ascending order
# using the bubble sort algorithm
for i in range(len(list) - 1):
for j in range(len(list) - i - 1):
if (list[j + 1] < list[j]):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
return list
| false |
9fa2c6abed51dc8d9c68bec958406ef10e73157c | Douglass-Jeffrey/Unit-3-07-Python | /dating_eligibility.py | 580 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Oct 2019
# This program determines if you are of the right age to date a grandmothers
# granddaughter
def main():
# process
try:
# input
age = int(input("Enter your age:"))
print("")
# Output
if age > 25 and age < 40:
print("You are a suitable fit for my granddaughter!!")
else:
print("You are not good enough for my granddaughter!!")
except Exception:
print("Please input a proper age")
if __name__ == "__main__":
main()
| true |
2f2dd98818822664a89cd275e8e26edfbf0d9286 | peppermint44/eulerian | /problem-4.py | 717 | 4.25 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91*99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def reverse(a):
b=0
while a>0:
c=a%10
b=b*10+c
a=a/10
return b
def is_palindrome(a):
return reverse(a) == a
def largest_palindrome_as_product(low,high):
largest_palindrome=0
for x in range (low,high):
for y in range (low,high):
z=x*y
if is_palindrome(z):
if z>largest_palindrome:
largest_palindrome=z
return largest_palindrome
print(largest_palindrome_as_product(100,1000)) | true |
7e56d4685227decfee31b1786f9de6321591bb55 | madmonkyang/cda-record | /personal/pythonic/rules/rule2.py | 825 | 4.3125 | 4 | # ---------------- 避免劣化代码 ----------------
"""
1)避免只用大小写来区分不同的对象
2)避免使用容易引起混淆的名称,如 element, list, dict
3)不要害怕过长的变量名(不追求过分缩写)
"""
# Bad:
# 不推荐使用 list, element 这种变量名
def funA(list, num):
for element in list:
if num == element:
return True
else:
pass
# Good:
def find_num(search_list, num):
for listValue in search_list:
if num == listValue:
return True
else:
pass
# ---------------- 深入认识Python ----------------
"""
不好的风格:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
Pythonic风格:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
"""
| false |
d3b665f9c3f533dfbb863f9e36802117c910e773 | todaygood/python_repo | /basic/string/in_str.py | 314 | 4.125 | 4 | #!/usr/bin/python
str="hello,world"
if "hello" in str:
print("yes ,in")
else:
print("no")
str="hello,world"
if str.strip()=="":
print("str is null")
if not str.strip():
print("str is null")
str=" "
if str.strip()=="":
print("str is null")
if str.strip():
print("str is not null")
| false |
dc00389dd2541cd2a91f89fa632e8c79d0c307a5 | Pythonierista/EPAM_hometasks | /task_11_ex_3.py | 629 | 4.1875 | 4 | """
Task 3
Implement a decorator `call_once` which runs `sum_of_numbers` function once and caches the result.
All consecutive calls to this function should return cached result no matter the arguments.
Example:
@call_once
def sum_of_numbers(a, b):
return a + b
print(sum_of_numbers(13, 42))
>>> 55
print(sum_of_numbers(999, 100))
>>> 55
print(sum_of_numbers(134, 412))
>>> 55
"""
def call_once(fn, memo=[]):
if not memo:
def f(*args):
memo.append(fn(*args))
return memo[0]
return f
else:
return memo[0]
@call_once
def sum_of_numbers(a, b):
return a + b
| true |
06dc859201a8cb8c04350e1e76fbee22ff78579d | Pythonierista/EPAM_hometasks | /task_4_ex_2.py | 699 | 4.3125 | 4 | """
Task04_1_2
Write `is_palindrome` function that checks whether a string is a palindrome or not
Returns 'True' if it is palindrome, else 'False'
To check your implementation you can use strings from here
(https://en.wikipedia.org/wiki/Palindrome#Famous_palindromes).
Note:
Usage of any reversing functions is prohibited.
The function has to ignore special characters, whitespaces and different cases
Raise ValueError in case of wrong data type
"""
def is_palindrome(s) -> bool:
if isinstance(s, str):
s = ''.join([i for i in s if i.isalnum()]).upper()
return s == ''.join([s[-i] for i in range(1, len(s) + 1) if s[-i].isalnum()]).upper()
else:
raise ValueError
| true |
7344c7f0fac0f84765803ee9a64aa4ac09e1661c | EvilDoof/Python-programming | /File editing/wordcount.py | 251 | 4.25 | 4 | name = input("Enter the file name: ")
fname = open(name)
words = list()
for line in fname:
line = line.rstrip()
piece = line.split()
for word in piece:
if word not in words:
words.append(word)
words.sort()
print(words)
| true |
64d58902827bfd2f3379c1365e6e83e7d4d4f1b8 | jgross21/Programming | /Notes/Chapter 4.py | 2,940 | 4.5625 | 5 | # Chapter 4 - Loops and Random Numbers
# FOR loop
# Useful for repeating code a specific number of times
for i in range(10):
print('Hello')
print('Goodbye')
print('This will print once')
#We can use the index in the loop
for i in range(10):
print(i)
# We can even adjust the range
for j in range(1, 11):
print(j)
# We can do steps
for k in range(5, 50, 5):
print(k)
# We can go backwards and negative
for i in range(5, -5, -3):
print(i)
# Nested loops
for i in range(10):
print('i')
for j in range(10):
print('j')
# Import time
for h in range(24):
for m in range(60):
for s in range(60):
print(h, m, s)
# time.sleep(1)
# Running Totals
# add all the numbers up from 1 to 100
total = 0
for i in range(101):
total +=i
print(total)
# add user input numbers together
total = 0
for i in range(3):
my_number = int(input('Number: '))
total += my_number
print (total)
# Random Number
import random
my_number = random.randrange(10)
print(my_number)
# randrage follows same format as range() in a FOR loop
print(random.randrange(10, 21)) # int from 10 to 20
print(random.randrange(0, 51, 5)) # random multiple of 5 from 0 to 50
# Sometimes you need a float
print(random.random()) # random float from 0 approaching 1.000000
print(random.random() * 10) # Random float from 0 to 10.0000
print(random.random() * 5 + 5) # Random float from 5 to 10.000
print(random.random() * 10 - 5) # random float from -5 to 5
# WHILE loop
# Has more flexibility than for loop
# WHILE loop continues until a condition is satisfied
# Looks similar to IF condition
# for loop
for i in range(10):
print(i)
# While loop
i = 0 # Establish a condition you can check
while i <10:
print(i) # The location of a print or code is important
i+=1
for i in range(5, 15):
print(i)
i = 5
while i < 15:
print(i)
i +=1
for i in range (5, -10, -2):
print(i)
while i > -10:
print(i)
i-=2
#The game loop
done = False
while not done:
answer = input('Do you want to quit?')
if answer.upper() == 'YES' or answer.upper() == 'Y':
done = True
else: print('I hope you are endoying the game.')
print('Game Over')
# The problem with while loops
x = 5
while x > 0:
print('Hi')
x = 10
while x > 0:
x += 1
# Roll a die
import random
sixes = 0
for i in range(1000):
die = random.randrange(1,7)
print(die)
if die == 6:
sixes += 1
print('You rolled', sixes, 'sixes.')
# Roll 2 die added together 100000 times
#Find \# of sixes
import random
sixes = 0
rolls = 100000
for i in range(rolls):
die1 = random.randrange(1,7)
die2 = random.randrange(1,7)
if die1 + die2 == 6:
sixes += 1
print(round(sixes / rolls * 100, 3), end = '%')
# For problem set
import random
flip = random.randrange(2)
if flip == 1:
pass
# do something
else:
pass
# do something else | true |
30c5bc741352bcd01c77d36ca33ecd8bea927605 | insaanehacker/Learn_Python | /Translator.py | 2,931 | 4.40625 | 4 | # Lets build a simple program that can able to translate vowels to "s"
# vowels.........aeiou
def Translate(phrase): # Here we define function as Translate and phrase value
Translator = "" # We set translator to empty string initially
for letter in phrase: # This will take each letter in phrase
if letter in "aeiou": # This will compare each letter in phrase with "aeiou", if condition matches
Translator = Translator + "s" # If we find vowels in phrase, replace the letter by s
else:
Translator = Translator + letter # Just print the actual word or letter, this means condition fails here
return Translator
print(Translate("I love you")) # We specify the parameter as phrase "I love you" and we call the function
# But we can modify this program
phrase = input("Enter the phrase: ") # This will get phrase from the user
def Translate(phrase): # Here we define function as Translator and pass phrase value
Translator = "" # We set translator to empty string initially
for letter in phrase: # This will take each letter in phrase
if letter in "aeiouAEIOU": # This will compare each letter in phrase with "aeiou" or "AEIOU", if condition matches
if letter.lower() in "aeiou": # This will check the letter is lowercase
if letter.isupper(): # This will check the letter is upper case
Translator = Translator + "S" # If we find vowels in phrase, replace the letter by S
else:
Translator = Translator + "s" # If we find vowels in phrase, replace the letter by s
else:
Translator = Translator + letter # Just print the actual word or letter, this means condition fails here
return Translator
print(Translate(phrase)) # We specify the parameter as phrase and we call the function
# New my phrase
phrase = input("Enter the phrase: ") # This will get phrase from the user
def Translate(phrase): # Here we define function as Translator and pass phrase value
Translator = "" # We set translator to empty string initially
for letter in phrase: # This will take each letter in phrase
if letter in "aeiouAEIOU": # This will compare each letter with "aeiou" or "AEIOU", if condition matches
if letter.islower(): # This will check the letter is lower case
Translator = Translator + "s" # If we find vowels in phrase, replace the letter by s
else: # If the letter is not lower case, execute below code
Translator = Translator + "S" # If we find vowels in phrase, replace the letter by S
else:
Translator = Translator + letter # Just print the actual word or letter, this means condition fails here
return Translator
print(Translate(phrase)) # We specify the parameter as phrase and we call the function | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.