blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ba2ce236426a14d35f10540770106ef7e14735a2 | maheboob76/ML | /Basics/Perceptron_vs_Sigmoid.py | 1,077 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
http://neuralnetworksanddeeplearning.com/chap1.html#exercise_263792
Small example to show difference between a perceptron and sigmoid neuron
For a Machine Learning model to learn we need a mechanism to adjust output of model by small adjustments in input. This example shows
why a percptron is unsuitable for learning tasks and how sigmoid neuron is different.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
B = 1
X = 1
N = 10
STEP = 1
W = [i for i in range(-N, N+1, STEP)]
def perceptron(w):
z = w * X + B
out = 0
if z > 0:
out =1
else:
out = 0
return out
def sigmoid(w):
z = w * X + B
out = 1.0/(1.0+np.exp(-z))
return out
y_perc = [perceptron(i) for i in W]
y_sig = [sigmoid(i) for i in W]
plt.plot(W, y_perc, '--o')
plt.plot(W, y_sig, '--X')
plt.title('Perceptron vs Sigmoid Neuron')
plt.xlabel('Input Weight')
plt.ylabel('Output Y')
plt.legend(['Perceptron', 'Sigmoid'], loc='upper left')
plt.show()
| true |
0feaf36241b524d9dc47f5b980aa9219471e2a55 | dilsonm/CeV | /mundo1/ex035.py | 545 | 4.21875 | 4 | """
Desenvolva um programa que leia o comprimento de três retas e diga ao usuário
se elas podem ou não formar um triangulo.
"""
verde = '\033[0;32m'
vermelho = '\033[0;31m'
r1 = int(input('Digite o comprimento da PRIMEIRA reta '))
r2 = int(input('Digite o comprimento da SEGUNDA reta '))
r3 = int(input('Digite o comprimento da TERCEIRA reta '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('Estes retas \033[0;32mPODEM\033[m formar um triangulo')
else:
print('Estes retas \033[0;31mNÃO PODEM\033[m formar um triangulo')
| false |
d45712e72812d145f416d7a56fcddc2b32333a0f | iguess1220/py | /0912/tuple2.py | 725 | 4.34375 | 4 | #赋值的右侧为多个数据,有自动组包为元组
""" a = 10,20,'heh'
print(type(a))
print(a)
"""
""" a = 10
b = 20
# 交换变量1 临时变量
temp = a
a = b
b = temp
print(a,b)
# 交换变量2 计算公式
a = a + b
b = a - b
a = a - b
print(a,b)
# 交换变量3 ,元组特性
b,a=a,b # 右侧多个数据会自动组包为元组,当左侧被赋值数量和右侧对等时,进行赋值
print(a,b) """
"""
a = 10
b = 20
c = 30
c,b,a = a,c,b
print(a,b,c) """
# 进行格式化的处理
""" price,weight = 7.5,8.5
info=(price,weight)
print("单价为%.2f,重量为%.2f" % info) """
# 把列表锁定为元组,不许修改
list = [1,2,3,4,5]
list = tuple(list)
print(list)
print(type(list)) | false |
9ae1347de0841b79e77cf9efc8fa204eea5e0c09 | iguess1220/py | /0918/eval.py | 515 | 4.25 | 4 | # 列表转换成字符串后再转列表出现的问题
# str1 = "[1,2,3,4]"
# list1 = list(str1)
# 出现的并不时我们要的结果,列表会把字符串所有元素都拆解
# print(list1)
# 使用函数eval可解决
# list2 = eval(str1)
# print(list2)
# 也可以转换字典,整数,浮点数等
# str2 = "{'a':'2','c':'7'}"
# print(eval(str2))
# eval 不要在工作中使用,可自动识别函数并执行,很危险
a = eval(input("please input: "))
print(a)
#print(__import__('os').getcwd()) | false |
c0556765191e7d7e49ad7f34b79770933d9e98c0 | iguess1220/py | /0918/lambda.py | 368 | 4.15625 | 4 | # 匿名函数
# a = lambda x,y: x+y
# print(a(1,2))
# #定义匿名函数并直接调用
# result =(lambda x,y: x*y)(1,2)
# print(result)
# 传入可变参数, 返回列表生成式,直接调用取值
result = (lambda *x: [i*i for i in x ])(1,2,3,4)
print(result)
# 解包赋值
a,b,c = (lambda *x: [i*i for i in x ])(2,4,6)
print(a)
print(b)
print(c)
| false |
c55b3aedeabb43ac12481bb7a5b2ba7d1bacd0b7 | iguess1220/py | /0913/qiepian.py | 316 | 4.1875 | 4 | str1 = 'hello,world'
# 切片格式 字符串[开始索引:结束索引] 范围: [)
print(str1[-1:])
print(str1[:5]) #果如从第一个开始,即0,可以省略,不写零,直接:
print(str1[6:]) # 如果截取到最后,可省略最后的数字
print(str1[-5:]) # 可倒数,从倒数第六个到结尾 | false |
4fe62261defaeed3b3dcc21aff9d1bebdca21225 | MarcusDMelv/Summary-Chatbot | /voice.py | 1,395 | 4.125 | 4 | # Code based on https://www.geeksforgeeks.org/text-to-speech-changing-voice-in-python/
# Python program to show
# how to convert text to speech
import pyttsx3
# Initialize the converter
converter = pyttsx3.init()
# Set properties before adding
# Things to say
# Sets speed percent
# Can be more than 100
converter.setProperty('rate', 150)
# Set volume 0-1
converter.setProperty('volume', 0.7)
# Queue the entered text
# There will be a pause between
# each one like a pause in
# a sentence
converter.say("Hello Justin")
converter.say("What is Zindin doing?")
# Gets and prints list of voices available
voices = converter.getProperty('voices')
# Empties the say() queue
# Program will not continue
# until all speech is done talking
converter.runAndWait()
for voice in voices:
# to get the info. about various voices in our PC
print("Voice:")
print("ID: %s" % voice.id)
print("Name: %s" % voice.name)
print("Age: %s" % voice.age)
print("Gender: %s" % voice.gender)
print("Languages Known: %s" % voice.languages)
# Now configure for female voice
voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
# or male ID: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
# Use female voice
converter.setProperty('voice', voice_id)
converter.say("Female AIs Rule!")
converter.runAndWait()
| true |
4f3f602373b166d9a2a9af94c5a33befa671208c | grantthomas/project_euler | /python/p_0002.py | 955 | 4.1875 | 4 | # Even Fibonacci numbers
# Problem 2
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def fibonacci(n: int) -> list:
"""generate all fibonacci numbers less than n
Args:
n (int): input
Returns:
list: list of fibonacci numbers less than n
"""
i = [1, 1, 2]
while i[-1] < n:
next = i[-1] + i[-2]
if next < n:
i.append(next)
else:
break
return i
def sum_evens(items: list) -> int:
result = 0
for item in items:
if item % 2 == 0:
result += item
return result
if __name__ == "__main__":
fib = fibonacci(4e6)
result = sum_evens(fib)
print(result)
| true |
64b527ed4f5a3a18da10ee421e7b88b06e90bed7 | kkbaweja/CS303 | /Hailstone.py | 2,487 | 4.4375 | 4 | # File: Hailstone.py
# Description: A program that computes the hailstone sequence for every number in a user defined range
# Student Name: Keerat Baweja
# Student UT EID: kkb792
# Course Name: CS 303E
# Unique Number: 50860
# Date Created: 2/7/2016
# Date Last Modified: 2/9/2016
def main():
# Prompt the user to enter the starting number
start = input("\nEnter starting number of the range: ")
# Prompt the user to enter the ending number
finish = input("\nEnter ending number of the range: ")
# Check to make sure start is positive
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Check to make sure the end is positive
while (finish <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Check to make sure the start is smaller than the end
while (start >= finish):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (finish <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Initialize variables
max_num = 0
number = start
max_cycle_length = 0
# Perform the calculation to find the hailstone sequence for each number in the range
while (number <= finish):
result = number
cycle_length = 0
while (result != 1):
if (result % 2 == 0):
result = result // 2
elif (result % 2 == 1):
result = 3*result + 1
cycle_length = cycle_length + 1
if (cycle_length >= max_cycle_length):
max_cycle_length = cycle_length
max_num = number
number = number + 1
# Print out result
print("")
print ("The number", max_num, "has the longest cycle length of", str(max_cycle_length) + ".")
# Call main function
main()
| true |
81603ced0143981ee6540c89ee829ff663547c2f | v-erse/pythonreference | /Science Libraries/Numpy/arraymath.py | 1,033 | 4.34375 | 4 | import numpy as np
print("Array Math:")
# Basic mathematical functions operate on ndarrays in an elementwise fashion
a = np.arange(10).reshape(2, 5)
b = np.arange(10).reshape(2, 5)
print(a + b)
print(a*b)
# We can use the dot function to find dot products of vectors and multiply
# matrices (the matrixmultiplication.jpg file in this folder explains matrix
# multiplication)
# We can also use the T attribute to access the transposed version of b, which
# would be the same as b.reshape(5, 2)
print(np.dot(a, b.T))
# Sum will find the sum of all the numbers in an array, column, or row
print(np.sum(a))
print(np.sum(a, axis=0)) # sum of each column
print(np.sum(a, axis=1)) # sum of each row
print("\n\nBroadcasting:")
# Numpy broadcasting allows us to take 'shortcuts' around some possible
# obstacles when doing array math
x = np.arange(1, 13).reshape(4, 3)
print(x)
y = np.array([1, 2, 1])
# In this example, y will be treated as if it has been stacked 4 times, to
# match the shape of x. This is broadcasting
print(x + y)
| true |
afe6d64552f6328412a7129f7a2fad6eadc8c554 | andres-zibula/geekforgeeks-problems-solved | /basic/twisted_prime_number.py | 554 | 4.15625 | 4 | """
Author: Andres Zibula
Github: https://github.com/andres-zibula/geekforgeeks-problems-solved
Problem link: http://practice.geeksforgeeks.org/problems/twisted-prime-number/0
Description: A number is said to be twisted prime if it is a prime number and reverse of the number is also a prime number.
"""
import math
def isPrime(n):
return all(n % i != 0 for i in range(2, math.floor(math.sqrt(n))+1))
T = int(input())
for _ in range(T):
n = int(input())
if isPrime(n) and isPrime(int(str(n)[::-1])):
print("Yes")
else:
print("No") | true |
ca26154644fcfa864afdd7063d0c435040183a0d | ErycPerovani/Jogo_de_adivinhacao.py | /forca.py | 966 | 4.125 | 4 | def jogar():
print("************************************")
print("**** Bem vindo ao jogo da forca ****")
print("************************************")
palavra_secreta = "Bacana"
letras_acertadas = ["_", "_", "_", "_", "_" ,"_"]
letras_faltando = str(letras_acertadas.count("_"))
enforcou = False
acertou = False
tentativas = 0
while(not enforcou and not acertou):
chute= input("Diga uma letra: ")
chute= chute.strip()
if(chute in palavra_secreta):
index = 0
for letra in palavra_secreta:
if(chute.upper() == letra.upper()):
letras_acertadas[index] = letra
index += 1
else:
tentativas += 1
enforcou = tentativas == 6
print(letras_acertadas)
print('Ainda estao faltando {} letras'.format(letras_faltando))
print("Fim do Jogo!!")
if(__name__ == "__main__"):
jogar() | false |
8f9692a0be3836b363adc733511e4addbfc12292 | coder2000-kmj/Python-Programs | /numprime.py | 595 | 4.34375 | 4 | '''
This is a program to print prime numbers starting from a number which will be given by the user
and the number of prime numbers to be printed will also be specified by the user
'''
def isprime(n,i=2):
if n<=2:
return True if n==2 else False
if n%i==0:
return False
if i*i>n:
return True
return isprime(n,i+1)
n=int(input("Enter the initial Number"))
num=int(input("enter the number of prime numbers you want"))
count=1
while count<=num:
if(isprime(n)):
print(n)
count+=1
n+=1
else:
n+=1
| true |
d8dd66792916b405fc40b6dbc17b2c8fbb0e5a9e | DipankerBaral/Tkinter-project | /circle.py | 1,263 | 4.3125 | 4 | #mid point circle drawing algorithm
# -*- coding: utf-8 -*-
from tkinter import *
def sympoints(x,y):
w.create_text(x + x_centre, y + y_centre,text='.')
w.create_text(y + x_centre, x + y_centre,text='.')
w.create_text(x + x_centre, -y + y_centre,text='.')
w.create_text(y + x_centre, -x + y_centre,text='.')
w.create_text(-y + x_centre, -x + y_centre,text='.')
w.create_text(-x + x_centre, -y + y_centre,text='.')
w.create_text(-x + x_centre, y + y_centre,text='.')
w.create_text(-y + x_centre, x + y_centre,text='.')
def midPointCircleDraw():
x ,y=0,r
#Printing the initial point on the axes after translation
sympoints(x,y)
print(x,y)
#Initialising the value of P
P = 5/4 - r
while (x <y):
x+=1
#Mid-point is inside the perimeter of circle
if (P < 0):
P = P + 2*x + 1
#Mid-point is outside or on the perimeter of circle
else:
y-=1
P = P + 2*x - 2*y + 1
sympoints(x,y)
print(x,y)
print("Enter centre of circle")
x_centre,y_centre=map(int, input().split())
print("Enter radius of circle")
r=int(input())
master=Tk()
canvas_width=master.winfo_screenwidth()
canvas_height=master.winfo_screenheight()
w=Canvas(master,width=canvas_width,height=canvas_height)
w.pack()
midPointCircleDraw()
mainloop()
| false |
ecc4d29375e3c6200c6ac3b8f9f3b4f4c0769ca7 | alphashooter/python-examples | /homeworks-2/homework-2/task2.py | 574 | 4.125 | 4 | import calendar
from datetime import datetime
target: int
while True:
day_name = input(f'Enter day name ({calendar.day_name[0]}, etc.): ')
for day, name in enumerate(calendar.day_name):
if name == day_name:
target = day
break
else:
print('invalid input')
continue
break
now = datetime.now()
year, month = now.year, now.month
while True:
if calendar.weekday(year, month, 1) == target:
break
month -= 1
if month < 1:
year -= 1
month = 12
print(f'01.{month:02}.{year}')
| true |
eca16d3794404a3659a448df344b120d26e9fe2e | mey1k/PythonPratice | /PythonPriatice/InsertionSort.py | 252 | 4.15625 | 4 | def insertionSort(x):
for size in range(1, len(x)):
val = x[size]
i = size
while i > 0 and x[i-1] > val:
x[i] = x[i-1]
i -= 1
x[i] = val
print(x)
insertionSort([3,23,14,123,124,123,12,3]) | true |
bd40b86f7639ce864d19963092c1535a68118866 | kulvirvirk/list_methods | /main.py | 1,619 | 4.6875 | 5 |
# The list is a collection that is ordered and changeable. Allows duplicate members.
# List can contain other lists
# 1. create a list of fruits
# 2. using append(), add fruit to the list
# 3. use insert(), to insert another fruit in the list
# 4. use extend() method to add elements to the list
# 5. use pop() method to pop one of the elements from list
# 6. use remove() method to remove fruit from the list
# 7. use clear () method to clear the list
# 1. create a list of fruits
# 2. using append(), add fruit to the list
my_fruits_list = ['apple', 'banana', 'cherry']
print(my_fruits_list)
my_fruits_list.append('orange')
print(my_fruits_list)
print('----------------*****----------------')
# 3. use insert(), to insert another fruit in the list
print(my_fruits_list)
my_fruits_list.insert(2,'kiwi')
print(my_fruits_list)
print('----------------*****----------------')
# 4. use extend() method to add elements to the list
print(my_fruits_list)
second_fruits_list = ['mango', 'apple']
my_fruits_list.extend(second_fruits_list)
print(my_fruits_list)
print('----------------*****----------------')
# 5. use pop() method to pop one of the elements from list
print(my_fruits_list)
my_fruits_list.pop(1)
print(my_fruits_list)
print('----------------*****----------------')
# 6. use remove() method to remove fruit from the list
print(my_fruits_list)
my_fruits_list.remove('kiwi')
print(my_fruits_list)
print('----------------*****----------------')
# 7. use clear () method to clear the list
print(my_fruits_list)
my_fruits_list.clear()
print(my_fruits_list)
print('----------------*****----------------')
| true |
a232c1dbe330abefd09cb6c54916776cfae04c2b | darkscaryforest/example | /python/classes.py | 1,316 | 4.21875 | 4 | #!/usr/bin/python
class TestClass:
varList = []
varEx1 = 12
def __init__(self):
print "Special init function called."
self.varEx2 = 13
self.varEx3 = 14
def funcEx(self):
print self.varEx2
return "hello world"
x = TestClass()
print "1. Classes, like functions, must be declared before use.\n" \
"Calling a function in a class: " + x.funcEx() + "\n"\
"Note that all functions take at least one argument..a reference to the instance object itself"
print "2. There's a huge difference between class and instance attributes.\n" \
"class attributes are like static variables applied across all class instances\n" \
"and instance variables are scoped to particular class instances.\n"
y = TestClass()
y.varList.append(5)
y.varEx1 = 2
y.varEx2 = 5
print "x's arributes after changes:\n" \
"x.varList = " + str(x.varList) + "\n" \
"x.varEx1 = " + str(x.varEx1) + "\n" \
"x.varEx2 = " + str(x.varEx2) + "\n" \
"x.varEx3 = " + str(x.varEx3)
print "y's arributes after changes:\n" \
"y.varList = " + str(y.varList) + "\n" \
"y.varEx1 = " + str(y.varEx1) + "\n" \
"y.varEx2 = " + str(y.varEx2) + "\n" \
"y.varEx3 = " + str(y.varEx3)
print "The list in both x and y is changed even though we updated\n" \
"it through just y. Interestingly, the other int variable\n" \
"varEx1 did not change in x.."
| true |
0d3ea4123385980f8b24ecc5b59397e5e813372d | SnakeTweaker/PyStuff | /module 6 grocery list.py | 1,490 | 4.125 | 4 |
'''
Author: CJ Busca
Class: IT-140
Instructor: Lisa Fulton
Project: Grocery List Final
Date: 20284
'''
#Creation of empty data sctructures
grocery_item = {}
grocery_history = []
#Loop function for the while loop
stop = 'go'
while stop !='q':
#This block asks the user to input name, quantity, and price of items
item_name = input('Item name:\n')
quantity = input('Quantity purchased:\n')
cost = input('Price per item:\n')
#This block utilizes the empty list above to store the data input from the user
grocery_item['name'] = item_name
grocery_item['number'] = int(quantity)
grocery_item['price'] = float(cost)
grocery_history.append(grocery_item.copy())
#User has the option to continue inputting items or quit
stop = input("Would you like to enter another item? \nType 'c' for continue or 'q' to quit:\n")
#The grand total has a set value that gets added for each price that is entered
grand_total = 0
#This block utilizes a for loop for the iterations of the entered objects
for index, item in enumerate(grocery_history):
item_total = item['number'] * item['price']
#This block details the total of al of the items in the iteration
grand_total += (item_total)
print('%d %s @ $%.2f ea $%.2f' % (item['number'], item['name'], item['price'], item_total))
item_total = 0
#Grand total of all items is displayed only when user inputs quit command
print('Grand total: $%.2f' % grand_total)
| true |
0c4f077fa6e50d24ad81f1e7de30b08e60ac34f6 | radishmouse/2019-11-function-demo | /adding-quiz.py | 437 | 4.3125 | 4 | def add(a, b):
return a + b
# print(a + b)
# if you don't have a `return`
# your function automatically
# returns `None`
# Write a function that can be called like so:
add(1, 1)
# I expect the result to be 2
num1 = int(input("first number: "))
num2 = int(input("second number: "))
num3 = int(input("third number: "))
print(add(add(num1, num2), num3))
# And the result be 3
# Hint: the function should not print()
| true |
21e783fc5101c5cc328ec3fb5ea750e4f3773f72 | Sushmitha2708/Python | /Data Modules/JSONModulesFromFiles.py | 926 | 4.21875 | 4 | #this progam deals with how to load JSON files into python objects and then write those
# objects back to JSON files
import json
# to load a JSON file into a python object we use JSON 'load' method
#load method--> loads a file into python object
#loads method --> loads a string into a python object
# to load a file,it must be opened first
with open('countries.json') as f:
data=json.load(f)#after opening it is now loaded into a python obj
for country in data['countries']:
print(country['name'],country['pm'])
for country in data['countries']:
del country['capital']
#after deleting, the file is dumped back to a new json file usinng 'dump' method
#dump method--> dumps a file into python object
#dumps method --> dumps a string into a python object
#before dumping the data to a new json file, it must be created
with open('new_countries.json','w') as f:
json.dump(data,f,indent=2) | true |
b6d0f2e9b62f82970b371114f8734acc87026c0a | Sushmitha2708/Python | /Loops and Conditionals/ForLoop.py | 236 | 4.125 | 4 | #SET COMPREHENSIONS
# set is similar to list but with unique values
nums=[1,1,1,2,3,5,5,5,4,6,7,7,8,9,9] #list
my_set=set()
for n in nums:
my_set.add(n)
print(my_set)
#comprehension
my_set={n for n in nums}
print(my_set) | true |
b8a25af14fa7bbc39227418c6aa6a8f57edc3200 | LLjiahai/python-django-web | /pdjango_web/python_note/基础/python3-5/regex_study.py | 1,005 | 4.34375 | 4 | import re
'''
python的正则表达式可以通过re模块来访问,这是在查找函数中使用非常频繁的一个组件。re.search返回一个匹配对象
随后可以用这个对象的group或者groups方法获取匹配的模式
python re模块的match(),search()
re模块的match()匹配是从字符串的开始位置匹配,只有从0位置匹配成功才有返回,否则返回none
search()匹配字符串中有无符合模式要求的子串
例如:
re.match('world','hello world'),会返回none
re.search(‘world’,‘hello world’).span()返回(6,10)
group和groups是两个不同的函数。
一般,m.group(N) 返回第N组括号匹配的字符。
而m.group() == m.group(0) == 所有匹配的字符,与括号无关,这个是API规定的。
m.groups() 返回所有括号匹配的字符,以tuple格式。
m.groups() == (m.group(0), m.group(1), ...)
'''
m = re.search(r'foo', 'seafood')
print(m)
print(m.group()) #获取到匹配的字符串
| false |
7da4fa2f89f95532f15bf6e442d8d83af17f3bb4 | XanderEagle/unit6 | /unit6.py | 1,349 | 4.3125 | 4 | # by Xander Eagle
# November 6, 2019
# this program displays the Birthday Paradox showing the percent of people that have the sme birthday based on the
# amount of simulations
import random
def are_duplicates(nums):
"""finds the duplicates
:return: true if there is a duplicate
false if no duplicate
"""
for x in nums:
for y in nums[x + 1:]:
if y == x:
return True
return False
def run_it():
"""
ask the user to input the number of simulations
:return: the number of simulations
"""
return int(input("How many times do you want to run the simulation?"))
def main():
"""
tracks the variables and finds 23 random numbers out of 365
:return: the amount of duplicate birthdays along with the percentage
"""
track_variables = 0
num_times = run_it()
for nums in range(num_times):
birthdays = []
for x in range(23):
number = random.randint(1, 365)
birthdays.append(number)
if are_duplicates(birthdays):
track_variables += 1
percent_total = track_variables / num_times * 100
print("There were duplicate birthdays", track_variables, "times. That means two people had the same birthday",
percent_total, "percent of the time.")
main()
| true |
2865d43f5210b945eadc07481a14436f34b3ad23 | Mike7P/python-projects | /Guessing_game/guessing_game.py | 1,147 | 4.125 | 4 |
print("Welcome to Kelly's Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
attempts = 0
difficulty_choosing = False
random_num = randint(1, 100)
# print(f"Pssst, the correct answer is {random_num}")
def guessing_func(guess, random_num):
global attempts
attempts -= 1
if guess == random_num or attempts == 0:
return 0
elif guess < random_num:
print('Too low!')
elif guess > random_num:
print('Too high!')
while not difficulty_choosing:
choice = input("Choose a difficulty. Type 'easy' or 'hard': ")
if choice == 'easy':
attempts = 10
difficulty_choosing = True
elif choice == 'hard':
attempts = 5
difficulty_choosing = True
else:
print("Sorry, I have no idea what you typed but it wasn't easy or hard!!")
game_go = True
while game_go:
print(f"You have {attempts} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
guess_good = guessing_func(guess, random_num)
if guess_good == 0:
game_go = False
if guess == random_num:
print(f"You got it! The answer was {guess}.")
else:
print(f"Game over! {attempts} attempts left!! ")
| true |
d7dd96224064d98e702d82a4b781989d265e0fcb | nathanhwyoung/code_wars_python | /find_the_parity_outlier.py | 910 | 4.4375 | 4 | # https://www.codewars.com/kata/5526fc09a1bbd946250002dc
# You are given an array (which will have a length of at least 3, but could be very large) containing integers.
# The array is either entirely comprised of odd integers or entirely comprised of even integers except for a
# single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
def find_outlier(integers):
odds = 0
evens = 0
answer = []
for num in integers:
if num % 2 != 0:
odds += 1
elif num % 2 == 0:
evens +=1
if odds > evens:
answer = [num for num in integers if num % 2 == 0]
elif evens > odds:
answer = [num for num in integers if num % 2 != 0]
return answer[0]
# print(find_outlier([2, 4, 6, 8, 10, 3]))
# print(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))
# print(find_outlier([160, 3, 1719, 19, 11, 13, -21])) | true |
78f52eed0d2426d52462b9467f6224ead214b4fb | pavankumarNama/PythonLearnig | /Ex_Files_Python_Standard_Library_EssT/Exercise Files/Chapter 5/05_01/datetime_start.py | 810 | 4.34375 | 4 | # Basics of dates and times
from datetime import date, time, datetime
# TODO: create a new date object
tdate = date.today()
print(tdate)
# TODO: create a new time object
t = time(15, 20, 20)
print(t)
# TODO: create a new datetime object
dt = datetime.now()
dt1 = datetime.today()
print(dt)
print(dt1)
# TODO: access various components of the date and time objects
print(tdate.year)
print(tdate.month)
print(tdate.weekday())
print(t.hour)
print(t.minute)
# print('--------- ', time.hour)
# TODO: To modify values of date and time objects, use the replace function
d1 = tdate.replace(year=2021, month=12, day=31)
t1 = t.replace(hour=20, minute=33, second=45, microsecond=1000)
dt1 = dt.replace(year=2022, month=11, day=30, hour=14, minute=30, second=55, microsecond=5000)
print(d1)
print(t1)
print(dt1)
| true |
da07296f30030b450f9b1a3d754c4e777138a946 | cannibalcheeseburger/PyShitCodes | /LEETSPEAK/AdvancedLeet.py | 579 | 4.125 | 4 | dic = {"a":"4","b":"|3","c":"(","d":"|)","e":"3","f":"|=",
"g":"9","h":"|-|","i":"!","j":"_|","k":"|<","l":"|_",
"m":"/\\/\\","n":"|\\|","o":"0","p":"|D","q":"q",
"r":"|2","s":"5","t":"7","u":"(_)","v":"\\/","w":"\\/\\/","x":"><",
"y":"`/","z":"2"}
inpoot = input("Enter String to convert to Basic Leet:")
inpoot = inpoot.lower()
def convert_to_leet(inpoot):
LEET = ""
for ch in inpoot :
if ch in dic:
LEET = LEET + dic[ch]
else:
LEET = LEET + ch
print(LEET)
convert_to_leet(inpoot) | false |
6c506a5b929738c7bfe76797f93923041020f061 | okeonwuka/PycharmProjects | /ProblemSolvingWithAlgorithmsAndDataStructures/Chapter_1_Introduction/pg29_selfcheck_practice.py | 2,996 | 4.15625 | 4 | import random
# create alphabet characters including 'space' character
alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', ' ']
# create empty list to house character matches from target sentence
sentence_generator = []
# # define random_alphabet_selector function (version 1)
# def random_alphabet_selector():
# global selected_alphabet
# selected_alphabet = random.choice(alphabet_list)
# return selected_alphabet
# define random_alphabet_selector function (version 2 - simpler)
def random_alphabet_selector():
return random.choice(alphabet_list)
# Input target sentence
target_sentence = input('Please enter desired sentence:')
print('your target sentence is: %s ' % target_sentence)
# # Monkey theorem algorithm test version 1
# for i in range(100):
# for a_character in target_sentence:
# random_alphabet_selector()
# if a_character == random_alphabet_selector():
# print('There is a match')
# sentence_generator.append(random_alphabet_selector())
# else:
# print('No match')
# print(sentence_generator)
# # Monkey theorem algorithm test version 2
# for i in range(500):
# for a_character in target_sentence:
# selected_alphabet = random_alphabet_selector()
# if a_character == selected_alphabet:
# print('yes there is a match, %s is in the target sentence' % selected_alphabet)
# if selected_alphabet in sentence_generator:
# pass
# else:
# sentence_generator.append(selected_alphabet)
# else:
# print('No match')
# print(sentence_generator)
# Monkey theorem algorithm test version 2
for i in range(10000):
for a_character in target_sentence:
selected_alphabet = random_alphabet_selector()
if a_character == selected_alphabet:
print('yes there is a match, %s is in the target sentence' % selected_alphabet)
sentence_generator.append(selected_alphabet)
else:
print('No match')
# combine items in the sentence_generator into a string and store in a variable called penultimate_sentence_generator
penultimate_sentence_generator = ''.join(sentence_generator)
print('The penultimate sentence generator is: %s' % penultimate_sentence_generator)
# Delimit/split the string in penultimate_sentence_generator by ' ' (space) and place in final_sentence_generator
final_sentence_generator = penultimate_sentence_generator.split(' ')
print('The Final sentence generated is: %s' % final_sentence_generator)
for a_word in final_sentence_generator:
word_count = final_sentence_generator.count(a_word)
for i in range(word_count):
if len(a_word) < 28:
final_sentence_generator.remove(a_word)
print('The final 27 character words are: %s' % final_sentence_generator)
| true |
8c40de2b5d9cfbb59af3428537caac07ed102c99 | okeonwuka/PycharmProjects | /Horizons/pythonPracticeNumpyArrays.py | 1,687 | 4.40625 | 4 | # The numpy module gives users access to numpy arrays and several computation tools.
# Numpy arrays are list-like objects intended for computational use.
from pprint import pprint
import numpy as np
my_array = np.array([1, 2, 3])
pprint(my_array)
# Operations on a numpy array are made element by element (unlike for lists of numbers):
pprint(my_array+1), pprint(my_array*2), pprint(np.sin(my_array))
# Numpy arrays are equipped with several useful methods such as:
my_array.shape, my_array.min(), my_array.max()
print(my_array.shape, my_array.min(), my_array.max())
# The numpy module also features some convenient array-generating functions:
# Linear space of 20 pts between 0 and 10
my_array2 = np.linspace(0, 10, 20)
pprint(my_array2)
# Sequence of numbers from 0 to 10 with step of 0.2,
# similar to range() but accepts non-integer steps
my_array3 = np.arange(0, 10, 0.2)
pprint(my_array3)
# Multi-dimensional arrays are created using nested list and a call to np.array()
# Here is an example of a 2D array:
my_array4 = np.array([[1, 2, 3], [4, 5, 6]])
pprint(my_array4)
# Items in a multi-dimensional array can be retrieved, like in a nested list, as:
my_array4[1][1]
print(my_array4[1][1])
# or
my_array4[0,2]
print(my_array4[0, 2])
# Moreover, numpy is equipped with several NaN (Not-a-Number) functions.
my_array5 = np.array([[1, np.nan], [np.nan, 2]])
pprint(my_array5)
np.nanmin(my_array5), np.nanmax(my_array5)
print(np.nanmin(my_array5), np.nanmax(my_array5))
np.isnan(my_array5)
pprint(np.isnan(my_array5))
# Finally, to concatenate numpy arrays, use:
np.concatenate([my_array,my_array2[0:5]])
pprint(np.concatenate([my_array,my_array2[0:5]]))
| true |
fa7839e158a42655a6bbdab05620c5fa0d1e7aa7 | wp-lai/xpython | /code/kthlargest.py | 922 | 4.21875 | 4 | """
Task:
Find the kth largest element in an unsorted array. Note that it is the kth
largest element in the sorted order, not the kth distinct element.
>>> find_kth_largest([3, 2, 1, 5, 6, 4], 2)
5
"""
from random import randint
def find_kth_largest(nums, k):
# find a random pivot
length = len(nums)
pivot = randint(0, length - 1)
nums[pivot], nums[0] = nums[0], nums[pivot]
# reorder so that left part > key, right part < key
key = nums[0]
i = 1
for j in range(1, length):
if nums[j] > key:
nums[i], nums[j] = nums[j], nums[i]
i += 1
nums[i - 1], nums[0] = nums[0], nums[i - 1]
# divide and conqure
if i == k:
return nums[i - 1]
elif i < k:
return find_kth_largest(nums[i:], k - i)
else:
return find_kth_largest(nums[:i - 1], k)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
7d17cbaddef7f2dad0a85adad69a2d838c7f2936 | wp-lai/xpython | /code/int2binary.py | 1,431 | 4.1875 | 4 | """
Task:
Converting decimal numbers to binary numbers
>>> convert_to_binary(25)
'0b11001'
>>> convert_to_binary(233)
'0b11101001'
>>> convert_to_binary(42)
'0b101010'
>>> convert_to_binary(0)
'0b0'
>>> convert_to_binary(1)
'0b1'
"""
# Solution 1:
# keep dividing by 2, store the remainder in a stack
# read in reverse order
def convert_to_binary(number):
if number == 0:
return '0b0'
stack = []
while number:
stack.append(number % 2)
number = number // 2
binary_str = "0b"
while stack:
binary_str += str(stack.pop())
return binary_str
# Solution 2: using built-in function bin
def convert_to_binary(number):
return bin(number)
# Solution 3: using string formatting
def convert_to_binary(number):
return '0b{:b}'.format(number)
# Solution 4: using bitwise operation
def convert_to_binary(number):
if number == 0:
return '0b0'
stack = []
while number:
stack.append(number & 1) # append last bit
number = number >> 1 # remove last bit
binary_str = "0b"
while stack:
binary_str += str(stack.pop())
return binary_str
# Solution 5: using recursion
def convert_to_binary(number):
digit = "01"
if number < 2:
return "0b" + digit[number]
else:
return convert_to_binary(number // 2) + digit[number % 2]
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
c65b02fc056b996dacd941e299fe558d47785d6d | erinnlebaron3/python | /partitionstr.py | 2,573 | 4.78125 | 5 | # partition function works in Python is it's going to look inside the string for whatever you pass in as the argument.
# once it finds that it then partitions the entire string and separates it into three elements and so it is going to take python and it is going to be the first element.
# whenever you call partition and you perform assignment like we're doing here. It actually returns what's called a tuple collection.
# essentially what it's allowing us to do is it means that it's going to break what used to be a string which was one object into three objects.
# It's going to break it into the first the second and the third.
# very popular Python convention for whenever you have values that you do not want to use the best way to represent those is with an underscore.
# So this is not a required syntax it is simply a best practice in the Python community
heading = "Python: An Introduction"
header, _, subheader = heading.partition(': ')
print(header)
print(subheader)
answer = Python
An Introduction
# Python is whenever you have some type of situation where it looks like this where we have some elements that we want.
# But then we may have some elements that we don't care about such as what we're trying to pull out so we don't want to care about this colon
# we don't want to worry about getting rid of it.
# We simply want to say that that existed in the string but we don't need it for everything we're going to do after that.
# ability to clean it up and pull out the contents that you want and leave the things you don't want partitions are a great way of doing it
# and other developers when they come in they look at your code or when you go back and
# you look at your program months or years later when you see this underscore you'll understand that it means that whatever gets piped into that value is a throwaway value.
heading = "Python: An Introduction"
header, _, subheader = heading.partition(': ')
print(header)
print(_)
print(subheader)
answer = Python:
An Introduction
# Now once again this is simply a python convention. It is not a syntactic rule
heading = "Python: An Introduction"
first, second, third = heading.partition(': ')
print (first)
print(second)
print(third)
answer = Python:
An Introduction
# important component to remember whenever you're working with partition is that it breaks whatever you pass
# the colon is considered best practice
# EXAMPLE
fullname = "Erinn Ragan LeBaron"
firstname, _, lastname = fullname.partition('Ragan ')
print(firstname)
print(lastname)
answer = Erinn LeBaron | true |
dd552daf2cf44e1a08733c54e31204750afc4f43 | erinnlebaron3/python | /List.py | 2,563 | 4.875 | 5 | # like an array. It is a collection of values and that collection can be added to. You can remove items. You can query elements inside of it.
# Every time that you want a new database query what it's going to do is it's going to look at its set of data structures and it's going to go and it's going to put them in that.
# in the case of a list you're going to have to know how to loop through
# this is now no longer just a set of strings what we have here is actually a true data structure we have a list of these string names which would be
# like what we'd get if we queried a database with users.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
answer = ['Kristine', 'Tiffany', 'Jordan']
# add to this list
# to add the string Anthony and I want to make this a new element at the list it goes at the very front I pass in the index.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(0, 'Anthony')
print(users)
answer =
['Kristine', 'Tiffany', 'Jordan']
['Anthony', 'Kristine', 'Tiffany', 'Jordan']
# add element to list
# replace and assign elements
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
answer =
['Kristine', 'Tiffany', 'Jordan']
['Kristine', 'Anthony', 'Tiffany', 'Jordan']
['Kristine', 'Anthony', 'Tiffany', 'Jordan', 'Ian']
# square brackets and hit return you can see this last element is what gets returned. Now, this is a very key thing to understand here.
# Each one of these other times were printed this out. Notice how it had the brackets around the entire collection of data. What that means is that these are still lists.
# So each one of these is a list object which means that as Python looks at it that you can only call the types of functions that are available to the list data type.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
print(users[2])
answer = Tiffany
# change name
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
print(users[2])
users[4] = 'Braden'
print(users)
answer =
['Kristine', 'Anthony', 'Tiffany', 'Jordan', 'Braden'] | true |
9673ae62285d1caf5117a936bb1e05b7699a76a6 | erinnlebaron3/python | /PackageProject.py | 2,385 | 4.4375 | 4 | # will help you on the entire course capstone project
# Technically you have learned everything that you need to know in order to build out this project.
# helps to be familiar with some of the libraries that can make your life a little bit easier and
# make your code more straightforward to implement
# web scraper
# what it is going to do is go out to a Web site and it is going to go and extract components from
# that site so that you can use them, you can bring them into your own program.
# so you need to bypass the entire concept of an API
# http://www.dailysmarty.com/topics/python
# to be able to build is a program that comes to this url and then scrapes the code from this.
# leverage the requests library you're going to be able to call the url directly and then get access to all content.
'http://www.dailysmarty.com/posts/how-to-implement-fizzbuzz-in-python'
"How to Implement FizzBuzz in Python"
"""
Libraries:
-requests
-inflection
-beautifulsoup
pip install requests
pip install inflection
pip install beautifulsoup4
"""
# go to pure web page daily smarty
# program goes to url and scrapes the code from this
# leverage requests to get url directly
# select all links that go to posts
# copy link address
# right-click on this and click copy link address right here let me open up in a text editor say vim project.py
# and so I'm going to paste in right here what that url looks, and so you are going to get access to this.
# only pull out the links that are related to posts.
# only the ones that go right to a post
# take link and convert link into page title
# build function takes title text in url and make a string with caps and spaces
# final output should look like different lists of titles with "" around with caps and spacing
import requests
from bs4 import BeautifulSoup
from inflection import titleize
def title_generator(links):
titles = []
def post_formatter(url):
if 'posts' in url:
url = url.split('/')[-1]
url = url.replace('-', ' ')
url = titleize(url)
titles.append(url)
for link in links:
post_formatter(link["href"])
return titles
r = requests.get('http://www.dailysmarty.com/topics/python')
soup = BeautifulSoup(r.text, 'html.parser')
links = soup.find_all('a')
titles = title_generator(links)
for title in titles:
print(title) | true |
077bbfec6567508594cadabda71238de6829b41c | erinnlebaron3/python | /NegativeIndexStr.py | 777 | 4.15625 | 4 | # In review the first value here is zero. The next one is one and it counts all the way up in successive values.
# However if you want to get to the very back and you actually want to work backwards then we can work with negative index
sentence = 'The quick brown fox jumped over the lazy dog'
print(sentence[-1])
answer = g
# -3 and it's going to print out the O from dog and we could just keep going and grab our values in this negative index
# kind of manner that is helpful but that will only allow us to grab a single value.
sentence = 'The quick brown fox jumped over the lazy dog'
print(sentence[-4:])
answer = dog
# remember whenever we pass in a colon and we leave the rest of the argument blank then it's going to go to the very end of the string.
| true |
ad51a4b6182415c29a404f0457b9d168f2ced94d | erinnlebaron3/python | /decimalVSfloat.py | 2,791 | 4.46875 | 4 | # in python all decimals are floating numbers unless decimal is called
# you can create a decimal is to copy decimal it has to be all like this with it titled with the capital D and decimal spelled out and then because it's a
# function we're going to call decimal.
# when it comes to anything that is finance related or scientific or where the level of precision is incredibly important then it's a good idea to bring in the decimal class
# is a very important caveat when working with decimals and that is if you want to perform advanced calculations that need to be very precise than using the
# floating point number is not going to be your best option.
# to import decimal we say import the decimal library and then say from decimal
from decimal import Decimal
# Float
product_cost = 88.40
comission_rate = 0.08
qty = 450
product_cost += (comission_rate * product_cost)
print(product_cost * qty)
answer = 42962.4
from decimal import Decimal
product_cost = 88.40
commission_rate = 0.08
qty = 450
product_cost += (commission_rate * product_cost)
print(product_cost * qty) # 42962.4
product_cost = Decimal(88.40)
commission_rate = Decimal(0.08)
qty = 450
product_cost += (commission_rate * product_cost)
print(product_cost * qty) # 42962.40000000000282883716451
# CONVERTING BETWEEN INTEGER, FLOAT, DECIMAL, AND COMPLEX NUMBER DATA
# Float
# keyword is float and I can say quantity
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(float(qty))
anwer = 450.0
# INTEGER
# gives us similar behavior to how the floor division computation works where even though 88.8 is closer to 89 all that
# essentially it's doing is it's just taking the floating point variable and just throwing it away.
# if you are converting these values it doesn't round it to the Close's hole number. It simply takes whatever integer value is there and it just keeps that and ignores the rest.
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(int(product_cost))
answer = 88
# DECIMAL
# remember to import decimal we say from decimal import this decimal
from decimal import Decimal
from decimal import Decimal
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(Decimal(product_cost))
answer = 88.790232012122200
# COMMISION RATE
# say complex and this is going to give us the scientific notation for commission rate
# scientific notation in parentheses and this actually because it returns in parens this is giving you a complex object that you can work with.
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(complex(commission_rate))
from decimal import Decimal
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(int(product_cost))
print(float(qty))
print(Decimal(product_cost))
print(complex(commission_rate)) | true |
f3566a6b295b511718e3fac82156d6bad58b52a0 | erinnlebaron3/python | /FuncConfigFallBck.py | 1,356 | 4.40625 | 4 | # syntax for doing is by performing something like this where I say teams and then put in the name of the key and then that is going to perform the query.
# want to have a featured team so I can say featured team store this in a variable.
teams = {
"astros": ["Altuve", "Correa", "Bregman"],
"angels": ["Trout", "Pujols"],
"yankees": ["Judge", "Stanton"],
"red sox" : ['Price', 'Bets']
}
featured_team = teams['astros']
print(featured_team)
answer = ['Altuve', 'Correa', 'Bregman']
# fallback - that's what we can do with the get function inside of Python dictionaries
# make sure that you are catching any kind of scenarios that have a situation like this where we're looking up a key that may or may not exist
# and you want to have some type of fallback and so this is going to give you instant feedback to let you know that what you tried to look up
# doesn't actually exist inside of the team's dictionary.
# GET
# get takes two arguments
# The first is a key we're looking for.
# gives us the abitlity to have multiple checks when using look ups in Python automaticaly
teams = {
"astros": ["Altuve", "Correa", "Bregman"],
"angels": ["Trout", "Pujols"],
"yankees": ["Judge", "Stanton"],
"red sox" : ['Price', 'Bets']
}
featured_team = teams.get('mets', 'No featured team')
print(featured_team)
answer = No featured team
| true |
023d47ee8dced82d994b1660c359715d72761482 | erinnlebaron3/python | /lenNegIndex.py | 1,462 | 4.46875 | 4 | # LENGTH
# the length function and it's actually called the L E N which is short for length
# this is going to give you the count for the full number of elements in a list
# there is a difference between length and index
# LENGTH
# remember the counter starts and the index starts at 0.
# even though we have four elements inside the last index item here is actually going to be three
# how we could get a count of all of the elements in the list.
tags = ['python', 'development', 'tutorials', 'code']
number_of_tags = len(tags)
print(number_of_tags)
answer = 4
# MOST OF THE LISTS YOU WORK WITH WONT BE HARD CODED
# how you could get the value from the last item even if you don't know what its index was by using a negative index.
tags = ['python', 'development', 'tutorials', 'code']
last_item = tags[-1]
print(last_item)
answer = code
# how to grab index
# once you do have the value for one of your elements you can pass it to the index function right here and then it will go traverse
# through the entire list and return the index of that value.
tags = ['python', 'development', 'tutorials', 'code']
index_of_last_item = tags.index(last_itme)
print(index_of_last_item)
answer = 3
# ALL CODE WITH ANSWERS
tags = ['python', 'development', 'tutorials', 'code']
number_of_tags = len(tags)
last_item = tags[-1]
index_of_last_item = tags.index(last_item)
print(number_of_tags)
print(last_item)
print(index_of_last_item)
answers =
4
code
3 | true |
6a88efb4a656dfda208f49f561d287175734e755 | erinnlebaron3/python | /FilesinPy.py/Create&WriteFile.py | 1,659 | 4.625 | 5 | # very common use case for working with the files system is to log values
# gonna see how we can create a file, and then add it to it.
# create a variable here where I'm going to open up a file.
# I'm going to show you here in the console that if I type ls, you can see we do not have a file called logger.
# function open is going to allow us to open or create a file.
# Python works is if you call open, if it finds a file then it will open up that file.
# you can perform whatever you need to inside of it. If it does not find a file with that name,
# then it will automatically create it.
# regular text file, and it takes another argument which is the way that we want to open it up.
# set of permissions that we want our program to follow. It takes in a string
# write is a function inside of the file library in Python a
# to close the file off. So I'm going to say file_builder.close() and then we're going to call the close function.
# string literal interpolation I'll say {i + 1}.
# right after the curly braces pass in \n,
# syntax where you are opening a file and then you're just calling right on it, it is not going to care whatsoever about
# the contents of the file previously.
# This is what you would do if you want to have almost like a temp type of logger
# truly remember from this guide is that if you use this syntax, where you're opening a file and you're simply
# calling right you will overwrite all of the content in that file.
file_builder = open("logger.txt", "w+")
for i in range(100):
file_builder.write(f"I'm on line {i + 1}\n")
# file_builder.write("Hey, I'm in a file!")
file_builder.close()
| true |
0ae57c234dc5a9daa688426e8c4953980f510f65 | erinnlebaron3/python | /Slice2StoreSlice.py | 2,968 | 4.78125 | 5 | # here are times where you may not know or you may not want to hard code in this slice range.
# And so in cases like that Python actually has a special class called slice which we can call and store whatever these ranges we want
# biggest reasons why you'd ever use this slice class over using just this explicit version slice(1, 4, 2) is whenever you want to define
# your ranges and your steps and those kinds of elements and you want to store them in a variable and then simply call them later on and or
# also another opportunity where this would be a very good fit is if you're maybe calling this on different datasets.
# SLICE
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
# print(tags[:2])
slice_obj = slice(2)
print(tags[slice_obj])
answer = ['python', 'development']
# similar when working with explicet slice
# working with an explicit slice and when we passed in a range the only difference is that
print(tags[:2])
# the key differences here is we can call store this method inside of another object inside
# of a variable and then we can call that anywhere in the program.
# so this is a very nice way of being able to store your slice so that you can reuse it on any other kinds of lists.
print(tags[slice_obj])
# with slice, you can see there are three potential arguments inside of this object and the first one is our start point. So we're going to have a start.
# going to have an end and then we're going to have a step which if you remember exactly with what we had with ranges and with these explicit type of
# slices we could pass in say [2:4:2]. And then this is going to bring us every other element because the last 2 is our step. This first 2 is our start
# and this 4 is our stop or this is our endpoint.
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
# print(tags[2:4:2])
slice_obj = slice(2)
print(slice_obj)
print(tags[slice_obj])
answer = slice(None, 2, None)['python', 'development']
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(tags[slice_obj])
answer = ['development', 'code']['development', 'code']
# working on a machine learning algorithm and you want to know in some other part of the program where the range started where it stopped and what
# the step interval was.
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(slice_obj.start)
print(slice_obj.stop)
print(slice_obj.step)
print(tags[slice_obj])
answer =
['development', 'code']
14
2
['development', 'code']
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(slice_obj.start)
print(slice_obj.stop)
print(slice_obj.step)
print(tags[slice_obj])
answer =
['development', 'code']
14
2
['development', 'code'] | true |
3c34b20a2bfb075095cd8395e86b312cb3b418e0 | pravallikachowdary/pravallika | /pg23.py | 465 | 4.1875 | 4 | # in arr[] of size n
# python function to find minimum
# in arr[] of size n
def smallest(arr,n):
# Initialize minimum element
min = arr[0]
# Traverse array elements from second
# and compare every element with
# current min
for i in range(1, n):
if arr[i] > min:
min = arr[i]
return min
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = smallest(arr,n)
print ("smallest in given array is",Ans)
| false |
987adf3d6c77ee903e0cf74b398c8cfdcb2d54f3 | jibinsamreji/Python | /MIni_Projects/carGameBody.py | 964 | 4.15625 | 4 | print("Welcome player! Type 'help' for more options..!")
user_input = input(">")
i = 0
start = False
stop = False
while user_input.upper() == "HELP":
if i < 1:
print("""
start - to start the car
stop - to stop the car
quit - to exit""")
i += 1
game_option = input(">").upper()
if game_option == 'START':
if not start:
print("Car started....Ready to go!")
start = True
stop = False
else:
print("Car already started....!")
elif game_option == 'STOP':
if not stop:
print("Car stopping...Car stopped!")
stop = True
start = False
else:
print("Car already stopped....!")
elif game_option == 'QUIT':
print("Quitting.....")
break
else:
print("Not a valid choice..! Please select an option from the above!")
else:
print("I don't understand that..")
| true |
3d8b2938eed4cd2d299218d4dd787d80518e8154 | victorsibanda/python-basics | /102_python_data_types.py | 1,696 | 4.59375 | 5 | #Strings
#Text and Characters
#Syntax
#"" and ''
#Define a string
#Anything that is text is a string
my_string = 'Hey I am a cool string B)'
print(my_string)
type(my_string)
#Concatenation
joint_string = 'Hey I am another' + ' cool string, ' + my_string
print (joint_string)
#example two of concatenation
name = 'Mohamed'
welcome_text = 'Welcome to SPARRRRRRRRRRRTTTTTTTAAAAAAAAA'
print (welcome_text+' '+name)
print (welcome_text,name) #overloading the sprint
#Interpolation
#inserting a sting inside another string
#or running python inside a string
print (f'Welcome {name} to class 54, we are Contested Terrain ')
#print (f'Welcome {input("What is your name")} to class 54, we are Contested Terrain ')
print ('Welcome to class 54 , we are Contested Terrain'.format(name))
#Useful methods
# A method is a funtion that belongs to a specific data type.
#e.g it would not make sense to capitalize integers
example_long_str = ' Hello , This is a badly formated test?'
print (example_long_str)
#Remove trailling white spaces
print (example_long_str.strip())
#Make it lowr case
print(example_long_str.lower())
#Make it upper case
print(example_long_str.upper())
#First character capitalised
print(example_long_str.strip().capitalize())
print(example_long_str.strip().title())
#Change the question mark into an exclamation mark
print(example_long_str.strip().replace('?','!') )
#chainsome methods and :
# Remove trailing white spaces
#make it nicely formatted with only first letter capitalised
#print(example_long_str.strip().replace('?','!').capitalize().replace('badly','well')
#create a list with individual words
print(example_long_str.strip().split())
| true |
faa0ffceb30031674446ed24efdb4e6085fa9873 | victorsibanda/python-basics | /101_python_variables_print_type.py | 531 | 4.1875 | 4 | # Variables
# it is like a box, you give it a name, and put stuff inside
book = 'Rich dad poor dad'
## Print function
#Outputs content to the terminal (makes it visible)
print(book)
# Type function
#Allows us to check data types
data_type_of_book = type(book)
print (data_type_of_book)
#input() - prompt for user input and you can add a string to the arguement so it prints before capturing the input
input ('this gets printed before capturing your input')
##Conventions
# lower case for variable naming with under score | true |
d6320818cdbf2b26bcffb410c1cad8e27ef9477f | devionb/MIM_Software_code_sample | /Part_A.py | 642 | 4.375 | 4 | # Devion Buchynsky
# Part A - Reverse the string if its length is a multiple of 4.
# multiples of 4: 4,8,12,16......
multiple_of_4_string_letter = 'abcd'
multiple_of_5_string_letter = 'abcde'
print('Before function is ran.')
print(multiple_of_4_string_letter)
print(multiple_of_5_string_letter)
def reverse_string(string_1):
if len(string_1) % 4 == 0: # if the string is a % of 4 then it will reverse the string, if not it will not do anything.
return ''.join(reversed(string_1))
return string_1
print('After function is ran.')
print(reverse_string(multiple_of_4_string_letter))
print(reverse_string(multiple_of_5_string_letter))
| true |
064a088d379dc1010eaa365e9857615bcd8f4d56 | diallog/PY4E | /assignment5.2/assignment5.2_noIntTest.py | 1,133 | 4.1875 | 4 | # Assignment 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
# Initialize variables
smallest = None # variable holds current smallest value
largest = None # variable holds current largest value
newNumber = 0 # variable holds new input for testing
intNewNumber = 0 # new input converted to integer
request = True
# Main program - build the list from user input
while request is True:
newNumber = input('Give a number or "done": ')
if newNumber == 'done':
request = False
else:
try:
intNewNumber = int(newNumber)
except:
print('''Invalid input''')
continue
if largest is None or intNewNumber > largest:
largest = intNewNumber
elif smallest is None or intNewNumber < smallest:
smallest = intNewNumber
continue
# Output
print('Maximum is', largest)
print('Minimum is', smallest)
| true |
4b0ec224525c1b9e584710cbe2456aa7c2f9000d | diallog/PY4E | /assignment2.3/assignment2.3.py | 606 | 4.21875 | 4 | # This assignment will obtain two pieces of data from the user and perform a calculation.
# This script begins with a hint from the course...but lets do a little over-achievement.
print("Alright, let's do our first calculation in Python using information obtained from the user.\r")
# This first line is provided for you
hrs = input("Please enter the number of hours worked: ")
# hrs = float(hrs)
rate = input("Thank you. Now enter the rate ($/hr): ")
# rate = float(rate)
# calculation...
pay = float(hrs) * float(rate)
# output
# print("Pay: " + str(pay))
# alternative approach
print("Pay:", pay)
| true |
7c023a7743c6f76a6f4c5b2bd46535ccae3d2efe | priyanshu3666/my-lab-practice-codes | /if_else_1.py | 237 | 4.21875 | 4 | #Program started
num = int(input("Enter a number")) #input taking from user
if (num%2) == 0 : #logic start
print("The inputted muber",num," is Even")
else :
print("The inputted muber",num," is Odd") #logic ends
#Program Ends
| true |
1f3007154c8734dce197638aae123261f4fd3eca | iamdoublewei/Leetcode | /Python3/125. Valid Palindrome.py | 983 | 4.28125 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
#Original
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.replace(" ", "")
if not s: return True
res = ''
s = list(s.lower())
for cur in s:
if cur >='a' and cur <= 'z' or cur >= '0' and cur <= '9':
res += cur
return res == ''.join(reversed(res))
#Improved:
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
res = ''
for cur in s.lower():
if cur.isalnum():
res += cur
return res == ''.join(reversed(res))
| true |
336f4764f1208ed1e8cea45946a6e097187ec098 | iamdoublewei/Leetcode | /Python3/1507. Reformat Date.py | 1,545 | 4.375 | 4 | '''
Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to the format YYYY-MM-DD, where:
YYYY denotes the 4 digit year.
MM denotes the 2 digit month.
DD denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
The given dates are guaranteed to be valid, so no error handling is necessary.
'''
class Solution:
def reformatDate(self, date: str) -> str:
dic = {'1st':'01', '2nd':'02', '3rd':'03', '4th':'04', '5th':'05', '6th':'06', '7th':'07',
'8th':'08', '9th':'09', '10th':'10', '11th':'11', '12th':'12', '13th':'13', '14th':'14',
'15th':'15', '16th':'16', '17th':'17', '18th':'18', '19th':'19', '20th':'20', '21st':'21',
'22nd':'22', '23rd':'23', '24th':'24', '25th':'25', '26th':'26', '27th':'27', '28th':'28',
'29th':'29', '30th':'30', '31st':'31', 'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04',
'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'}
date = date.split()
date[0] = dic[date[0]]
date[1] = dic[date[1]]
return '-'.join(date[::-1]) | true |
38e0976de0b8376345610a411550df8ca5639293 | iamdoublewei/Leetcode | /Python3/680. Valid Palindrome II.py | 1,005 | 4.15625 | 4 | '''
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def isPalindrome(s, i, j):
while j >= i:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
if len(s) <= 1:
return True
i, j = 0, len(s) - 1
while j >= i:
if i == j:
break
if s[i] != s[j]:
return isPalindrome(s, i + 1, j) or isPalindrome(s, i, j - 1)
i += 1
j -= 1
return True
| true |
84a99ce38f0a9fa7e7456be2ec28f70c54b8d41d | iamdoublewei/Leetcode | /Python3/849. Maximize Distance to Closest Person.py | 1,464 | 4.25 | 4 | '''
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to closest person.
Example 1:
Input: [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
Input: [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat, the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Note:
1 <= seats.length <= 20000
seats contains only 0s or 1s, at least one 0, and at least one 1.
'''
class Solution:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
zeros, mx = 0, 0
for i, v in enumerate(seats):
if not v:
zeros += 1
if not i:
mx = -1
else:
if mx == -1:
mx = zeros
else:
mx = max(mx, (zeros + 1) // 2)
zeros = 0
if zeros:
mx = max(mx, zeros)
return mx
| true |
98ceacd32d0924643b4f6caa745e67c3f754951e | iamdoublewei/Leetcode | /Python3/417. Pacific Atlantic Water Flow.py | 2,184 | 4.40625 | 4 | '''
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
m == heights.length
n == heights[r].length
1 <= m, n <= 200
0 <= heights[r][c] <= 105
'''
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
row = len(heights)
col = len(heights[0])
pac = set()
alt = set()
res = []
def search(r, c, h, ocean):
if r < 0 or c < 0 or r >= row or c >= col or (r, c) in ocean or heights[r][c] < h:
return
ocean.add((r, c))
search(r + 1, c, heights[r][c], ocean)
search(r - 1, c, heights[r][c], ocean)
search(r, c + 1, heights[r][c], ocean)
search(r, c - 1, heights[r][c], ocean)
for i in range(col):
search(0, i, 0, pac)
search(row - 1, i, 0, alt)
for i in range(0, row):
search(i, 0, 0, pac)
search(i, col - 1, 0, alt)
for i in pac:
if i in alt:
res.append(list(i))
return res
| true |
06603409c216e418a50c655532a82a17429f040c | iamdoublewei/Leetcode | /Python3/2000. Reverse Prefix of Word.py | 1,366 | 4.40625 | 4 | '''
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word consists of lowercase English letters.
ch is a lowercase English letter.
'''
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
for i in range(len(word)):
if word[i] == ch:
return word[:i + 1][::-1] + word[i + 1:]
return word | true |
e3b81970fb6473a49d9a480991999a110605927d | kirakrishnan/krishnan_aravind_coding_challenge | /TLS/turtle_simulator.py | 2,218 | 4.125 | 4 | import turtle
import time
def setup_simulator_window():
"""
set up a window with default settings to draw Traffic Lights
:param:
:return t: turtle object
"""
t = turtle.Turtle()
t.speed(0)
t.hideturtle()
screen = turtle.Screen()
screen.screensize()
screen.setup(width = 1.0, height = 1.0)
return t
def draw_circle(t):
"""
Draws a Traffic Light circle
:param:
:return:
"""
t.begin_fill()
t.circle(100)
t.end_fill()
def set_pos(x, y, t):
"""
Set up the position for next circle
:param x: x axis position
:param y: y axis position
:param t: turtle object
:return:
"""
t.setpos(x,y)
def fill_circle(x,y,current_light, light, t):
"""
Set up the position for Traffic Light and fills it
:param x: x axis position
:param y: y axis position
:param current_light: current light that should be displayed
:param light: corresponding light for this circle
:param t: turtle object
:return:
"""
set_pos(x,y,t)
if(current_light == light):
t.fillcolor(current_light)
else:
t.fillcolor('white')
draw_circle(t)
def switch_light(current_light):
"""
Generates the next light in sequence that should be displayed
:param current_light: current light that should be displayed
:return next_light: next light that should be displayed
"""
if(current_light == "green"):
next_light = "yellow"
elif(current_light == "yellow"):
next_light = "red"
elif(current_light == "red"):
next_light = "green"
return next_light
def open_simulator(times):
"""
Generates a simulator window to display traffic lights and
iterates thru each light as per the given transition times
:param times: corresponding transition times for each lights
"""
t = setup_simulator_window()
current_light = "green"
while(True):
fill_circle(0, 220, current_light, "red", t)
fill_circle(0, 0, current_light, "yellow", t)
fill_circle(0, -220, current_light, "green", t)
time.sleep(times[current_light])
current_light = switch_light(current_light)
| true |
91c081afcb0ca54068bd1a38049c3da5ddd73c6a | evantarrell/AdventOfCode | /2020/Day 2/day2.py | 1,622 | 4.21875 | 4 | # Advent of Code 2020 - Day 2: Password Philosophy
# Part 1, read input file with each line containing the password policy and password. Find how many passwords are valid based on their policies
# Ex: 1-3 a: abcde is valid as there is 1 a in abcde
# but 3-7 l: ablleiso is not valid as there are only 2 l's in ablleiso
import re
regexPattern = '(\\d+)-(\\d+) (\\w): (\\w+)'
validPasswordCount = 0
with open('input.txt', 'r') as input:
for line in input:
match = re.search(regexPattern, line)
if match is not None:
lowerLimit = int(match.group(1))
upperLimit = int(match.group(2))
letter = match.group(3)
password = match.group(4)
letterCount = password.count(letter)
if letterCount >= lowerLimit and letterCount <= upperLimit:
validPasswordCount += 1
print('Part 1: There were ' + str(validPasswordCount) + ' valid passwords')
# Part 2, same but the password policy meaning is different.
# Instead of counts it denotes two positions for the given letter to occur in, base 1 indexing. The letter must occur in exactly one of the two positions, other occurrences don't matter
validPasswordCount = 0
with open('input.txt', 'r') as input:
for line in input:
match = re.search(regexPattern, line)
if match is not None:
pos1 = int(match.group(1)) - 1
pos2 = int(match.group(2)) - 1
letter = match.group(3)
password = match.group(4)
if len(password) > pos2 and (password[pos1] == letter or password[pos2] == letter) and not (password[pos1] == password[pos2]):
validPasswordCount += 1
print('Part 2: There were ' + str(validPasswordCount) + ' valid passwords')
| true |
2ed81826bd5979dfb2b87405901f552b614f00f6 | zanixus/py-hw-mcc | /professor_analysis_KM.py | 1,194 | 4.125 | 4 | #!/usr/bin/python3
"""
Kevin M. Mallgrave
Professor Janet Brown-Sederberg
CTIM-285 W01
16 Feb 2019
Grade analysis script that handles tuple input.
"""
def mean(number_list):
number_sum = 0
for i in number_list:
number_sum = i + number_sum
number_mean = number_sum / len(number_list)
return number_mean
def variance(number_list, mean_input):
print(number_list)
numbers_squared = []
list_position = 0
for i in number_list:
list_position = 0
numbers_squared.insert(list_position, (mean_input - i) ** 2)
list_position += 1
return (mean(numbers_squared))
def std_deviation(variance_input):
return (variance_input ** (.5))
abbey = 72
ben = 84
charlotte = 70
david = 85
emma = 88
frank = 81
georgia = 77
harry = 77
isabelle = 87
jeb = 63
grades = [abbey, ben, charlotte, david, emma,
frank, georgia, harry, isabelle, jeb]
print(grades)
grade_mean = mean(grades)
grade_variance = variance(grades, grade_mean)
grade_std_deviation = std_deviation(grade_variance)
print("\n")
print("Mean: " + str(grade_mean) + "\n")
print("Variance: " + str(grade_variance)+"\n")
print("Standard Deviation: " + str(grade_std_deviation)+ "\n")
| false |
684f9a65b6c72684f2355958751ae8d4b1de97a5 | kaushikram29/python1 | /character.py | 220 | 4.21875 | 4 | X=input("Enter your character")
if((X>="a" and X<="z) or (X>="A" and X<="Z")):
print(X, "it is an alphabet")
elif ((X>=0 and Z<=9)):
print(X ,"it is a number or digit")
else:
print(X,"it is not alphabet or digit")
| true |
c17a66237825077916c7c9b03add598dc9017e55 | urbanskii/UdemyPythonCourse | /secao05/se05E27.py | 690 | 4.25 | 4 | """
27 - Escreva um programa que, dada a idade de um nadador, classifique-o em uma das
seguintes categorias:
Categoria Idade
Infantil A 5 a 7
Infantil B 8 a 10
Juvenil A 11 a 13
Juvenil B 14 a 17
Sênior maiores de 18 anos
"""
def main():
idade = int(input('Informe a idade: '))
if 5 <= idade <= 7:
print(f'Infantil A: {idade}')
elif 8 <= idade <= 10:
print(f'Infantil B: {idade}')
elif 11 <= idade <= 13:
print(f'Juvenil A: {idade}')
elif 14 <= idade <= 17:
print(f'Juvenil A: {idade}')
elif idade >= 18:
print(f'Sênior: {idade}')
else:
print('Idade incorreta!')
if __name__ == '__main__':
main()
| false |
e09f4233d7f2b2cff76cde0daee108b1b631613c | urbanskii/UdemyPythonCourse | /secao04/se04E46.py | 411 | 4.375 | 4 | """
46 - Faça um programa que leia um número inteiro positivo de três dígitos (de 100 a 999).
Gere outro número formado pelos dígitos invertidos do número lido, Exemplo:
Númerolido = 123
NúmeroGerado = 321.
"""
def main():
numero = input('Digite o numero de 3 digitos: ')
print(f'Númerolido: {numero}')
print(f'Número Gerado: {numero[::-1]}')
if __name__ == '__main__':
main()
| false |
02f0bf58d7c57dac995888980e0dc1aeeb03be48 | urbanskii/UdemyPythonCourse | /secao04/se04E06.py | 519 | 4.125 | 4 | """
6 - Leia uma temperatura em graus Celsius e apresente-a convertida em graus Fahrenheit.
A fórmula de conversão é: F = C*(9.0/5.0)+32.0, sendo F a temperatura em Fahrenheit
e C a temperatura em Fahrenheit.
"""
def main():
temperatura_celsius_input = float(input('Digite a temperatura em Celsius: '))
temperatura_Fahrenheit = temperatura_celsius_input*(9.0/5.0)+32.0
print(f'Temperatura Celsius convertida em Fahrenheit: {temperatura_Fahrenheit}')
if __name__ == '__main__':
main()
| false |
9035b3faa2a4970955d628c1d91584c1a3033b9e | urbanskii/UdemyPythonCourse | /secao04/se04E14.py | 412 | 4.125 | 4 | """
14 - Leia um ângulo em graus e apresente-o convertido em radianos.
A fórmula de conversão é: R = G* π (Pi)/180, sendo G o Ângulo em graus
e R em radianos e π (Pi) = 3.14.
"""
def main():
angulo = float(input('Digite um ângulo em graus: '))
radiano = angulo * 3.14/180
print(f'Resultado do ângulo em grausº convertido em radiano: {radiano}')
if __name__ == '__main__':
main()
| false |
6701c714d5dfef2b71e9dc7f39a6c906fb73b849 | urbanskii/UdemyPythonCourse | /secao04/pep8.py | 1,731 | 4.125 | 4 | """
PEP8 - Python Enhancement Proposal
São propostas de melhorias para a linguagem Python
The Zen of Python
import this
A ideia da PEP8 é que possamos escrever códigos Pỳthon de forma Pythônica.
[1] - Utiliza Camel Case para nomes de Classes;
class Calculadora:
pass
class CalculadoraCientifica:
pass
[2] - Utilize nomes em minúsculo, separados por underline para funções ou variáveis;
def soma():
pass
def soma_dois():
pass
numero = 4
numero_impar = 5
[3] - Utilize 4 espaços para identação! (Não use tab)
if 'a' in 'banana':
print('tem')
[4] - Linhas em branco
- Separar funções e definições de classe com duas linhas em branco;
- Métodos dentro de uma classe devem ser separados com uma única linha em branco;
[5] - Imports - Imports devem ser sempre feitos em linhas separadas;
#Import Errado
import sys, os
#Import correto
import sys
import os
#Não há problemas em utilizar:
from types import StringType, ListType
#Caso tenha muitos imports de um mesmo pacote, recomenda-se fazer:
from types import {
StringType,
ListType,
SetType,
OutroType
}
#imports devem ser colocados no topo do arquivo, logo depois de quaisquer comentários ou docstrings e
#antes de constantes ou variáveis globais.
[6] - Espaços em expressões e instruções
#Não faça:
funcao(_algo[_1_], {_outro: 2_}_)
#Faça:
funcao(algo[1], {outro: 2})
#Não faça:
algo_(1)
#Faça:
algo(1)
#Não faça:
dict_['chave'] = list_[indice]
# Faça:
dict['chave'] = lista[indice]
#Não faça:
x_____________ = 1
y------------- = 3
variavel_longa = 5
# Faça
x = 1
y = 3
variavel_longa = 5
[7] - Termine sempre uma instrução com uma nova linha;
"""
import this
| false |
0cb2ccd07dd0dbe94c7e1c3722d13817762e52a0 | mattquint111/Learning-Python | /day3-assignment1.py | 512 | 4.1875 | 4 | # Assignment 1 - Factorial
#number = int(input("Enter a non-negative number: "))
# def factorial():
# soln = 1
# for i in range(1, number+1):
# soln *= i
# return soln
#print(factorial())
# Recursive factorial function
def factorial2(n):
# default solution for n == 0 (n! == 1)
soln = 1
if n == 0:
return soln
else:
# call factorial2() until n-1 == 0
soln = n * factorial2(n - 1)
return soln
# 3! == 6
print(factorial2(5)) | false |
14a4ed8730578aa3a1fcf7bf32b3096835ac221c | Clearymac/Integer-division-and-list | /task 2.py | 864 | 4.28125 | 4 | #LIST RETARRD
list = ['Evi', 'Madeleine', 'Cool guy', 'Kelsey', 'Cayden', 'Hayley', 'Darian']
#sorts and prints the list
list.sort()
print('Sorted list:', list)
#asks the user to input their name
name = input("What is your name? ")
name = name.title()
#checks if name is in list and gives option to add to list
if name in list:
print("Oh senpai! that name is already in the list asdahasdhahkshldgakshd uwu")
bruh = input("would you like to add your name or replace your name in the list or nothing? ")
bruh = bruh.lower()
if bruh == "add":
list.append(name)
print(list)
elif bruh == "replace":
replace_name = input("What of the following names would you like to replace?\n{}\n".format(list))
list = list.replace(replace_name, name)
print(list)
elif bruh == "nothing":
print("poopoo stinker")
else:
print("what are you on?")
| true |
a421d26ec9850e4430424be0c72e9109af4fb090 | yfeng75/learntocode | /python/challenge_dict.py | 1,043 | 4.125 | 4 |
locations={0: "You are sitting in front of a computer learning python",
1: "You are stadning at the endo f a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside a building, a well house for a small stream",
4: "You are in a valley beside a stream",
5: "You are in the forest"}
exits = {0:{"Q": 0},
1:{"W": 2, "E": 3,"N": 5, "S": 4 , "Q": 0},
2:{"N": 5, "Q": 0},
3:{"W": 1, "Q": 0},
4:{"N": 1, "W": 2,"Q": 0},
5:{"W": 2, "S": 1 , "Q": 0}}
letter = {"WEST":"W","EAST": "E","NORTH": "N","SOUTH": "S","QUIT": "Q"}
# print(letter.values())
loc =1
while True:
availableExits = ", ".join(exits[loc].keys())
print(locations[loc])
if loc ==0:
break
direction = input("Available exits are " +availableExits +":").upper()
print()
if letter[direction] in exits[loc]:
loc=exits[loc][letter[direction]]
else:
print("You cannot go in that direction")
| false |
a752737c13ff711f56f779e51d8457a6a105d69b | vasyanch/edu | /Vasiliev_book/mult_matrix.py | 1,917 | 4.46875 | 4 | '''
В данном коде реализованы три функции:
rand_matrix(n,m) - инициализирует и возвращает
матрицу n на m, представленную в виде вложенных списков.
unit_matrix(n) - возвр. единичную матрицу размера n.
mult_matrix(A1, A2) - возвр. произведение матриц A1 и A2.
show_matrix(A) - выводит в консоль матрицу в
мат-ом виде.
'''
from random import *
def rand_matrix(n, m):
A = [[randint(0, 9) for j in range(m)] for i in range(n)]
return A
def unit_matrix(n):
A = [[int(i == j) for j in range(n)] for i in range(n)]
return A
def mult_matrix(A, B):
n = len(A) #кол-во строк в матрице А
if n == len(B[0]):
C = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C
else:
print(''''Sorry, number of string in A must equal
number of column in B. Try again.''')
def show_matrix(a):
for i in a:
for j in i:
print(j, end = ' ')
print()
if __name__ == '__main__':
seed(2014)
A = rand_matrix(3, 5)
print('Список:', A)
print('Эта же матрица:')
show_matrix(A)
E = unit_matrix(4)
print('Единичная матрица:')
show_matrix(E)
A1 = rand_matrix(3,3)
A2 = rand_matrix(3,3)
print('Первая матрица:')
show_matrix(A1)
print('Вторая матрица:')
show_matrix(A2)
print('Произведение матриц:')
show_matrix(mult_matrix(A1, A2))
| false |
451af1ea328f3331078e6271fb0a7dcb24e8c2fd | mentalclear/autobots-fastapi-class | /typing_playground/funcs/random_stuff.py | 485 | 4.1875 | 4 | def greeting(name: str) -> str:
""" This function expects to have argument name of type string"""
return 'Hello ' + name
print(greeting('Tester'))
# A type alias is defined by assigning the type to the alias. In this example,
# Vector and list[float] will be treated as interchangeable synonyms
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector) | true |
609b61bab4602df7434e12d207ae1ff5862534cb | ChristyLeung/Python_Green | /Green/5.3.1-2 voting.py | 487 | 4.1875 | 4 | # 5.3
# 5.3.1
if conditional_test:
do something
age = 19
if age >= 18:
print("You are old enough to vote!")
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# 5.3.2
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote!")
print("Please register to vote as soon as you turn 18!")
| true |
1f8acbbc0af62fdf18d8408eade076fce2d59931 | KShaz/Machine-Learning-Basics | /python code/ANN 3-1 Supervised Simoid training.py | 1,725 | 4.125 | 4 | # https://iamtrask.github.io/2015/07/12/basic-python-network/
#X Input dataset matrix where each row is a training example
#y Output dataset matrix where each row is a training example
#l0 First Layer of the Network, specified by the input data
#l1 Second Layer of the Network, otherwise known as the hidden layer
#Syn0 First layer of weights, Synapse 0, connecting l0 to l1.
# 3 inputs, 1 output
# SUPERVISED neural network using non linear Sigmoid feedback
import numpy as np
# sigmoid function
# this nonlinearity maps a function called a "sigmoid"
# If the sigmoid's output is a variable "out", then the derivative is simply out * (1-out)
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input dataset
X = np.array([ [0,0,1],
[0,1,1],
[1,0,1],
[1,1,1] ]) # np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
# output dataset
y = np.array([[0,0,1,1]]).T #T is for mattrix transpose
# seed random numbers to make calculation deterministic. (1) is the sequence used for random
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1 # random=[0,1], we want weight=[-1,1], random(line,column), syn0 is vertical
for iter in range(10000):
# forward propagation
l0 = X
l1 = nonlin(np.dot(l0,syn0)) #l1 = nonlin (l0 x syn0), matrix-matrix multiplication
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
l1_delta = l1_error * nonlin(l1,True)
# update weights
syn0 += np.dot(l0.T,l1_delta)
print ("Output After Training:")
print (l1)
| true |
4efffd09c623ecf7c64ef4c4e1bac18dc2ec8af5 | harris44/PythonMaterial | /02_Advanced/algorithms_and_data_structures/01_Guessing_Game_with_Stupid_search.py | 1,272 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randrange
"""
Purpose: Stupid Search.
In a list of numbers, user guesses a number.
if it is correct, all is good. Else, next time, he/she will guess among the unguessed numbers.
"""
__author__ = "Udhay Prakash Pethakamsetty"
list_of_numbers = range(10, 20)
winning_number = randrange(10, 20) # place this statement in while loop, to increase probability of failure
# attempts = len(list_of_numbers)
while True:
try:
# attempts -= 1
guess_number = int(raw_input('Guess a number between 10 and 20:'))
if guess_number == winning_number:
print 'You Guessed correctly'
break
else:
list_of_numbers.remove(guess_number)
# print 'Your guess is closer by ', abs(guess_number - winning_number)
print 'You guessed larger number' if guess_number > winning_number else 'You guessed lower number'
if len(list_of_numbers) == 1: # attempts <= 1:
print 'You are STUPID. Use your brain.'
print 'Max. attempts completed. The winning number is', list_of_numbers[0]
except Exception:
print 'You STUPID! Guess properly'
# all exceptions are catched here, as user should not know the problem
| true |
741186406a63a689c06999e232429c1cd2a6eaf5 | yavar29/python_programs | /declaring_and_printing_inbuilt_data_structures.py | 664 | 4.125 | 4 | # first method of declaring a list
l=[]
l.append("saim")
l.append("yavar")
l.append("sidra")
l.append(101)
l.append(101.99)
l.append("adil")
print(l)
# second method of directly declaring a list
l1=['saim', 'yavar', 'sidra1', 1013, 101.99, 'adil1']
print(l1)
print(l1[0]+' '+str(l1[3]))
print(type(l1))
# declaring a tuple
tup=('hello','bye',33,77.8)
print(tup)
print(type(tup))
# first method of declaring a dictionary
dic={'a':'apple','b':'ball','c':'cat','d':'dog'}
print(dic)
print(type(dic))
print(dic['b'])
# second method of declaring a dictionary
dic1={}
dic1['sehwag']=101
dic1['sachin']=199
dic1['dhoni']=51
dic1['ashvin']=6
print(dic1)
| false |
854b44a67d155c0c901d010a3e7ed5fc3735761a | liboyue/BOOM | /examples/BioASQ/extra_modules/bioasq/Tiler.py | 671 | 4.3125 | 4 | import abc
from abc import abstractmethod
'''
@Author: Khyathi Raghavi Chandu
@Date: October 17 2017
This code contains the abstract class for Tiler.
'''
'''
This is an Abstract class that serves as a template for implementations for tiling sentences.
Currently there is only one technique implemented which is simple concatenation.
'''
class Tiler(object):
__metaclass__ = abc.ABCMeta
@classmethod
def __init__(self):
pass
#abstract method that should be implemented by the subclass that extends this abstract class
@abstractmethod
def tileSentences(self, sentences, pred_length):
pass
'''
instance = Tiler(["John"," has cancer"])
print instance.sentenceTiling()
'''
| true |
9c86c21e8546fd8bde9a8b41187fd54e6c25b538 | BumShubham/assignments-AcadView | /assignment8.py | 1,591 | 4.46875 | 4 | #Q1
#What is time tuple
'''
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −
Index Field Domain of Values
0 Year (4 digits) Ex.- 1995
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60/61 are leap seconds)
6 Day of Week 0 to 6 (Monday to Sunday)
7 Day of Year 1 to 366 (Julian day)
8 DST -1,0,1
'''
#Q2 Write a program to get formatted time.
import time
import math
import os
print(time.strftime("%H:%M:%S"))
#Q3 Extract month from the time.
'''The function strftime takes '2' arguments one format and another time strftime(format,t = time)
'''
print(time.strftime("%B,%m"))
#Q4 Extract day from the time
print(time.strftime("%d, %j"))
#Q5 Extract date (ex : 11 in 11/01/2021) from the time.
print(time.strftime("%d in %d/%m/%Y"))
#Q6 Write a program to print time using localtime method.
localtime = time.localtime(time.time())
print("Local current time :", localtime)
#Q7 Find the factorial of a number input by user using math package functions.
'''
Used to calculate factorial of a Number, using Math package function
Math.factorial(number) is used
'''
no=int(input('enter a no:'))
print(math.factorial(no))
#Q8 Find the GCD of a number input by user using math package functions.
'''
Used to calculate GCD of a number, using Math package function
Math.gcd(no1,no2) is used
'''
a=int(input('enter 1st no:'))
b=int(input('enter 2nd no:'))
print(math.gcd(a,b))
#Q9 Use OS package and do the following tasks: Get current working directory.Get the user environment.
print(os.getcwd())
print(os.getenv('TEMP')) | true |
8dfe63e954810cead138b81ef4c5fdf813cf224e | ShahrukhSharif/Applied_AI_Course | /Fundamental of Programming/python Intro/Prime_Number_Prg.py | 364 | 4.125 | 4 | # Wap to find Prime Number
'''
num = 10
10/2,3,4,5 ---> Number is not pN OW PN
'''
num = int(input("Input the Number"))
is_devisible = False
for i in range(2,num):
if(num%i==0):
is_devisible = True
break
if is_devisible is True:
print("Number is Not Prime {}".format(num))
else:
print("Number is Prime Number {}".format(num))
| true |
612ace04b4af232ecc5408a2c92f06620e75a17b | kitsuyui/dict_zip | /dict_zip/__init__.py | 2,086 | 4.375 | 4 | """dict_zip
This module provides a function that concatenates dictionaries.
Like the zip function for lists, it concatenates dictionaries.
Example:
>>> from dict_zip import dict_zip
>>> dict_zip({'a': 1, 'b': 2}, {'a': 3, 'b': 4})
{'a': (1, 3), 'b': (2, 4)}
>>> from dict_zip import dict_zip_longest
>>> dict_zip_longest({'a': 1, 'b': 2, 'c': 4}, {'a': 3, 'b': 4})
{'a': (1, 3), 'b': (2, 4), 'c': (4, None)}
"""
import functools
def dict_zip(*dictionaries):
"""Returns a new dictionary \
concatenated with the dictionaries specified in the argument.
The key is a common key that each dictionary has.
The value is a tuple of the values of the dictionaries.
>>> dict_zip({'a': 1, 'b': 2}, {'a': 3, 'b': 4})
{'a': (1, 3), 'b': (2, 4)}
"""
common_keys = functools.reduce(
lambda x, y: x & y, (set(d.keys()) for d in dictionaries)
)
return_dic = {}
for dic in dictionaries:
for key, val in dic.items():
if key in common_keys:
return_dic.setdefault(key, []).append(val)
return {key: tuple(val) for key, val in return_dic.items()}
def dict_zip_longest(*dictionaries, fillvalue=None):
"""Returns a new dictionary \
concatenated with the dictionaries specified in the argument.
The keys are the union set of the dictionaries.
The value is a tuple of the values of the dictionaries.
If the specified dictionary does not have the key, \
it is filled with fillvalue (default: None).
>>> dict_zip_longest({'a': 1, 'b': 2, 'c': 4}, {'a': 3, 'b': 4})
{'a': (1, 3), 'b': (2, 4), 'c': (4, None)}
"""
all_keys = __all_keys(d.keys() for d in dictionaries)
return_dic = {key: tuple() for key in all_keys}
for dic in dictionaries:
for key in all_keys:
return_dic[key] += (dic.get(key, fillvalue),)
return return_dic
def __all_keys(iterables):
keys = []
for iterable in iterables:
for key in iterable:
if key in keys:
continue
keys.append(key)
return keys
| true |
5afd548624578e174b04bec5374c778e1bbed79f | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom04/a_module.py | 1,048 | 4.15625 | 4 | """
How to mock function in a module.
In a unit test we dont want to actually read a file so we will mock
the read_file_content() function. But still test get_number_of_line_in_file().
"""
def get_number_of_line_in_file():
"""
Return how many lines exist in a file
"""
content = read_file_content()
nr_lines = 0
for _ in content:
nr_lines += 1
return nr_lines
def read_file_content():
"""
This function will be mocked
"""
with open("a file.txt", encoding="utf-8") as fd:
return fd.readlines()
def get_number_of_line_in_file_with_arg(filename):
"""
Return how many lines exist in a file.
The filename is sent as argument
"""
content = read_file_content_with_arg(filename)
nr_lines = 0
for _ in content:
nr_lines += 1
return nr_lines
def read_file_content_with_arg(filename):
"""
This function will be mocked and has an argument with can be asserted
"""
with open(filename, encoding="utf-8") as fd:
return fd.readlines()
| true |
7bc58f3621d6e04206543d4b556929e56b1c3b0f | dbwebb-se/python-slides | /oopython/example_code/vt23/kmom03/get_post_ok/src/guess_game.py | 1,766 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Main class for the guessing game
"""
import random
from src.guess import Guess
class GuessGame:
"""
Holds info for playing a guessing game
"""
def __init__(self, correct_value=None, guesses=None):
if correct_value is not None:
self._correct_value = correct_value
else:
self._correct_value = random.randint(1, 15)
self.guesses = []
if guesses:
for value, attempt, is_correct in guesses:
self.guesses.append(Guess(value, attempt, is_correct))
# self.guesses = [Guess(v, a, c) for v, a, c in guesses] if guesses is not None else [] # denna raden gör samma sak som de fyra raderna ovanför
self.guess_attempts = len(self.guesses)
def make_guess(self, guess_value):
"""
Makes a new guess and adds to list
"""
self.guess_attempts += 1
if guess_value == self._correct_value:
self.guesses.append(Guess(guess_value, self.guess_attempts, True))
return True
self.guesses.append(Guess(guess_value, self.guess_attempts))
return False
def get_correct_value(self):
""" Return private attribute """
return self._correct_value
def get_if_guessed_correct(self):
""" return if last guess was correct or not """
return self.guesses[-1].correct if self.guesses else False
def to_list(self):
""" Turn old guesses to a list """
# new_list = []
# for g in self.guesses:
# new_list.append((g.value, g.attempt, g.correct))
# return new_list
return [(g.value, g.attempt, g.correct) for g in self.guesses] # denna raden gör samma sak som de fyra raderna ovanför. | true |
9902a96d8649184b27bafe7835742d13bcec0f07 | yyyuaaaan/python7th | /crk/8.4subsets.py | 1,655 | 4.25 | 4 | """__author__ = 'anyu'
9.4 Write a method to return all subsets of a set.
gives us 2" subsets.We will therefore not be able to do better than 0(2") in time or space complexity.
The subsets of {a^ a2, ..., an} are also called the powerset, P({aj, a2, ..., an}),or just P(n).
This solution will be 0(2n) in time and space, which is the best we can do. For a slight optimization,
we could also implement this algorithm iteratively.
Generating P(n) for the general case is just a simple generalization of the above steps.
We compute P(n-l), clone the results,and then add an to each of these cloned sets.
How can we use P ( 2 ) to create P( 3 ) ? We can simply clone the subsets in P ( 2 ) and add a3 to them:
P(2) ={} , {aj, {aj, {9lJ a2}
P(2) + a3 = {a3}, {at, aj, {a2, a3}, {aaJ a2, a3}
When merged together, the lines above make P(3).
"""
def powerset2(myset):
"""
recursion, powerset is subsets!, don't be consused of the name
"""
if not myset: #l is [] wrong, but (not l) is ok
return [[]]
else: # + and append() is very different
return powerset2(myset[:-1]) + [ subset+[myset[-1]] for subset in powerset2(myset[:-1])]
def powerset(myset):
result = [[]]
for element in myset:
result += [subset+[element] for subset in result] # result.extend() also ok subset.append is wrong c
#coz [] somehow become Nonetype
# result will not change when do list operations
return result
print powerset([])
print powerset(['a','b','c'])
print powerset2(['a','b','c'])
| true |
c2ffda55f905b9d0bc11dd1cff64761490722eb0 | yyyuaaaan/python7th | /crk/4.4.py | 1,547 | 4.125 | 4 | """__author__ = 'anyu'
Implement a function to check if a tree is balanced.
For the purposes of this question, a balanced tree is defined
to be a tree such that the heights of the two subtrees of any # this is so called AVL-tree
node never differ by more than one.
"""
class Node(object):
def __init__(self):
self.data=None
self.left=None
self.right=None
def __str__(self):
return "data:"+str(self.data)+"("+str(self.left)+"|"+str(self.right)+")"+"depth:"+str(self.depth)
#O(n^2) naive algorithm
def heightoftree(t):
if not t:
return 0
else:
return max(heightoftree(t.left)+1, heightoftree(t.right)+1)
def checkavl(t):
if not t:
return True
elif abs(heightoftree(t.left)-heightoftree(t.right))<=1:
return checkavl(t.left) and checkavl(t.right)
else:
return False
#On each node, we recurse through its entire subtree.
# This means that getHeight is called repeatedly on the same nodes.
# The algorithm is therefore O(N2).
#effcient algorithm, get heights of subtrees and check subtrees if balanced at the same time O(V+E)= O()
def heightandavl(t):
"""
o(n) time and O(logn) space, space is the height
"""
if not t:
return 0
else:
h1= heightandavl(t.left)
h2= heightandavl(t.right)
if abs(h1 - h2)>1 or h1<0 or h2<0: #must include h1<0 and h2<0
return -1 # one num to denote False
# wrong! return abs(h1-h2)<=1
return max(h1, h2)+1 #if height>=0 then True
| true |
b5e756f9eec761edbd58127e9ad66d9d0ec3dae5 | tnguyenswe/CS20-Assignments | /Variables And Calculations (2)/Nguyen_Thomas_daylight.py | 1,071 | 4.28125 | 4 | '''
Name: Thomas Nguyen
Date: 1/6/20
Professor: Henry Estrada
Assignment: Variables and Calculations (2)
This program takes the latitude and day of the year and calculates the minutes of sunshine for the day.
'''
#Import math module
import math
#Gets input from user
latitude = float(input("Enter latitude in degrees: "))
day = float(input("Enter day of year (1-365): "))
#Calculates the latitude in radians instead of degrees.
latitudeinradians = math.radians(latitude)
#Calculates p - I broke it up into different variables for easier readability.
insideoftan = math.tan(.00860*(day-186))
insideofarctan = math.atan(0.9671396*insideoftan)
insideofcos = math.cos(0.2163108+ (2*insideofarctan))
p = math.asin(0.39795*insideofcos)
#Calculates d
numerator = math.sin(.01454)+math.sin(latitudeinradians)*math.sin(p)
denominator = math.cos(latitudeinradians)*math.cos(p)
d = 24 - (7.63944*math.acos(numerator/denominator))
#Prints the amount of minutes in daylight. Multiply d by 60 because d is in hours, not minutes.
print("There are about %.3f" % (d*60) + " minutes of daylight." )
| true |
722b1e1ca439affec2aed8d27f674f281ebc36bb | gg/integer_encoding | /src/integer_encoding.py | 1,339 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
from collections import deque
def encoder(alphabet):
"""
Returns an encoder that encodes a positive integer into
a base-`len(alphabet)` sequence of alphabet elements.
`alphabet`: a list of hashable elements used to encode an integer; i.e.
`'0123456789'` is an alphabet consisting of digit character elements.
"""
base = len(alphabet)
def encode(num):
if num == 0:
return [alphabet[0]]
deq = deque()
while num > 0:
num, rem = divmod(num, base)
deq.appendleft(alphabet[rem])
return list(deq)
return encode
def decoder(alphabet):
"""
Returns a decoder that decodes a base-`len(alphabet)` encoded sequence of
alphabet elements into a positive integer.
`alphabet`: a list of hashable elements used to encode an integer; i.e.
`'0123456789'` is an alphabet consisting of digit characters.
"""
base = len(alphabet)
index = dict((v, k) for k, v in enumerate(alphabet))
def decode(xs):
try:
result = 0
for i, x in enumerate(xs[::-1]):
result += (base ** i) * index[x]
return result
except KeyError:
raise ValueError("%r is not in the alphabet %r" % (x, alphabet))
return decode
| true |
273d638b3c2b9ea9bc8e8b32e59f8c45e61e7ef5 | sassy27/DAY1 | /OOP/Class instance.py | 781 | 4.125 | 4 | class employees:
raised_amount = 1.04
num_emp = 0
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
employees.num_emp += 1 # prints number of employees by adding after each emp created
def fullname(self):
return "{} {}". format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raised_amount)
emp_1 = employees("sassy","siyan", 50000)
emp_2 = employees("santi","cazzorla",5050)
employees.raised_amount = 1.10 # can change the raised amount after
print(emp_1.__dict__)
print(emp_1.fullname())
print(emp_1.raised_amount)
print(emp_1.pay)
emp_1.apply_raise() # have to use apply raise to get new figure
print(emp_1.pay)
print(employees.num_emp) | true |
4589928fdb9ae81e9d9d23b509b30a61539ebd8e | rohitx/Zelle-Python-Solutions | /Chapter2/question1.py | 289 | 4.125 | 4 | print "This program takes Celsius temperature as user \
input and outputs temperature in Fahrenheit"
def main():
celsius = input("What is the Celsius temperature?")
fahrenheit = (9/5.) * celsius + 32
print "The temperature is", fahrenheit, "degrees Fahrenheit."
main() | true |
7bcdb4a3550071c4ff668aa0f7977a1aad65ad16 | rohitx/Zelle-Python-Solutions | /Chapter3/question1.py | 349 | 4.25 | 4 | import math
print "This program computes the Volume and Surface of a sphere\
for a user-specified radius."
def main():
radius = float(raw_input("Please enter a radius: "))
volume = (4/3.) * (math.pi * radius**3)
surface = 4 * math.pi * radius**2
print "The Volume is: ", volume
print "The Surface is: ", surface
main() | true |
ca20faf4e6b8365bcbffe5f3fe94ce0c1d07c239 | PeterParkSW/User-Logins | /UserLogins.py | 1,525 | 4.4375 | 4 | #dictionary containing paired usernames and passwords that have been created
#keys are usernames, values are passwords
credentials = {}
#asks user for a new username and password to sign up and put into credentials dictionary
def signup():
new_user = input('Please enter a username you would like to use: ')
while new_user in credentials:
print('That username already exists.')
new_user = input('Please enter a different username you would like to use: ')
if new_user not in credentials:
new_pw = input('Please enter a password you would like to use: ')
credentials[new_user] = new_pw #adds the key-value pair to the credentials dictionary
print('You have successfully chosen a username and password!')
signup()
#asks the user to choose a username and password
user = input('Please enter your username: ')
pw = input('Please enter your password: ')
#checks if username and password match to an account
# if username == 'robert' and password == 'password123':
# return 'Nice, you\'re in!'
# else:
# return 'Get outta here!'
def is_valid_credentials(username, password):
if username in credentials and password == credentials.get(username):
print('Your credentials have been verified.')
return True
else:
print('Your username and password do not match.')
return False
is_valid_credentials('peter', 'park') #example to check if there is a matching username & password in credentials dictionary | true |
d5441ca9d8a467482c1341852a04c893850c10b5 | KhoobBabe/math-expression-calculator | /mathmatical expression calculator.py | 1,629 | 4.1875 | 4 | import warnings
print('Enter a mathematical expression to view its result')
#we put a while to cotinously prompt the yser to input expressions
cond = True
while cond is True:
#this ignores other warnings
warnings.simplefilter('ignore')
#input is taken here
a = input("\nEnter a mathematical expression: ")
#this shows history of the entered expressions
if a == "history":
file = open("history.txt", mode="r")
data = file.read()
print(data)
file.close()
#this clears the history
elif a == "clear":
file = open("history.txt", mode="w")
file.close()
print("Your History has been cleared :) ")
#this exits the program
elif a == "exit":
cond = False
print("program closed, Adios master :-)")
#the expression is solved here
else:
try:
b = eval(a)
print(f'The result of the entered expression is {b}.')
#the expression is stored in the file history
file = open("history.txt", mode="a")
file.write(f"{a}\n")
file.close()
print()
#if an operator i.e. +, -, *, / is missing
except TypeError:
print("Operator is missing")
continue
#if the value is divided by zero
except ZeroDivisionError:
print("Division with 0 is infinity")
continue
#this handles other errors
except Exception as e:
print(e.__class__, "has occoured")
continue
| true |
f58fce209324c621cbeebac88493ef6a9589e448 | MakarVS/GeekBrains_Algorithms_Python | /Lesson_7/les_7_task_2.py | 1,695 | 4.28125 | 4 | """
Задача № 2.
Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
"""
from random import uniform
n = 10
array = [uniform(0, 50) for _ in range(n)]
print(f'Изначальный массив - {array}')
def sort_merge(array):
"""
Сортировка методом слияния
:param array: массив
:return: отсортированный массив
"""
if len(array) <= 1:
return array[:]
else:
mid = len(array) // 2
left_array = sort_merge(array[:mid])
right_array = sort_merge(array[mid:])
return merge(left_array, right_array)
def merge(left, right):
"""
Промежуточная функция слияния двух отсортированных массивов
:param left: левый массив
:param right: правый массив
:return: отсортированный слитый массив
"""
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
print(f'Отсортированный массив - {sort_merge(array)}')
| false |
91c31541149c611200972360d1fe701328937e12 | MakarVS/GeekBrains_Algorithms_Python | /Lesson_2/Check/Lesson2/Les2_Task3.py | 436 | 4.125 | 4 | #3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
#Например, если введено число 3486, надо вывести 6843.
num = int(input("Введите число: "))
num2 = 0
while True:
num2 = num2 * 10 + num % 10
num //= 10
if num == 0:
break
print(f"{num2}")
| false |
0a0e377ff207f57bafb2cd622c772080d4559fe4 | AvyanshKatiyar/megapython | /app4/app4_code/backend.py | 2,190 | 4.3125 | 4 | import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
#id checks how many entries
def insert(title, author, year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
# id is created automatically by NULL matching somehow
conn.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title, author, year, isbn ))
conn.commit()
conn.close()
def view():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM book")
rows=cur.fetchall()
conn.close
return rows
#initializing the strings as empty values as we wont need all of them at once like can query only for auhtor as well at the starting
# basically since lets say we are looking for author name
# then as title is "" empty therefore it will return an empty value as no entry with null value yes
def search(title="", author="", year="",isbn=""):
#if year then all entries for that year
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM book WHERE title=? OR Author=? OR year=? OR isbn=?", (title, author, year, isbn))
rows=cur.fetchall()
conn.close
return rows
#use id to delete
def delete(id):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
# id is created automatically by NULL matching somehow
conn.execute("DELETE FROM book WHERE id=?", (id,))
conn.commit()
conn.close()
def update(id,title, author, year, isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
# id is created automatically by NULL matching somehow
conn.execute("UPDATE book SET title=?,author=?, year=?, isbn=? WHERE id=?", (title, author,year,isbn,id))#order matters here
conn.commit()
conn.close()
connect()
#insert("My name jef","jef",2015, 6060)
#insert("Moshi Moshi Max","Alpino",2013, 9393939)
#insert("How to how to books","Haus",1888, 939393)
#update(3,'How to how to books', 'Haus Himmelmaker', 1888, 939393)
#print(view())
#print(search(title="Moshi Moshi Max"))
#note id does not change | true |
eb740ea5b08d9f8b1cec289512d993ec5093ea42 | AvyanshKatiyar/megapython | /Not_app_code/the_basics/forloops.py | 889 | 4.1875 | 4 | monday_temperatures=[9.1, 9.7, 7.6]
#rounding
print(round(monday_temperatures[0]))
for temperature in monday_temperatures:
print(round(temperature))
#loop goes through all the variables
#looping through a dictionary
student_grades={"Marry": 9.1, "Sim": 8.8, "John": 7.5}
#chose what you want to iterate over items keys values
for grades in student_grades.items():
print(grades)
for grades in student_grades.values():
print(grades)
for grades in student_grades.keys():
print(grades)
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for a, b in phone_numbers.items():
print("%s: %s"%(a,b))
#while loops
username = ''
while username != "pypy":
username=input("Enter username: ")
#break and other stuff
while True:
username=input("Enter yo name: ")
if username== "pypy":
break
else:
continue
| true |
cecf188d0a3425dbc83dac4b9caf56f1f428b4d2 | meetashwin/python-play | /basic/countsetbits.py | 392 | 4.5 | 4 | # Program to count the set bits in an integer
# Examples:
# n=6, binary=110 => Set bits = 2 (number of 1's)
# n=12, binary=1100 => Set bits = 2
# n=7, binary=111 => Set bits = 3
def countsetbits(n):
count = 0
while(n):
count += n & 1
n >>= 1
return count
print("Enter the number to find set bits for:")
n = int(input())
print("Set bits for {0} is {1}".format(n, countsetbits(n))) | true |
5212f2d72f6162d1d169b7b583f4ff83fdf85781 | dannko97/python_github | /Algorithmic illustration_算法图解/divide and conguer_sum.py | 606 | 4.15625 | 4 |
# recursion
def DaC_sum(list):
"""sum of the elements of a list"""
if list == []:
return 0
else:
x = list[0]
return x + DaC_sum(list[1:])
def DaC_len(list):
"""number of the elements of a list"""
if list == []:
return 0
else:
return 1 + DaC_len(list[1:])
def DaC_biggest(list):
"""find the biggest element of a list"""
if list == []:
return 0
else:
x = list[0]
return max(x, DaC_biggest(list[1:]))
mylist = [2, 18, 5, 6]
# print(DaC_sum(mylist))
# print(DaC_len(mylist))
print(DaC_biggest(mylist))
| false |
6b674887d7d590d12016e60aed03cce67d284b9d | remcous/Python-Crash-Course | /Ch04/squares.py | 452 | 4.5625 | 5 | #initialize an empty list to hold squared numbers
squares = []
for value in range(1,11):
# ** acts as exponent operator in python
square = value**2
# appends the square into the list of squares
squares.append(square)
print(squares)
# more concise approach
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
# List Comprehension method to initialize list
squares = [value**2 for value in range(1,11)]
print(squares) | true |
b9854e8781e6261b6919999f85e782205aab07d1 | BD20171998/holbertonschool-higher_level_programming | /0x0A-python-inheritance/2-is_same_class.py | 686 | 4.46875 | 4 | #!/usr/bin/python3
"""
This is an example of the is_same_class function
>>> a = 1
>>> if is_same_class(a, int):
... print("{} is an instance of the class {}".format(a, int.__name__))
>>> if is_same_class(a, float):
... print("{} is an instance of the class {}".format(a, float.__name__))
>>> if is_same_class(a, object):
... print("{} is an instance of the class {}".format(a, object.__name__))
1 is an instance of the class int
"""
def is_same_class(obj, a_class):
"""
This function that returns True if the object is exactly an instance of the
specified class ; otherwise False
"""
if type(obj) is a_class:
return True
else:
return False
| true |
36bcd1fc0ec00f9ca1da87c053a7813973b4d23d | BD20171998/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 624 | 4.25 | 4 | #!/usr/bin/python3
"""This is an example of the append_write function
>>> append_write = __import__('4-append_write').append_write
>>> nb_characters_added = append_write("file_append.txt", "Holberton School \
... is so cool!\n")
>>> print(nb_characters_added)
29
"""
def append_write(filename="", text=""):
"""
Function that appends a string at the end of a text file (UTF8) and
returns the number of characters written
"""
count = 0
with open(filename, mode='a+', encoding='utf-8') as f:
for i in text:
f.write(i)
count += 1
f.close()
return count
| true |
182439b2b6788b01a954ce47777231ae3a53a0f2 | roshanpiu/PythonOOP | /12_Inheritance.py | 658 | 4.28125 | 4 | '''Inheritance example'''
class Animal(object):
'''Animal class'''
def __init__(self, name):
self.name = name
def eat(self, food):
'''eat method'''
print '%s is eating %s.' % (self.name, food)
class Dog(Animal):
'''Dog class'''
def fetch(self, thing):
'''eat method'''
print '%s goes after %s.' % (self.name, thing)
class Cat(Animal):
'''Cat class'''
def swatstring(self):
'''swatstring method'''
print '%s shreds the string.' % (self.name)
CT = Cat('Fluffy')
DG = Dog('Rover')
DG.fetch('paper')
CT.swatstring()
DG.eat('Dog food')
CT.eat('Cat food')
CT.swatstring()
| false |
b024737c383e9990ea898a749ec09a2ef3a42320 | samaroo/PythonForBeginners | /Ch7_Exercise.py | 1,064 | 4.3125 | 4 | # Notes
# Functions in "Math" Library
# use "import math" to import math library
# abs(x) will return the absolutw calue of x
# "math.ceil(x)" will round x up to the nearest integer greater than it
# "math.floor(x)" will round x down to the nearest integer less than it
# "pow(x, y)" will return x^y
#
# Functions in "Random" Library
# "random.choice(x)" where x is a list or tuple will return a random element of x
# "random.randrange(x, y)" will return a random elements between x and y
# "random.shuffle(x)" where x is a list or tuple, will shuffle x
import math
import random
# Find the hypotnuse of a triangle with sides 15 and 17
print(math.hypot(15, 17))
# convert degrees to radians and radians to degrees
print(math.radians(180))
print(math.degrees(2))
print(math.radians(270))
print(math.degrees(5))
# generate 100 random numbers between 1 and 10
sum = 0;
x = 100
for i in range(x):
num = random.randrange(1,10)
sum += num
print(num)
print("The sum is: ", sum)
print("The average is: ", sum / x) | true |
47a9a81a19167702406cdc447d564bcfbf27c94c | Yaco-Lee/Python | /Calculator/src/yacoapp.py | 1,602 | 4.1875 | 4 | # ACA ES DONDE VAMOS A DEFINIR LAS COSAS
def main():
operaciones = getOperaciones()
print("tenemos por ahora")
devuelveListaDeOperaciones(operaciones)
print("que deseas?")
accion = getAccion()
# print("poné el primer numero wacheen")
# primernumero = input()
# print("ahora el segundo")
# segundonumero = input()
# x = int(primernumero)
# y = int(segundonumero)
numerosACalcular = TomarNumeros()
busquedaEnOperaciones = operaciones.get(accion)
if numerosACalcular.len() < 2:
print("Tenias que poner dos numeros!, ahora se rompe todo")
result = busquedaEnOperaciones(numerosACalcular[0], numerosACalcular[1])
print(result)
def TomarNumeros():
numerosQuePusoElUsuario = []
print("Pone un numero")
loquepusoelusuario = input()
if type(loquepusoelusuario) == int:
numerosQuePusoElUsuario.append(int(loquepusoelusuario))
else:
print("flashaste cualca, no podes poner más numeros")
print("calculando...")
return numerosQuePusoElUsuario
def getOperaciones():
return {
"sumar": sumar,
"restar": restar,
"multiplicar": multiplicar,
"dividir": dividir,
}
def getAccion():
return input()
def restar(x,y):
return x-y
def sumar(x, y):
return x + y
def multiplicar(x,y):
return x * y
def dividir(x,y):
if y == 0:
print("no se puede dividir por cero... aún... ¬¬")
return 0
else:
return x / y
def devuelveListaDeOperaciones(listaDeOperaciones):
for a in listaDeOperaciones:
print(a)
################################################
# ACA ES DONDE VAMOS A EJECUTAR LAS COSAS
main()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.