blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
547cb83f7e01c386f187bcdf01994b6e904f859f
|
honnali/ADP_Assignment
|
/phmail.py
| 392
| 4.15625
| 4
|
#Design and Implement python code for Phone Number and Email Address Extractor using Regular Expression
import re
s1="Phone number is 5648213488,9876543210"
x=re.search("[6-9]\d{9}",s1)
print(x.group())
e='^[a-zA-Z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,6}$'
def check(email):
if(re.search(e,email)):
print("Valid")
else:
print("Invalid")
#check("ankit32.com")
check("sanmT8@gmail.com")
| false
|
95af810ee907a31e305afca8e4f7413807b82213
|
BT-WEBDEV/Volcano-Web-Map
|
/script.py
| 1,674
| 4.25
| 4
|
#folium - lets us generate a map within python
#pandas - lets us read the csv file containing volcano locations.
import folium
import pandas
#dataframe variable will let us read the txt file.
df=pandas.read_csv("Volcanoes.txt")
#map variable - this creates our map object.
map=folium.Map(location=[df['LAT'].mean(),df['LON'].mean()],zoom_start=4,tiles='Stamen Terrain')
#function color(elev) - determines color of map marker based on elevation
def color(elev):
#variable minimum to pull in the lowest elevation level
minimum=int(min(df['ELEV']))
#variable step is max elevation value minus the minmum elevation value
#then divided by 3 - for the 3 different elevation levels
step=int((max(df['ELEV'])-min(df['ELEV']))/3)
if elev in range(minimum,minimum+step):
col='green'
elif elev in range(minimum+step,minimum+step*2):
col='orange'
else:
col='red'
return col
#fg variable is the feature group - this will let us enable volcano locations on the layer control panel.
fg=folium.FeatureGroup(name="Volcano Locations")
#for loop to generate through the latitude, longitude, and name of each volcano.
for lat,lon,name,elev in zip(df['LAT'],df['LON'],df['NAME'],df['ELEV']):
#this creates our markers on the map for each volcano location.
folium.Marker([lat,lon],popup=name,icon=folium.Icon(color=color(elev))).add_to(fg)
#this adds the feature group to the map
map.add_child(fg)
#this adds the layer control panel to the map.
map.add_child(folium.LayerControl())
#this generates the map into an html file.
map.save(outfile='test.html')
| true
|
74bde0e83f315810c5a80032527d31780d6e7200
|
DavidLohrentz/LearnPy3HardWay
|
/ex3.py
| 946
| 4.5
| 4
|
# print the following text
print("I will now count my chickens:")
# print Hens and add 25 + (30/6)
print("Hens", 25 + 30.0/6)
# print Roosters calc the following
print("Roosters", 100 - 25.0 * 3 % 4)
# print this text
print("Now I will count the eggs:")
# print the following calc total
print(3.0 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
# print "Is it true that 3 + 2 < 5 - 7?"
print("Is it true that 3 + 2 < 5 - 7?")
# print True or False following calc
print(3.0 + 2 < 5 - 7)
# print string and total of two numbers
print("What is 3 + 2?", 3.0 + 2)
#print string, total of two numbers
print("What is 5 - 7?", 5.0 - 7)
# print string
print("Oh, that's why it's False.")
# print string
print("How about some more.")
# print string, True or False
print("Is it greater?", 5 > -2)
# print string, True or False
print("Is it greater or equal?", 5 >= -2)
# print string, True or False
print("Is it less or equal?", 5 <= -2)
| true
|
e9578f654f6e9e0c8f2d9a450bb7010814a36230
|
DavidLohrentz/LearnPy3HardWay
|
/ex15.py
| 740
| 4.375
| 4
|
# get the argv module ready
# from sys import argv
# tell argv what to do with the command line input
#script, filename = argv
# define txt; mode r is read only
# save filename text to txt variable
# txt = open(filename, mode = 'r')
# put in a blank line at the top
print("\n")
# print a string with filename variable
# print(f"Here's your file {filename}.")
# display the text in the filename file
# print(txt.read())
# close(txt)
# now do the same thing from input here
print("Type the filename again:")
# ask for input and assign the filename to file_again variable
file_again = input("\n> ")
# open this second filename file
txt_again = open(file_again)
# display the text in this file
print(txt_again.read())
| true
|
288b48493795a69feb81d2da83d2239c977344c4
|
jiyifan2009/calculator
|
/main.py
| 891
| 4.25
| 4
|
#Calculator
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
num1 = int(input("What's the first number?: "))
for symbol in operations:
print(symbol)
should_continue=True
#Here we select "+"
while should_continue:
operation_symbol = input("Pick an operation: ")
num2 = int(input("What's the next number?: "))
calculation_function = operations[operation_symbol]
answer= calculation_function(num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
decide=input(f"Type 'y'to continue calculating with {answer},or type 'n'to exit.")
if decide=="y":
num1 = answer
else:
should_continue=False
calculator()
calculator()
| true
|
13ac170d8fa2a582b5bd2c045142f4f7973e6509
|
yuenliou/leetcode
|
/lcof/06-cong-wei-dao-tou-da-yin-lian-biao-lcof.py
| 1,923
| 4.1875
| 4
|
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from typing import List
from datatype.list_node import ListNode, MyListNode
def reversePrint(head: ListNode) -> List[int]:
return reversePrint(head.next) + [head.val] if head else []
def reversePrint3(head: ListNode) -> List[int]:
list = []
def reverse(head: ListNode):
if not head: return
reverse(head.next)
list.append(head.val)
reverse(head)
return list
def reversePrint2(head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
# list = []
# while len(stack):
# list.append(stack.pop())
return stack[::-1]
def reversePrint1(head: ListNode) -> List[int]:
def reverse(head: ListNode) -> ListNode:
pre = None
cur = head
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
list = []
head = reverse(head)
while head:
list.append(head.val)
head = head.next
return list
def main():
"""
思路1.翻转链表
思路2.栈
思路3.递归
"""
my_list_node = MyListNode()
my_list_node.addAtTail(1)
my_list_node.addAtTail(2)
my_list_node.addAtTail(3)
my_list_node.addAtTail(4)
my_list_node.addAtTail(5)
ret = reversePrint(my_list_node.head)
print(ret)
'''剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
if __name__ == '__main__':
main()
| true
|
e6eae9ba50431852dd588b56dc975cabe2be8a98
|
73nko/daily-interview
|
/Python/matrix-spiral-print.py
| 2,042
| 4.1875
| 4
|
###
# 13-12-2020
# Hi, here's your problem today. This problem was recently asked by Amazon:
# You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix.
# Example:
# grid = [[1, 2, 3, 4, 5],
# [6, 7, 8, 9, 10],
# [11, 12, 13, 14, 15],
# [16, 17, 18, 19, 20]]
# The clockwise spiral traversal of this array is:
# 1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12
###
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
def next_direction(direction):
return {
RIGHT: DOWN,
DOWN: LEFT,
LEFT: UP,
UP: RIGHT
}[direction]
def next_position(position, direction):
if direction == RIGHT:
return (position[0], position[1] + 1)
elif direction == DOWN:
return (position[0] + 1, position[1])
elif direction == LEFT:
return (position[0], position[1] - 1)
elif direction == UP:
return (position[0] - 1, position[1])
def should_change_direction(M, r, c):
in_bounds_r = 0 <= r < len(M)
in_bounds_c = 0 <= c < len(M[0])
return (not in_bounds_r or
not in_bounds_c or
M[r][c] is None)
def matrix_spiral_print(M):
remaining = len(M) * len(M[0])
current_direction = RIGHT
current_position = (0, 0)
while remaining > 0:
r, c = current_position
print(M[r][c])
M[r][c] = None
remaining -= 1
possible_next_position = next_position(
current_position, current_direction)
if should_change_direction(M, possible_next_position[0], possible_next_position[1]):
current_direction = next_direction(current_direction)
current_position = next_position(
current_position, current_direction)
else:
current_position = possible_next_position
grid = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
matrix_spiral_print(grid)
# 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
| true
|
b628c6fcf630b12388ea72c75bec610993c7fa25
|
73nko/daily-interview
|
/Python/cal-angle.py
| 1,087
| 4.34375
| 4
|
###
# 16-01-2021
# Hi, here's your problem today. This problem was recently asked by Microsoft:
#
# Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock.
###
###
# SOLUTION
# This is primarily breaking down the problem into a formula.
# It is more tricky than algorithmically difficult, but you might encounter questions like this as warmups.
#
# The key is to understand that the hour-hand makes a full rotation in 12 hours,
# or 12 * 60 minutes. The minute hand makes a full rotation in 60 minutes.
#
# So, that gives us a factor of 360 degree / (12 * 60) for the hour hand,
# and 360 degree / 60 for the minute hand. Then we can use this to compute the angle:
###
def calc_angle(h, m):
if h < 0 or m < 0 or h > 12 or m > 60:
print('Wrong input')
if h == 12:
h = 0
if m == 60:
m = 0
hour_angle = (360 / (12.0 * 60)) * (h * 60 + m)
minute_angle = (360 / 60.0) * m
angle = abs(hour_angle - minute_angle)
angle = min(360 - angle, angle)
return angle
print(calc_angle(3, 30))
| true
|
e0c4b786df476a43bb9210912fdc1df62cfe6601
|
73nko/daily-interview
|
/Python/falling-dominoes.py
| 1,465
| 4.125
| 4
|
###
# 05-12-2020
# Hi, here's your problem today. This problem was recently asked by Twitter:
# Given a string with the initial condition of dominoes, where:
# . represents that the domino is standing still
# L represents that the domino is falling to the left side
# R represents that the domino is falling to the right side
# Figure out the final position of the dominoes. If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright.
###
class Solution(object):
def pushDominoes(self, dominoes):
N = len(dominoes)
force = [0] * N
# Populate forces going from left to right
f = 0
for i in range(N):
if dominoes[i] == 'R':
f = N
elif dominoes[i] == 'L':
f = 0
else:
f = max(f-1, 0)
force[i] += f
# Populate forces going from right to left
f = 0
for i in range(N-1, -1, -1):
if dominoes[i] == 'L':
f = N
elif dominoes[i] == 'R':
f = 0
else:
f = max(f-1, 0)
force[i] -= f
result = ''
for f in force:
if f == 0:
result += '.'
elif f > 0:
result += 'R'
else:
result += 'L'
return result
print(Solution().pushDominoes('..R...L..R.'))
# ..RR.LL..RR
| true
|
b870fbb7bf5c9ecdefd05971e372aa1242a17113
|
ismailft/Data-Structures-Algorithms
|
/LinkedLists/LinkedList.py
| 746
| 4.21875
| 4
|
#Implementation of a linked list:
class Node(object):
def __init__(self, data):
self.Data = data
self.next = None
self.prev = None
class LinkedList(object):
def __init__(self):
self.head = None
print("Linked List Created!")
def addNode(self, data):
node = Node(data)
if self.head == None:
self.head = node
else:
node.next = self.head
node.next.prev = node
self.head = node
def printList(self):
currentHead = self.head
while currentHead != None:
print(currentHead.Data)
currentHead = currentHead.next
l = LinkedList()
l.addNode(1)
l.addNode(2)
l.addNode(10)
l.printList()
| true
|
87a1288436eeb85f7d485ee347c254da06855fd6
|
loveplay1983/daily_python
|
/python_module_with_example/Text/str_cap.py
| 543
| 4.1875
| 4
|
# Manually accomplish the same functionality of string.capwords()
# separate text first then use a temp list add each part of the text in which each text has already been convert to captalized by for loop, then use join() to combine all together
# import string
text = 'hello world'
def captalize(text):
text_sep = text.split()
text_cap = []
str_cap = ' '
for item in text_sep:
each = item[0].upper() + item[1:]
text_cap.append(each)
return str_cap.join(text_cap)
result = captalize(text)
print(result)
| true
|
01882010d5ec0d5fab6e89804a09fe05c3fb1a58
|
WitheredGryphon/witheredgryphon.github.io
|
/python/HackerRank/Regex/detect_the_email_addresses.py
| 936
| 4.15625
| 4
|
'''
You will be provided with a block of text, spanning not more than hundred lines.
Your task is to find the unique e-mail addresses present in the text.
You could use Regular Expressions to simplify your task.
And remember that the "@" sign can be used for a variety of purposes!
Input Format
The first line contains an integer N (N<=100), which is the number of lines present in the text fragment which follows.
From the second line, begins the text fragment (of N lines) in which you need to search for e-mail addresses.
Output Format
All the unique e-mail addresses detected by you, in one line, in lexicographical order, with a semi-colon as the delimiter.
'''
import re
matches = []
for i in range(int(input())):
match = re.findall("\\b(?:\w|\.){1,}@(?:\w*\.*){1,}\\b", input())
matches.extend(match)
matches = (list(filter(None,matches)))
matches = ';'.join(sorted(set(filter(None, matches))))
print (matches)
| true
|
11bbb77f4b587d8863076daafee3138f29241f13
|
WitheredGryphon/witheredgryphon.github.io
|
/python/Code Wars/count_the_smiley_faces.py
| 1,457
| 4.125
| 4
|
'''
Description:
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
Example cases:
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
Note: In case of an empty array return 0.
You will not be tested with invalid input (input will always be an array).
Order of the face (eyes, nose, mouth) elements will always be the same
Happy coding!
'''
def count_smileys(arr):
smileyCount = 0
for i in arr:
if i[0] == ':' or i[0] == ';':
if len(i) == 2:
if i[1] == ')' or i[1] == 'D':
smileyCount += 1
else:
if i[1] == '-' or i[1] == '~':
if i[2] == ')' or i[2] == 'D':
smileyCount += 1
return smileyCount #the number of valid smiley faces in array/list
| true
|
bb2d4ac961ebd2e517cc2e29ebcc47011e420027
|
ruvvet/File-Rename
|
/Rename.py
| 2,862
| 4.125
| 4
|
# BATCH FILE RENAMER PROGRAM
# Rename all files within a folder using the folder name, a specified name, or last modified date as the prefix.
import os
import glob
import sys
import time
def main():
# Input the directory with all files.
# Returns all files in the folder and the # of files in the folder.
filePath = str(input('Folder path: '))
print('List of files:', os.listdir(filePath))
print('with', len(os.listdir(filePath)), 'files in', filePath)
choice = optionsMenu()
if choice == 1:
folderRename(filePath)
elif choice == 2:
inputRename(filePath)
elif choice == 3:
dateRename(filePath)
else:
print('Oops, try again.')
optionsMenu()
# Loop
goAgain = str(input('Rename more files: Y or N >>> '))
while goAgain == 'Y':
main()
print('END')
# Menu selection
def optionsMenu():
# User selects 1 of 3 options.
print('1. Rename files with dir name.')
print('2. Rename files with user input.')
print('3. Rename files with last modified date.')
choice = int(input('Option 1, 2 or 3: '))
return choice
# This function renames all files in the directory using the root dir name.
def folderRename(absFilePath):
# For each file in the directory,
# Print the name of the old file
# Print the name of the new file name
# Rename file
folderName = os.path.basename(absFilePath)
for filePath in os.listdir(absFilePath):
full_path = os.path.join(absFilePath, filePath)
print('Old:', full_path)
if os.path.isfile(full_path):
new_path = os.path.join(absFilePath, folderName + "_" + filePath)
print('Renamed to: ', new_path)
os.rename(full_path, new_path)
# This function renames all files in the directory using a user input.
def inputRename(absFilePath):
inputName = input('Input file rename prefix: ')
for filePath in os.listdir(absFilePath):
full_path = os.path.join(absFilePath, filePath)
print('Old: ', full_path)
if os.path.isfile(full_path):
new_path = os.path.join(absFilePath, inputName + "_" + filePath)
print('Renamed to:', new_path)
os.rename(full_path, new_path)
def dateRename(absFilePath):
for filePath in os.listdir(absFilePath):
full_path = os.path.join(absFilePath, filePath)
dateModified = time.strftime('%m_%d_%Y', time.localtime(os.path.getmtime(full_path)))
print('Old: ', full_path, ' >> Date Last Modified: ', dateModified)
if os.path.isfile(full_path):
new_path = os.path.join(absFilePath, dateModified + "_" + filePath)
print('Renamed to:', new_path)
os.rename(full_path, new_path)
main()
| true
|
cb97e7dd2d356b76a8fc46cb1bac5ebbea3c20ff
|
DiogoConcerva/NextPython
|
/Aula07_Aprofundamento01.py
| 882
| 4.21875
| 4
|
# coding=utf8
# Escreva um programa que pergunte nomes de alunos de uma sala de aula. O número de alunos é
# desconhecido, por isso o programa deve perguntar até que seja digitada a palavra “fim”.
# Depois, o programa deve sortear um aluno para apresentar o trabalho primeiro.
# Exemplo:
# Digite um nome: Yann
#
# Digite um nome: Camilinha
#
# Digite um nome: Richardneydson
#
# Digite um nome: Claudiane
#
# Digite um nome: fim
#
# O primeiro aluno a apresentar será: Claudiane.
import random
alunos = []
def inserir_alunos():
while True:
nome = input('Informe o nome do aluno: ').lower()
if nome == 'fim':
break
else:
alunos.append(nome.capitalize())
def sorteio():
escolha = random.randint(0, len(alunos))
return alunos[escolha]
inserir_alunos()
print(f'O primeiro aluno a apresentar será: {sorteio()}.')
| false
|
f7c6dacf0211aab0aea782506786e633e245711a
|
DiogoConcerva/NextPython
|
/Aula03_Ex06.py
| 242
| 4.125
| 4
|
# Escreva um programa que substitui as ocorrencias
# de um caractere 0 em uma string por outro caractere 1
# 010101 -> 111111
entrada = input('Entre com uma string que contenha 0: ')
print('Substituindo 0 por 1: ', entrada.replace('0', '1'))
| false
|
8cc6f71d98b5ec71e2d6dee8baba8e22641ec5de
|
DiogoConcerva/NextPython
|
/Aula05_Ex06.py
| 504
| 4.25
| 4
|
# Crie um programa que tenha uma função que receba uma lista de números inteiros e exiba todos os
# seus valores em ordem invertida. Obs.: Sem usar invert ou o fatiador com passo -1
l = []
def ordena_contrario(l):
for num in reversed(l):
print(num)
def leitura_numeros(numeros):
for c in range(numeros):
l.append(int(input(f'Informe o {c + 1}º número: ')))
ordena_contrario(l)
numeros = int(input('Quantos números deseja inserir na lista? '))
leitura_numeros(numeros)
| false
|
f5c6213aac0f6d02789e29dd82d82b3054b7e69b
|
rishabhjhaveri10/Linear-Regression
|
/linear_regression_scipy.py
| 2,337
| 4.4375
| 4
|
#This code has its inspiration from Data Science and Machine Learning with Python course by Frank Kane on www.udemy.com.
import numpy as np
from matplotlib import pyplot as plt
from scipy import stats
#Model 1
#Generating page speeds randomly with a mean of 3, standard deviation of 0.5 and for 1000 people.
page_speeds = np.random.normal(3, 0.5, 1000)
#Generating amount spent by customer randomly with a mean of 70, standard deviation of 5 and for 1000 people.
amount_spent = np.random.normal(70, 5, 1000)
#Plotting a scatter plot of page speeds vs amount spent by customer
plt.figure(1)
plt.scatter(page_speeds, amount_spent)
plt.title('Model 1')
plt.xlabel('Time taken to load a page')
plt.ylabel('Amount spent by customer')
#Performing linear regression
#Model: y = m*x + c : amount spent by customer = slope * page speeds + constant
slope, intercept, r_value, p_value, std_err = stats.linregress(page_speeds, amount_spent)
fit_line = predict(page_speeds)
plt.plot(page_speeds, fit_line, c = 'r')
plt.show()
print 'The value of r-squared is : ' + str(r_value ** 2)
good_fit(r_value)
#As we can see from the value of r-squared that if we fit a line it might not be a very good fit.
#Because the data is randomly generated and we do not have a linear relationship between variables.
#Now we build another model in which we will explicitly give a linear relationship between variables.
#Model 2
page_speeds_1 = np.random.normal(3, 0.5, 1000)
#For this model we have explicitly given a linear relationship.
amount_spent_1 = 100 - (page_speeds_1 + np.random.normal(0, 0.1, 1000)) * 1.5
plt.figure(2)
plt.scatter(page_speeds_1, amount_spent_1)
plt.title('Model 2')
plt.xlabel('Time taken to load a page')
plt.ylabel('Amount spent by customer')
slope, intercept, r_value, p_value, std_err = stats.linregress(page_speeds_1, amount_spent_1)
fit_line1 = predict(page_speeds_1)
plt.plot(page_speeds_1, fit_line1, c = 'r')
plt.show()
print 'The value of r-squared is : ' + str(r_value ** 2)
good_fit(r_value)
#We define a function to fit the line.
def predict(x):
return slope * x + intercept
#We define a function to display if it a good fit or not.
def good_fit(x):
y = x * x
if y > 0.5:
print 'It is a good fit'
else:
print 'It is not a good fit'
| true
|
bfaa2c9608606117ad7ed4bdf552f1f51feb61d5
|
namkyu/test_python
|
/test/classTest/class1.py
| 512
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
class Athlete:
def __init__(self, a_name="", a_times=[]):
## 여기서 멤버 변수를 선언해 주는 것임
self.name = a_name
self.times = a_times
def how_big(self):
return (len(self.name))
def add_time(self, time_value):
self.times.append(time_value)
def add_times(self, list_of_times):
self.times.extend(list_of_times)
c = Athlete()
d = Athlete("i am nklee")
d.add_time("1")
d.add_times(["2", "3", "4"])
print(c)
print(d)
print(d.name)
print(d.times[0:3])
| false
|
0778ccfd4830cb34d032acaf51f4dfd764f07cb3
|
marlonrenzo/A01054879_1510_assignments
|
/A3/character.py
| 1,300
| 4.34375
| 4
|
def get_character_name():
"""
Inquire the user to provide a name.
:return: a string
"""
name = input("What is your name?").capitalize()
print(f"Nice to meet you {name}\n")
return name
def create_character() -> dict:
"""
Create a dictionary including attributes to associate to a character.
:post condition: will create a character as a dictionary of attributes
:return: the information of a character as a dictionary
"""
print("\nWelcome to the Dungeon of Kather. 'Ere are where young lads, like yourself, learn to become a warrior.\n"
"It is tradition at Castor's Thrine that all younglings are placed within the walls of Kather to begin training.\n"
"The Dungeon has 25 rooms for you to traverse through and eventually escape. Go forth and slash your way through \n"
"young blood-seeker. There are monsters in this realm. Escape the dungeon with your life and you will be unstoppable.\n\n"
"Let's begin by getting to know you.........")
character = {'Name': get_character_name(), 'Alias': "You", 'HP': [10, 10], 'Inventory': [], 'position': {"x": 2, "y": 2}}
return character
# Test dictionary: {'Name': 'Marlon', 'Alias': 'You', 'HP': [10, 10], 'Inventory': [], 'position': {"x": 2, "y": 2}}
| true
|
0a571afe9dc8d96a68d51d74efbd9af73adeb66c
|
marlonrenzo/A01054879_1510_assignments
|
/A4/Question_3.py
| 1,371
| 4.34375
| 4
|
import doctest
def dijkstra(colours: list) -> None:
"""
Sort the colours into a pattern resembling dutch flag.
Capitalize all letters except for strings starting with 'b' in order to sort the way we need to.
:param colours: a list
:precondition: colours must be a non-empty list
:post condition: will return a sorted list that resembles the dutch national flag
:return: a list
>>> dijkstra(['blue', 'white', 'blue', 'red', 'red', 'white'])
['red', 'red', 'white', 'white', 'blue', 'blue']
>>> dijkstra(['blue', 'blue', 'blue', 'blue', 'red', 'white'])
['red', 'white', 'blue', 'blue', 'blue', 'blue']
"""
for i in range(0, len(colours)): # loop through the list and capitalize
if colours[i][0] != 'b':
colours[i] = colours[i].title() # only capitalize strings that don't start with 'b'
colours.sort() # sort the colours by ascii value, so that capital letters are first, lowercase strings following
for i in range(0, len(colours)): # loop through the list of colours to lowercase the capitalized strings
colours[i] = colours[i].lower()
print(colours)
def main():
"""
Call all functions to run the program.
:return: None
"""
doctest.testmod()
dijkstra(['blue', 'white', 'blue', 'red', 'red', 'white'])
if __name__ == '__main__':
main()
| true
|
cf9a22378eb8cb4bd42f5821b51ccf9123c32e4d
|
Saketh1196/Programming
|
/Python/Weather Measurement.py
| 367
| 4.21875
| 4
|
Temp=float(input("Enter the temperature in Fahrenheit: "))
Celsius=(5/9)*(Temp-32)
print("The temperature in Celsius is: ",Celsius)
while True:
if Celsius>30:
print("The Weather is too hot. Please take care")
elif Celsius<10:
print("The Weather is too Cold. Wear Warm Clothes")
else:
print("Standard Weather")
break
| true
|
3408d16e00c283cdb9f6f96b7aafa5909146beb8
|
Sumanth-Sam-ig/pythoncode
|
/quadratic.py
| 397
| 4.15625
| 4
|
print('consider the quadrtic equation of the form')
print('a*x**2+b*x+c')
print('enter the value of a ')
a=int(input())
print('enter the value of b ')
b=int(input())
print('enter the value of c ')
c=int(input())
d=b**2-4*a*c
if d<0 :
print('roots are not possible')
else :
x1=(-b+(d)**1/2 )/2*a
x2=(-b-(d)**1/2 )/2*a
print ('the roots of the equation are')
print x1
print x2
| false
|
5cbf031344cab3889dfa61b44b9739befd5abd29
|
Sumanth-Sam-ig/pythoncode
|
/sum of square and cube of series.py
| 762
| 4.21875
| 4
|
print ('Enter the number n')
a=int(input())
print('Enter the number of the mathematical operation required')
print ('')
print(""" 1 - Sum of the numbers till n
2 - sum of the squares of the numbers
3 -sum of the cubes of the numbers """)
print('\n')
b=int(input())
if b>3:
print('invalid entery')
elif b==1:
p=a-1
while(p>=0) :
a=a+p
p-=1
print('sum of n termsis',a )
elif b==2 :
p=a-1
k=a**2
while(p>=0) :
k=k+p**2
p-=1
print ('the sum of the square of the n numbers is ',k )
elif b==3 :
p=a-1
k=a**3
while(p>=0) :
k=k+p**3
p-=1
print ('the sum of the cube of the n numbers is ',k )
| true
|
76ad14efd7fd787c72dd439f54eb6fc21fd0bb57
|
Anancha/Inventing-Phoenix-Getting-to-know-Raspberry-PI-Pico
|
/1) Blink code for Raspberry PI Pico.py
| 734
| 4.125
| 4
|
#Code created by Inventing Phoenix
#1 FEB 2021
from machine import Pin # For accessing these pins using the Pin class of the machine module
import time # Time module helps in creating delays
led= Pin(25,Pin.OUT) # The Pin is assigned and the mode of the pin is set in this command
while True: # While True is used to creating a loop that will never end
led.high() # .high() will set the pin to the high logic level
time.sleep(1) # time.sleep(1) will create an delay of 1 seconds. Time can be changed inside the bracket.
led.low() # .low() will set the pin to the low logic level
time.sleep(1)
#Thank you for watch this Video Please subricbe the channel and click on the bell icon.
| true
|
054f79d1db651c486c47f347815039e0d87cdef7
|
Lucilvanio/Hello-Word
|
/Exercício 33 - Ler maior e menor número.py
| 507
| 4.1875
| 4
|
n = int(input('Digite um número: '))
n1 = int(input('Digite outro número: '))
n2 = int(input('Digite mais um número: '))
if n < n1 and n < n2:
print(f'{n} é o menor número.')
if n1 < n and n1 < n2:
print(f'{n1} é o menor número.')
if n2 < n1 and n2 < n:
print(f'{n2} é o menor número.')
if n > n1 and n > n2:
print(f'{n} é o maior número.')
if n1 > n and n1 > n2:
print(f'{n1} é o maior número.')
if n2 > n and n2 > n1:
print(f'{n2} é o maior número.')
| false
|
9eb18156516741b7e836d6aedfb9305a1b8a8c18
|
andy-j-block/COVID_Web_Scraper
|
/helper_files/get_todays_date.py
| 400
| 4.28125
| 4
|
from datetime import date
def get_todays_date():
###################
#
# This function gets today's current day and month values for later use in
# the program.
#
###################
todays_date = str(date.today())
current_day = todays_date.split('-')[2]
current_month= todays_date.split('-')[1]
return current_day, current_month
| true
|
3b883c9774629cc9194dd429045b527ad57100c2
|
EnnaSachdeva/Algorithms
|
/deepcopy_vs_shallowcopy.py
| 1,922
| 4.1875
| 4
|
import copy
class fruit:
def __init__(self, color, height, width, list1=None):
self.color = color
self.height = height
self.width = width
self.list1 = list1
print()
print("######### Testing classes #######")
apple_1 = fruit("red", 2, 3)
orange_1 = apple_1
apple_1.color = "orange"
print(apple_1.color, orange_1.color)
# test shallow copy
apple_2 = fruit("red", 2, 3)
orange_2 = copy.copy(apple_2)
apple_2.color = "orange"
print("After shallow copy: ", apple_2.color, orange_2.color)
# test deep copy
apple_3 = fruit("red", 2, 3)
orange_3 = copy.deepcopy(apple_3)
apple_3.color = "orange"
print("After deep copy: ", apple_3.color, orange_3.color)
# test for list
print()
print("######### Testing lists #######")
list1 = [1,2,3,4]
list2 = list1
list1[1] = 5
print(list1, list2)
list1 = [1,2,3,4]
list2 = copy.copy(list1)
list1[1] = 5
print("After shallow copy: ", list1, list2)
list1 = [1,2,3,4]
list2 = copy.deepcopy(list1)
list1[1] = 5
print("After deep copy: ", list1, list2)
# test for list of list
print()
print("######### Testing list of lists #######")
list1 = [[1,2,3,4]]
list2 = list1
list1[0][1] = 5
print(list1, list2)
list1 = [[1,2,3,4]]
list2 = copy.copy(list1)
list1[0][1] = 5
print("After shallow copy: ", list1, list2)
list1 = [[1,2,3,4]]
list2 = copy.deepcopy(list1)
list1[0][1] = 5
print("After deep copy: ", list1, list2)
print()
print("######### Testing lists inside classes #######")
apple_1 = fruit("red", 2, 3, [1,2,3,4])
orange_1 = apple_1
apple_1.list1[1] = 5
print(apple_1.list1, orange_1.list1)
# test shallow copy
apple_2 = fruit("red", 2, 3, [1,2,3,4])
orange_2 = copy.copy(apple_2)
apple_2.list1[1] = 5
print("After shallow copy: ", apple_2.list1, orange_2.list1)
# test deep copy
apple_3 = fruit("red", 2, 3, [1,2,3,4])
orange_3 = copy.deepcopy(apple_3)
apple_3.list1[1] = 5
print("After deep copy: ", apple_3.list1, orange_3.list1)
| false
|
b82235bfdb9c233787b1f791e34f293cf739c8dd
|
Yixuan-Lee/LeetCode
|
/algorithms/src/Ex_987_vertical_order_traversal_of_a_binary_tree/group_share_jiangyh_dfs.py
| 1,229
| 4.1875
| 4
|
"""
DFS method
Time complexity:
Space complexity: O(N)
"""
import collections
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def verticalTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
# define a map where
# the key is x coordinate
# the value is a tuple of two element (y coordinate, value)
group = collections.defaultdict(list)
def dfs(node, x, y):
# key is x coordinate
# value is a tuple (y coordinate, node value)
group[x].append((y, node.val))
if node.left is not None:
# go to left
# for sorting purpose, it changes to y+1 instead of y-1
dfs(node.left, x-1, y+1)
if node.right is not None:
# go to right
# for sorting purpose, it changes to y+1 instead of y-1
dfs(node.right, x+1, y+1)
dfs(root, 0, 0)
return [[t[1] for t in sorted(group[x])] for x in sorted(group)]
| true
|
eb0ab4d39ecbda17d7a3903c3825eeb435da3d4a
|
mozahid1/Easy-Calculator
|
/Easy_to_Calculate.py
| 1,155
| 4.1875
| 4
|
# This function adds two numbers
def add(x,y):
return x + y
# This function subtracts two numbers
def subtract(x,y):
return x - y
# This function multiplies two numbers
def multiply(x,y):
return x * y
# This function divides two numbers
def divide(x,y):
return x / y
print("Select Your Operation:-")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
while True:
# Take input from the user
choice = input("Enter choice(between 1 to 4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Try Again")
| true
|
ba6b894681b78a1023760739eb2a1731b9aa8965
|
Neveon/python-algorithms
|
/binary_search/binary_search_intro.py
| 1,102
| 4.25
| 4
|
# Iterative Binary Search
def binary_search_iterative(data, target):
# array is already sorted - we split the array in half to find if the target is
# in the upper half or lower half of the already sorted array
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
print('Indices: low is {}, mid is {}, high is {}'.format(low, mid, high))
if target == data[mid]:
return True
elif target < data[mid]:
high = mid - 1 # low half with high point of array being below mid
else:
low = mid + 1 # upper half, with low point being above mid
return False
test_arr = [2,3,5,7,8,9,11,13,15,16,21,27,32]
# print(binary_search_iterative(test_arr, 5))
# Recursive Binary Search
def binary_search_recursive(data, target, low, high):
# Check if low crossed high
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search_recursive(data, target, low, mid-1)
else:
return binary_search_recursive(data, target, mid+1, high)
| true
|
0a5d8c0250731a8347c0d80b7d926627da29e29f
|
jchaconm/PythonGroup_12
|
/Python 1/Lesson 2 - 3/Funciones Lambda reduce filter map generadores.py
| 1,961
| 4.40625
| 4
|
#Las funciones lambda tienen como finalidad ser funciones de corta sentencia, es decir son funciones creadas sobre la marcha
# el esiguente ejemplo refleja como definir esta funcion que no posee una estructura tipica de funciones
lambda argumentos: resultado
doblar = lambda num: num*2
doblar(2)
#Resultado:
4
#La funcion map toma una función y un iterable como argumentos, y devuelve un nuevo iterable con la función
#aplicada a cada argumento .
#Ejemplo del operador Map
def add_five(x):
return x + 5
nums = [11, 25, 34, 100, 23]
result = list(map(add_five, nums))
print(result)
#Resultado:
[16, 30, 39, 105, 28]
#La funcion filter ofrece una forma elegante de filtrar todos los elementos de una lista, para los que la función de
#función devuelve True.
#Usando el operador Filter
nums = [0, 2, 5, 8, 10, 23, 31, 35, 36, 47, 50, 77, 93]
result = filter(lambda x: x % 2 == 0, nums)
print(result)
#Resultado:
[2, 8, 10, 36, 50]
#La funcion reduce toma como argumentos una funcion con dos o mas parametros y una lista de elementos y obtiene
#Usando el operado filter
from functools import reduce #en python3 reduce se encuentra en modulo functools
nums = [47,11,42,13]
result = reduce(lambda x, y: x + y, nums)
print(result)
# La funcion compresora es un tipo de construcción que consta de una expresión que determina
#cómo modificar los elementos de una lista, seguida de una o varias clausulas for y, opcionalmente,
#una o varias clausulas if
cubos = [valor ** 3 for valor in lista]
print('Cubos de 1 a 10:', cubos)
#Los generadores son funciones que nos permitirán obtener sus resultados poco a poco. Es decir,
#cada vez que llamemos a la función nos darán un nuevo resultado.
# Definimos nuestra función
def pares():
index = 1
# En este caso definimos un bucle infinito
while True:
# Devolvemos un valor
yield index*2
index = index + 1
for i in pares():
print(i)
| false
|
e9d5d74c5d6667f525866164554d59d515737a31
|
makennamartin97/python-algorithms
|
/ninjainheritence.py
| 1,677
| 4.4375
| 4
|
# As you can see, peons have limited abilities. They only have default health
# point of 100 and can't attack but can only takeDamage.
# Imagine that you wanted to create a new class called Warrior. You want
# warrior to have everything that a Peon has. You also want the warrior to
# do everything that a Peon can do. In addition, however, you want to set it
# up such that
# when a warrior is created, you want the default hp to be 200!
# you want the warrior to have a default 'armor' of 70, which means 70% of the damage will be reduced.
# you want to add a new method called attack(), which returns a random integer between 10 to 20.
# you want the warrior to override the takeDamage(dmg) method. This time, its hp would only go down by 30% of dmg (as its armor would have absorbed 70% of dmg).
# Finish implementing class Warrior using inheritance.
import random
class Peon:
def __init__(self):
self.hp = 100
def takeDamage(self, dmg):
self.hp = self.hp - dmg
def returnHP(self):
return self.hp
# note that we're creating a new class Warrior that EXTENDS from an existing class Peon
class Warrior(Peon):
def __init__(self):
self.hp = 200
self.armor = 70
def attack(self):
return random.randint(10,21)
def takeDamage(self, dmg):
self.hp = self.hp - (dmg * .30)
return self.hp
# testing
warrior1 = Warrior()
warrior2 = Warrior()
print(warrior1.returnHP()) #200
print(warrior1.armor) #70
print(warrior1.attack())
print(warrior1.takeDamage(100)) #170.0
print(warrior2.takeDamage(200)) #140.0
print(warrior1.returnHP()) #170.0
print(warrior2.armor) #70
| true
|
965fe9cd22babe11276fc0efaf1fd5389498fb0e
|
makennamartin97/python-algorithms
|
/sorts/bubblesort.py
| 541
| 4.25
| 4
|
# bubble sort
# It is a comparison-based algorithm in which each pair of adjacent elements
# is compared and the elements are swapped if they are not in order.
def bubblesort(list):
# Swap the elements to arrange in order
for i in range(len(list)-1,0,-1): # start stop step
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return list
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(bubblesort(list))
| true
|
68530451a07c82d1a0c553bf6535fd0dbdf8f95f
|
makennamartin97/python-algorithms
|
/stutteringfxn.py
| 508
| 4.125
| 4
|
# Write a function that stutters a word as if someone is struggling to read it.
# The first two letters are repeated twice with an ellipsis ... and space after
# each, and then the word is pronounced with a question mark ?.
# stutter("incredible") ➞ "in... in... incredible?"
# stutter("enthusiastic") ➞ "en... en... enthusiastic?"
# stutter("outstanding") ➞ "ou... ou... outstanding?"
def stutter(word):
new = word[0] + word[1] + '... '
return new + new + word + '?'
print stutter('makenna')
| true
|
df1eba0e96c7a622d0a7f9140d2480e83e930847
|
makennamartin97/python-algorithms
|
/sorts/mergesort.py
| 922
| 4.28125
| 4
|
# merge sort
# Merge sort first divides the array into equal halves and then combines
# them in a sorted manner.
unsortedlist = [64, 34, 25, 12, 22, 11, 90]
def mergesort(unsortedlist):
if len(unsortedlist) <= 1:
return unsortedlist
# find middle pt and divide it
mid = len(unsortedlist) //2
leftlist = unsortedlist[:mid]
rightlist = unsortedlist[mid:]
leftlist = mergesort(leftlist)
rightlist = mergesort(rightlist)
return list(merge(leftlist,rightlist))
# Merge the sorted halves
def merge(left,right):
res = []
while len(left) != 0 and len(right) != 0:
if left[0] < right[0]:
res.append(left[0])
left.remove(left[0])
else:
res.append(right[0])
right.remove(right[0])
if len(left) == 0:
res = res + right
else:
res = res + left
return res
print(mergesort(unsortedlist))
| true
|
be4114feb5e61f82d58686aa757adea9a93f8296
|
makennamartin97/python-algorithms
|
/factorial.py
| 315
| 4.375
| 4
|
# Create a function that takes an integer and returns the factorial of that
# integer. That is, the integer multiplied by all positive lower integers.
# factorial(3) ➞ 6
# factorial(5) ➞ 120
# factorial(13) ➞ 6227020800
def factorial(num):
if num < 2:
return num
else:
return factorial(num-1) * num
| true
|
ebd48b50da798e04f5d06e2b47e7a6331d75d80e
|
renat33/it-academy-python-winter
|
/Hackerrank5.py
| 335
| 4.21875
| 4
|
# Напишите программу, которая считывает с клавиатуры целое число,
# вычисляет его факториал и выводит факториал на консоль.
num = int(input())
fac = 1
for i in range(1, num + 1):
num = i * fac
fac = num
print(num)
| false
|
3def48fa48e7add42ed31186c7d15327a554d68e
|
samuel-navarro/calendar
|
/date_parser.py
| 1,080
| 4.46875
| 4
|
import yearinfo
def date_str_to_tuple(date_string: str):
"""
Calculates a date tuple (day, month, year) from a date string in the format dd.mm.yyyy
:param date_string: Date string with the form dd.mm.yyyy
:return: The date tuple with three integers if the parsing was successful, None otherwise
"""
date_fields = date_string.split('.')
if len(date_fields) != 3:
return None
try:
day, month, year = (int(field) for field in date_fields)
if not _is_valid_date(day, month, year):
return None
return day, month, year
except ValueError:
return None
def _is_valid_date(day, month, year):
"""
Determines whether a date is valid
:param day: Day of the date
:param month: Month of the date
:param year: Year of the date
:return: True if the date is valid, False otherwise
"""
if not 1 <= month <= 12:
return False
days_in_month = yearinfo.get_month_to_day_dict(year)
if not 1 <= day <= days_in_month[month]:
return False
return True
| true
|
004f67d6f2cab48cd116b90937d2cdb7768c780a
|
emcd123/Rosalind_solns
|
/fibfaclog.py
| 1,483
| 4.15625
| 4
|
def factorial(n):
res = 1
for i in range(1,n+1):
res = res * i
return res
def factorial_log(n):
print("-> factorial({})".format(n))
res = 1
for i in range(1,n+1):
res = res * i
print("<- factorial: {}".format(res))
return res
def factorial2(n):
if n == 1:
return 1
else:
res = n * factorial2(n-1)
return res
def factorial2_log(n):
print("-> factorial2({})".format(n))
if n == 1:
print("<- factorial2: 1")
return 1
else:
res = n * factorial2(n-1)
print("factorial2: {}".format(res))
return res
def fibonacci(n):
new, old = 1, 0
for i in range(n-1):
new, old = new + old, new
return new
def fibonacci2(n):
if n in [1,2]:
return 1
else:
return fibonacci2(n-1) + fibonacci2(n-2)
def fibonacci_log(n):
print("-> fibonacci({})".format(n))
new, old = 1, 0
for i in range(n-1):
new, old = new + old, new
print("<- fibonacci: {}".format(new))
return new
# this function makes a function into a logging function
def log_wrap(f):
# make new function wrapped_f
def wrapped_f(*n):
print("-> {0}({1})".format(f.__name__, n))
res = f(*n)
print("<- {0}: {1}".format(f.__name__, res))
return res
return wrapped_f
def twoparams(x,y):
return 2*x - 3*y
# now we could define a logging version of any function
# by
# f_log = log_wrap(f)
| false
|
09d69fb7eb61eefa361141d80f8572862de9090a
|
atulasati/scripts_lab_test
|
/user_crud/PROG1326_Lab7_VotreNom.py
| 2,104
| 4.1875
| 4
|
import getpass
class User(object):
""" Defined user object.
create user object passing params - name, city, phone
Args:
name (str, mandatory): user name, to be provide during the user creation
city (str, mandatory): user city, to be provide during the user creation
"""
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def display_name(self):
print (self.name)
def display_city(self):
print (self.city)
def display_phone(self):
print (self.phone)
def __str__(self):
return "<User obj:%s>" %self.name
while(True):
name = input ("What is your name? ")
city = input ("%s what town do you live in ? "%name)
phone = input ("what is your cellphone number? ")
if name.strip() == '':
print("name can not be empty!")
continue
user = User(name, city, phone)
print ("user:", user)
while(True):
what_to_do = """What do you want to do ?
1 – Print
2 – Modification
a – The name
b – Town
c – Phone number
m – Print the menu
3 – Print user
4 – Exit"""
print (what_to_do)
command = ""
while (True):
command = input ("Command: ")
if command.strip() in ["4", "m"]:
break
command_list = {
"1a":user.name,
"1b":user.city,
"1c":user.phone,
"3":("Here is the information on the user \nName: %s \nTown: %s \nPhone %s") %(
user.name,
user.city,
user.phone
)
}
operation = command_list.get(command.strip())
if operation:
print (operation)
else:
if command.strip() == "2a":
new_name = input ("What is your new name? : ")
user.name = new_name
elif command.strip() == "2b":
new_city = input ("What is your new town? : ")
user.city = new_city
elif command.strip() == "2c":
new_phone = input ("What is your new new phone number? : ")
user.phone = new_phone
else:
print ("Incorrect command!")
if command == "4":
print ("Goodbye!")
break
input_key = input("Press Enter key to exit.")
if input_key == '':
break
| true
|
3b77508b910db0d8b6781964d76f25389c9597f6
|
vaibhavtwr/patterns-and-quiz
|
/python/kmtom.py
| 496
| 4.21875
| 4
|
#Python Program to Convert Kilometers to Miles
ch=int(input("enter 1 for change in kilometers to miles \n enter 2 for change in miles to kilometers"))
if (ch==1):
n=int(input("enter the distance in kilometers"))
m=0.621371*n
txt="you distance in kilometer {} and in miles {}"
print(txt.format(n,m))
elif (ch==2) :
n=int(input("enter the distance in miles"))
km=1.60934*n
txt="your distance in miles {} and in kilometers {}"
print(txt.format(n,km))
else:
print("you enter wrong choice")
| true
|
1178bb0800c6b294a4462d3e08813f772341b721
|
dklickman/pyInitial
|
/Lab 8/workspace2.py
| 982
| 4.28125
| 4
|
num_date = input("Please enter a date in mm/dd/yy format: ")
# Create variables to check against the month conditions
# and convert to an integer so we can math on it
month_check = int(num_date[0:2])
day_check = int(num_date[3:5])
year_first_value = (int(num_date[6]))
year_second_value = (int(num_date[7]))
year_check = year_first_value + year_second_value
print(month_check, day_check, year_check)
while month_check < 0 or month_check > 12:
print("That is not a valid month, please re-enter the date.")
num_date = input("Please enter a date in mm/dd/yy format: ")
while day_check < 0 or day_check > 31:
print("That is not within the range of a valid day of the month.")
num_date = input("Please re-enter the date: ")
while year_check != 4:
print("2013 is the only valid year for entry in this program.")
print()
num_date = input("Please re-enter the date: ")
print("Fin")
| true
|
9cf3a51ee95373998a0f10b48714147b82a795e2
|
dklickman/pyInitial
|
/Lab 7/Notes/7.7 Returning a List from a Function.py
| 973
| 4.375
| 4
|
# This program uses a function to create a list
# The function returns a reference to the list
def main():
# Get a list with values stored in it
numbers = get_values()
# Display the values in the list
print("The numbers are", numbers)
# The get_values() function gets a series of numbers
# from the user and stores them in a list where the
# function returns a reference to the list
def get_values():
# Create an empty list to fill
values = []
# Create a variable to control the loop
again = 'y'
# Get the values from the user and add them
# to the list
while again == 'y' or again == 'Y':
num = int(input("Enter a number: "))
values.append(num)
# Prompt user to enter another value
# or exit the loop
again = input("Enter 'y' to enter another number.")
# return the list
return values
# Call that sweet sweet main
main()
| true
|
e14f317d78a45ecac9a946cb0448c79a986f62e6
|
dklickman/pyInitial
|
/Lab 7/Notes/7.7 Working with Lists and Files Part D2 reading numbers to a file.py
| 856
| 4.1875
| 4
|
# While reading numbers from a file into a list; convert the number
# stored as a string back into an integer so math can be performed
# This program reads numbers from a file into a list
def main():
# Open the file
infile = open('numberlist.txt', 'r')
# Read the file's content into a list
numbers = infile.readlines()
# Close the file
infile.close()
# Create a loop to convert the string values stored in the
# list into integers
# Create an indexerror prevention variable
index = 0
while index < len(numbers):
# This says the value assigned to index is equal to the
# element position in the list, then we convert that to an int
numbers[index] = int(numbers[index])
index += 1
print(numbers)
# Call the main function
main()
| true
|
83e550b09a6b39a2ea66387520f1134f451d97ac
|
Adrian-Jablonski/python-exercises
|
/Guess_A_Number/Guess_A_Number.py
| 1,243
| 4.15625
| 4
|
import random
secret_number = random.randint(1, 10)
guesses_left = 5
game_over = False
print("I am thinking of a number between 1 and 10")
print("You have ", guesses_left, " guesses left.")
while game_over == False:
guess = int(input("What's the number? "))
if guess == secret_number:
print("Yes! You win!")
elif guess < secret_number and guess >= 1:
print(guess, " is too low")
guesses_left -= 1
elif guess > secret_number and guess <= 10:
print(guess, " is too high")
guesses_left -= 1
else:
print("Invalid number. Type a number between 1 and 10")
if guesses_left == 0:
print("You ran out of guesses")
elif guess != secret_number :
print("You have ", guesses_left, " guesses left.")
if guesses_left == 0 or guess == secret_number:
play_again = input("Would you like to play again? (Y or N) ").lower()
if play_again == "n":
print("Bye!")
game_over = True
elif play_again == "y":
print("I am thinking of a number between 1 and 10")
secret_number = random.randint(1, 10)
guesses_left = 5
print("You have ", guesses_left, " guesses left.")
| true
|
e5e378fabf26fec9c650ba4d624ac2720a8bbdb8
|
nehayd/pizza-deliveries
|
/main.py
| 985
| 4.1875
| 4
|
# 🚨 Don't change the code below 👇
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
add_cheese = input("Do you want extra cheese? Y or N ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
price = 15 if size == "S" else 20 if size == "M" else 25 if size == "L" else print("Please enter valid input")
if size == "S" and add_pepperoni == "Y":
extra_pepperoni = 2
elif (size == "M" or size == "L") and add_pepperoni == "Y":
extra_pepperoni = 3
elif (size == "S" or "M" or "L") and add_pepperoni == "N":
extra_pepperoni = 0
else:
print("Please enter valid input")
if (size == "S" or "M" or "L") and add_cheese == "Y":
extra_cheese = 1
elif (size == "S" or "M" or "L") and add_cheese == "N":
extra_cheese = 0
else:
print("Please enter valid input")
print("Your final bill is: $%s." %(price+extra_pepperoni+extra_cheese))
| true
|
8ee2de89c9697171cbd18ff19855e37e320b3d19
|
VasudevJaiswal/Python-Quistions-CP
|
/If-Elif-Else/02 - Test/02.py
| 842
| 4.15625
| 4
|
# Write a program to accept the cost price of a bike and display the road tax to be paid according to the following criteria :
# Cost price (in Rs) Tax
# > 100000 15 %
# > 50000 and <= 100000 10%
# <= 50000 5%
print("By Cost price of a bike - calculate road tax to be paid ")
tax = 0
Cost_Price = int(input("Enter Cost price of Bike : "))
if(Cost_Price>100000):
tax = (Cost_Price*15)/100
elif(Cost_Price>50000 and Cost_Price<=100000):
tax = (Cost_Price*10)/100
elif(Cost_Price<=50000):
tax = (Cost_Price*5)/100
print("tax is Payed by bike owner ", str(tax))
# For not close immediately
input("Press Enter to close program")
| true
|
45a80c99c1943ffe147270995fff4fe2eb827d4f
|
akhilnair111/100DaysOfCode
|
/Week1/String Slicing.py
| 542
| 4.125
| 4
|
""" Copeland’s Corporate Company also wants to update how they generate temporary passwords for new employees.
Write a function called password_generator that takes two inputs, first_name and last_name and then concatenate the last three letters of each and returns them as a string. """
first_name = "Reiko"
last_name = "Matsuki"
def password_generator(first_name, last_name):
new_pass = first_name[(len(first_name)-1)-2:] + last_name[(len(last_name)-1)-2:]
return new_pass
temp_password = password_generator(first_name, last_name)
| true
|
3be4dc6f769698dc958ceeed3e6dc4c50deda0f2
|
akhilnair111/100DaysOfCode
|
/Week2/Delete a Key using dictionaries.py
| 1,131
| 4.15625
| 4
|
""" 1.
You are designing the video game Big Rock Adventure. We have provided a dictionary of items that are in the player’s inventory which add points to their health meter. In one line, add the corresponding value of the key "stamina grains" to the health_points variable and remove the item "stamina grains" from the dictionary. If the key does not exist, add 0 to health_points.
2.
In one line, add the value of "power stew" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points.
3.
In one line, add the value of "mystic bread" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points.
4.
Print available_items and health_points. """
available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20
health_points += available_items.pop("stamina grains", 0)
health_points += available_items.pop("power stew", 0)
health_points += available_items.pop("mystic bread", 0)
print(available_items)
print(health_points)
| true
|
6bb25eb72442be16fde69b5bba6cccfafd93010b
|
akhilnair111/100DaysOfCode
|
/Week3/part_of_speech.py
| 2,399
| 4.15625
| 4
|
""" . Import wordnet and Counter
from nltk.corpus import wordnet
from collections import Counter
wordnet is a database that we use for contextualizing words
Counter is a container that stores elements as dictionary keys
2. Get synonyms
Inside of our function, we use the wordnet.synsets() function to get a set of synonyms for the word:
def get_part_of_speech(word):
probable_part_of_speech = wordnet.synsets(word)
The returned synonyms come with their part of speech.
3. Use synonyms to determine the most likely part of speech
Next, we create a Counter() object and set each value to the count of the number of synonyms that fall into each part of speech:
pos_counts["n"] = len( [ item for item in probable_part_of_speech if item.pos()=="n"] )
...
This line counts the number of nouns in the synonym set.
4. Return the most common part of speech
Now that we have a count for each part of speech, we can use the .most_common() counter method to find and return the most likely part of speech:
most_likely_part_of_speech = pos_counts.most_common(1)[0][0]
Now that we can find the most probable part of speech for a given word, we can pass this into our lemmatizer when we find the root for each word. Let’s take a look at how we would do this for a tokenized string:
tokenized = ["How", "old", "is", "the", "country", "Indonesia"]
lemmatized = [lemmatizer.lemmatize(token, get_part_of_speech(token)) for token in tokenized]
print(lemmatized)
# ['How', 'old', 'be', 'the', 'country', 'Indonesia']
# Previously: ['How', 'old', 'is', 'the', 'country', 'Indonesia']
Because we passed in the part of speech, “is” was cast to its root, “be.” This means that words like “was” and “were” will be cast to “be”. """
import nltk
from nltk.corpus import wordnet
from collections import Counter
def get_part_of_speech(word):
probable_part_of_speech = wordnet.synsets(word)
pos_counts = Counter()
pos_counts["n"] = len( [ item for item in probable_part_of_speech if item.pos()=="n"] )
pos_counts["v"] = len( [ item for item in probable_part_of_speech if item.pos()=="v"] )
pos_counts["a"] = len( [ item for item in probable_part_of_speech if item.pos()=="a"] )
pos_counts["r"] = len( [ item for item in probable_part_of_speech if item.pos()=="r"] )
most_likely_part_of_speech = pos_counts.most_common(1)[0][0]
return most_likely_part_of_speech
| true
|
40a07ac8623ec825f9262ff5bb2839076ca5885a
|
luismelendez94/holbertonschool-higher_level_programming
|
/0x06-python-classes/3-square.py
| 486
| 4.3125
| 4
|
#!/usr/bin/python3
"""This is the class Square"""
class Square:
"""Compute the area of the square"""
def __init__(self, size=0):
"""Initialize variable size"""
try:
self.__size = size
if size < 0:
raise ValueError("size must be >= 0")
except TypeError:
raise TypeError("size must be an integer")
def area(self):
"""Compute the area size of a square"""
return self.__size ** 2
| true
|
944a48e3b0f0714cab53057649706393df849e5e
|
luismelendez94/holbertonschool-higher_level_programming
|
/0x06-python-classes/5-square.py
| 1,003
| 4.375
| 4
|
#!/usr/bin/python3
"""This is the class Square"""
class Square:
"""Print a square"""
def __init__(self, size=0):
"""Initialize variable size"""
self.__size = size
def area(self):
"""Compute the area size of a square"""
return self.__size ** 2
@property
def size(self):
"""Setter: Retrieve the size"""
return self.__size
@size.setter
def size(self, value):
"""Getter: Set and verify the size"""
try:
self.__size = value
if value < 0:
raise ValueError("size must be >= 0")
except TypeError:
raise TypeError("size must be an integer")
def my_print(self):
"""Print the square"""
if self.__size != 0:
for i in range(self.__size):
for i in range(self.__size):
print("#", end="")
if i != self.__size:
print()
else:
print()
| true
|
bae61c16ce9f880b3b0041b229e69deee721f74f
|
luismelendez94/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/0-add_integer.py
| 445
| 4.3125
| 4
|
#!/usr/bin/python3
"""Function that make an integer addition
Verifies if it is an integer and if float,
converts it to integer
"""
def add_integer(a, b=98):
"""Function that adds 2 integers"""
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError("a must be an integer")
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError("b must be an integer")
return int(a) + int(b)
| true
|
c5e4053bab655882d4530e2d197fdf5a5b2625a1
|
akhsham/Karademy-Python-Boot-Camp--Aksham-
|
/week1/karademy_python_calculator/karademy_python_calculator.py
| 990
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 12:32:42 2020
@author: darian
"""
num1 = int(input("please insert a number: "))
num2 = int(input("please insert another number: "))
operator = int(input("Please select operator: \n"
"1 => Add [A + B] \n"
"2 => Subtract [A - B]\n"
"3 => Multiply [A * B]\n"
"4 => Divide [A / B]\n"
":"
))
def add (input1 , input2):
return (input1 + input2)
def sub (input1 , input2):
return (input1 - input2)
def mlt (input1 , input2):
return (input1 * input2)
def dev (input1 , input2):
return (input1 / input2)
if operator == 1:
print("RESULT: " , add( num1 , num2 ))
if operator == 2:
print("RESULT: " , sub( num1 , num2 ))
if operator == 3:
print("RESULT: " , mlt( num1 , num2 ))
if operator == 4:
print("RESULT: " , dev( num1 , num2 ))
| false
|
f71e1facae36061727ccd6673297ab8da0a09bbf
|
cjoelfoster/pythagorean-triple-finder
|
/pythagorean-triples.py
| 2,349
| 4.625
| 5
|
#! /usr/bin/env python3.6
## Find all pythagorean triples within a specified range of values
# 1) input a value, 'z'
# 2) find all pythagorean triples such that x^2 + y^2 = z^2, 0<=x<=z, 0<=y<=z
# 3) return the list of triples in ordered by increasing z, x, y
# 4) future development: include a lower bound for 'z' such that
# z1<=x<=z2, z1<=y<=z2
# setup
import sys
import subprocess
import time
def get_bounds():
"""Ask user for an upper bound and returns a list containing an upper and lower bound"""
lower_bound = 0
upper_bound = input("Please enter a whole number: ")
domain = [lower_bound, upper_bound]
return domain
def find_triples(domain):
"""mathematical basis:
pythagorean triples are tuples of whole numbers, (x, y, z) which satisfy the equation x^2 + y^2 = z^2.
let z_lower-bound > zero (i.e. ignore trivial solution x = y = z = 0), then z_lower-bound <= z <= z_upper-bound is a set (i.e. list) of all pythagorean triples which satisfy z_lower-bound <= sqrt(x^2 + y^2) <= z_upper-bound.
This implies that x^2 + y^2 >= (z_lower-bound)^2 AND x^2 + y^2 <= (z_upper-bound)^2. Which further implies that for x, y not equal to zero (further ignoring all trivial solutions of the form a^2 + 0^2 = z^2), we have that x, y > z_lower-bound AND x, y < z_upper-bound.
Then we can incrementally look at the validity of solutions where we incrementally fix the independent variable (z) and one of the dependent variables while whe increment the other independent variable between the bounds."""
if(domain.first < domain.last):
#Obviously this cannot work with x,y restricted to be within the bounds of z because even for the elementary 5,4,3 tuple if you restricted 4<z<6 our tuple would be invalid; so the domains for x and y have to be any whole number between zero and z_upper-bound exclusive.
for z in range(domain.first, domain.last):
for x in range(domain.first + 1, domain.last - 1):
for y in range(domain.first + 1, domain.last -1)
# verify import
print(sys.version_info)
time.sleep(0.5)
# initialize screen
# Begin Sandbox
Initialize_sandbox(name)
n = ""
while(n !=':q:'):
n = input(":: ")
if(n==':q:'):
print("Goodbye!")
elif(n==' '):
Initialize_sandbox(name)
else:
print(" " + n)
#exit
subprocess.call("clear")
| true
|
7f5c0c8a59160d9d8bf765dc38062c929da37be4
|
Banti374/Sorting-Algorithms
|
/insertion sort.py
| 556
| 4.1875
| 4
|
def insertionSort():
arr = []
r = int(input("Enter the length of the array : "))
i = 1
while i <= r:
x = int(input("Enter the value : "))
i += 1
arr.append(x)
print(arr)
n = len(arr)
for i in range(1,n):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i])
insertionSort()
| false
|
ea644a40d55c45f5698fac5f0ec3148aceac4101
|
Gelitan/IwanskiATLS1300
|
/Animating with Turtles/PC02_20200131_Iwanski.py
| 2,797
| 4.40625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 09:41:11 2020
@author: analiseiwanski
"""
#========
#PC02-Animating with Turtles
#Analise Iwanski
#200131
#
#This code creates an abstract animation of tangent circles with radii based on the fibonacci sequence, then creates a red and blue
#opposite strings of semicircles to make a strand of DNA
#========
from turtle import * #fetches turtle commands
import numpy as np #from Dr. Z's programming mathematical equations doc
window = Screen()
window.setup(800, 800, 100, 100) #setting up the window
window.bgcolor("black")
circleWhite = Turtle() #naming and creating the first turtle
circleWhite.color("white")
circleWhite.shape("triangle")
circleWhite.turtlesize(0.5)
circleWhite.pensize(3)
circleWhite.penup()
circleWhite.speed(10)
fibonacciNumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] #got list of fibonnaci numbers from https://www.mathsisfun.com/numbers/fibonacci-sequence.html
numberOfNumbers=len(fibonacciNumbers) #gives value of the length of the list, learned from https://www.geeksforgeeks.org/find-size-of-a-ist-in-python/
circleWhite.pendown()
#use for loops to create circles for the number of fibonnaci numbers
for i in range(numberOfNumbers):
circleWhite.circle(fibonacciNumbers[i],360)
#use for loops to create circles for the number of fibonnaci numbers, but mirrored horizontally
for i in range(numberOfNumbers):
circleWhite.circle(-fibonacciNumbers[i],360)
halfCircleRed = Turtle() #creating second turtle
halfCircleRed.color("red")
halfCircleRed.shape("turtle")
halfCircleRed.turtlesize(0.5)
halfCircleRed.pensize(3)
halfCircleRed.penup()
halfCircleRed.speed(8)
halfCircleRed.goto(-300,0)
halfCircleRed.pendown()
halfCircleRed.left(90)
evens = [0,2,4,6,8,10,12,14]
odds = [1,3,5,7,9,11,13,15]
#drawing the animation to create the red semicircles
for h in range(15): #chose 15 as the number of semicircles, created semicircles that face opposite by creating different rule for evens and odds
if h in evens:
halfCircleRed.right(180)
halfCircleRed.circle(20,180)
if h in odds:
halfCircleRed.left(180)
halfCircleRed.circle(20,-180)
halfCircleBlue = Turtle() #creating third turtle
halfCircleBlue.color("blue")
halfCircleBlue.shape("turtle")
halfCircleBlue.turtlesize(0.5)
halfCircleBlue.pensize(3)
halfCircleBlue.penup()
halfCircleBlue.speed(8)
halfCircleBlue.goto(300,0)
halfCircleBlue.pendown()
halfCircleBlue.right(90)
evens = [0,2,4,6,8,10,12,14]
odds = [1,3,5,7,9,11,13,15]
#drawing the animation to create the blue semicircles
for k in range(15):
if k in evens:
halfCircleBlue.right(180)
halfCircleBlue.circle(20,180)
if k in odds:
halfCircleBlue.left(180)
halfCircleBlue.circle(20,-180)
| true
|
9f68fc23bba9abef83216264a9233d696495f81f
|
coflin/Intrusion-Detection-System
|
/shaktimaan/bashmenu/HiddenPython
| 893
| 4.4375
| 4
|
#!/usr/bin/python
import os
#Code for searching the hidden files in the given directory
path=raw_input("Enter the path : ")
print("---------------------------------------------")
def hiddenFile(path):
for root,dirs,files in os.walk(path,topdown=False): #looping through the directory '.' means current working directory
for dirname in dirs:
if(dirname[0]=="."): #if the directory name starts with .
print (os.path.abspath(os.path.join(root)))
print(dirname) #print the directory name
print("------------------------------------------")
for filename in files: #looping through the files in the directory
if(filename[0]=="."): #if the file starts with '.'
print (os.path.abspath(os.path.join(root)))
print(filename) #print file name
print("------------------------------------------")
if(os.path.exists(path)):
hiddenFile(path)
else:
print "Wrong path"
| true
|
1ef857b41c9d6449388b6026d28487716534fdd6
|
quezada-raul-9060/CS161_Final_Project
|
/CS161_project/Brick_class.py
| 1,048
| 4.15625
| 4
|
class theBrick(object):
"""
Created a class for the brick.
The class is for a brick/rectangle created.
Will make a hitbox for the brick.
"""
def __init__(self, x, y, width, height):
"""
Sets variables for the brick.
This code gives the specifics of the brick.
Like his dimensions location.
Parameters
----------
arg1 : int
Takes integer to represent coordinate x.
arg2 : int
Takes integer to represent coordinate y.
arg3 : int
Takes integer to represent the width of the brick.
arg4 : int
Takes integer to represent the height of the brick.
"""
self.x = x
self.y = y
self.width = width
self.height = width
self.hitbox = (self.x + 150, self.y + 300, 60, 20)
def draw(self, window):
self.hitbox = (self.x + 150, self.y + 300, 60, 20)
pygame.draw.rect(window, (0, 255, 0), self.hitbox, 2)
| true
|
e68f3a6816d2008674f8fe1f67f1fab62c97a619
|
HoaiHoai/btvn-vuthithuhoai
|
/Assignment1/2.py
| 320
| 4.15625
| 4
|
import math #library needed to use method acos
pi = math.acos(-1) #get pi value 3.1459265359 (arc cosine of -1 = pi)
radius = float(input("Radius? ")) #read input 'radius' from user
area = radius ** 2 * pi #calculate area r^2*pi
print("Area = %.2f" % area) #print out with 2 numbers after decimal point
| true
|
350a83984b3caf17099ade37124fac67b08f6cab
|
Jeremalloch/edX-6.00.1x
|
/Week 2/Credit card debt 2.py
| 878
| 4.25
| 4
|
#balance - the outstanding balance on the credit card
#annualInterestRate - annual interest rate as a decimal
#monthlyPaymentRate - minimum monthly payment rate as a decimal
#Month: 1
#Minimum monthly payment: 96.0
#Remaining balance: 4784.0
#balance = 4213
#annualInterestRate = 0.2
#monthlyPaymentRate = 0.04
minimumPaymentTotal=0
for month in range(1,13):
minimumPayment=round(balance*monthlyPaymentRate,2)
unpaidBalance=balance-minimumPayment
interest=round((annualInterestRate/12)*unpaidBalance,2)
balance=unpaidBalance+interest
print('Month: ' + str(month))
print('Minimum monthly payment: '+ str(minimumPayment))
print('Remaining balance: ' + str(balance))
minimumPaymentTotal+=minimumPayment
remamingBalance=balance
print('Total paid: '+str(minimumPaymentTotal))
print('Remaining balance: '+ str(remamingBalance))
| true
|
7876bbb52fea9a7cce825001ec66dbb730307eca
|
richard-yap/Lets_learn_Python3
|
/module_11_file_ops.py
| 880
| 4.21875
| 4
|
#------------------------------File operations---------------------------------
f = open("file.txt", "r") #reading a File
# "w" write File
# "a" append file
#teacher example:
f = open("test.txt", "w") # write or overwrite it
for i in range(10):
f.write("This is line {}\n".format(i + 1)) #must write \n if not the text will keep going and going
# you have to do this in order to view the file as the file is still in yr RAM, do this
#and it will go to the hardisk
f.close()
# do it this way if you dw to forget to f.close()
with open("test.csv", "a") as f # this is to add more things to the file (appending)
for i in range(10):
f.write("This is line {}\n".format(i + 1))
#if you want csv change it to .csv
#getting uniquue words
# save an article into article.txt first
f = open("article.txt), "r")
texr = f.read()
len(set(text.split()))
| true
|
91f28cba112f73d8778bf3b753991ad7543d1ae3
|
richard-yap/Lets_learn_Python3
|
/module_7_list_comprehension.py
| 2,260
| 4.15625
| 4
|
#--------------------------LIST COMPREHENSION-------------------------------
# syntatic sugar
# python advanced shortcuts
# unique in python
[n ** 2 for n in range(10)]
#map method
list(map( lambda x : x ** 2, range(10)))
#map + filtering
# the filter will be done on the data before the map
[n ** 2 for n in range(10) if not n % 2]
#exercise
[n ** 2 for n in range(1, 100) if not n % 3 and not n % 5][:20]
#teacher's answers:
is_divisible = lambda x, y : x % y == 0
list_1 = [n ** 2 for n in range(100) if not is_divisible(n, 3) and not is_divisible(n, 5)][:20]
#exercise 2
ex = "Today is a great day"
[w[0] for w in ex.split()]
# or
words = ex.split()
get_first_letter = lambda x: x[0]
[get_first_letter(x) for x in words]
#------------------------------SET COMPREHENSION------------------------------
# same thing as how you'd write a list comprehension but in curly brackets {}
{get_first_letter(x) for x in words}
#------------------------------DICT COMPREHENSION------------------------------
{i : i*i for i in range(1, 11) if i % 2 == 0}
#----------------------------------GENERATOR-----------------------------------
# generator is like a ticket machine
# only if you want to have a more efficient method to compute yr result
# since it takes up less RAM space
# two types
# generator expression is also known as a comprehension but in the form of a tuples
# generator
#using the list() function will cause the memory to pull out all the numbers
#gives a generator because python is using generator
mygen = (n * n for n in range(10))
# only one number is pulled out at one time
#compared to for loops for loops is like an automated ticketing machine, will keep calling next
next(mygen)
# using the loop method
#however you can only loop one time
for i in mygen:
print(i)
#exercise
namelist = ["ally", "jane", "berlinda"]
name_gen = (i.capitalize() for i in namelist)
next(name_gen)
#--------------------------------GENERATOR FUNCTION----------------------------------
# for generator loops you have to use yield, not return
# if your logic is more compliacated
def even(n):
for i in range(n):
if i % 2 == 0 : yield i:
test = even(10)
next(test)
| false
|
434cf9470be72b22b2b04218eeb9aa1c378d623e
|
barrymcnamara18/IoT-Software-Dev
|
/Examples/4_strings.py
| 892
| 4.1875
| 4
|
####################
## EXAMPLE: for loops over strings
####################
s = "idemou loops"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print("There is an i or u")
print "Here we do again ..."
for char in s:
if char == 'i' or char == 'u':
print("There is an i or u")
break
####################
## EXAMPLE: while loops and strings
## CHALLENGE: rewrite while loop with a for loop
####################
# an_letters = "aefhilmnorsxAEFHILMNORSX"
# word = input("I will cheer for you! Enter a word: ")
# times = int(input("Enthusiasm level (1-10): "))
#
# i = 0
# while i < len(word):
# char = word[i]
# if char in an_letters:
# print("Give me an " + char + "! " + char)
# else:
# print("Give me a " + char + "! " + char)
# i += 1
# print("What does that spell?")
# for i in range(times):
# print(word, "!!!")
| false
|
b7cb25e3ad93ba04ec69d0d9e9b5764af206917e
|
fmeccanici/thesis_workspace
|
/gui/nodes/tutorials/getting_started.py
| 1,210
| 4.125
| 4
|
## https://techwithtim.net/tutorials/pyqt5-tutorial/basic-gui-application/
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow,self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(200,200,300,300) # sets the windows x, y, width, height
self.setWindowTitle("My first window!") # setting the window titl
self.label = QLabel(self)
self.label.setText("my first label")
self.label.move(50, 50) # x, y from top left hand corner.
self.b1 = QtWidgets.QPushButton(self)
self.b1.setText("click me")
self.b1.move(100,100) # to move the button
self.b1.clicked.connect(self.button_clicked) # inside main function
def button_clicked(self):
print("clicked") # we will just print clicked when the button is pressed
self.label.setText("you pressed the button")
self.update()
def update(self):
self.label.adjustSize()
def window():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
window()
| true
|
2ebe3ca2166f2c0d23723d7b470649a980589bf8
|
pacefico/crackingcoding
|
/hackerrank/python/stacks_balanced_brackets.py
| 1,397
| 4.375
| 4
|
"""
A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].
Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {)
occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type.
There are three types of matched pairs of brackets: [], {}, and ().
url: https://www.hackerrank.com/challenges/ctci-balanced-brackets
"""
import re
def is_matched(expression):
open_brackets = ["[", "{", "("]
close_brackets = ["]", "}", ")"]
stack = []
for item in expression:
if item in open_brackets:
stack.append(item)
else:
if len(stack) == 0 or stack.pop() != open_brackets[close_brackets.index(item)]:
return False
return True if len(stack) == 0 else False
def original_tests():
t = int(input().strip())
for a0 in range(t):
expression = input().strip()
if is_matched(expression) == True:
print("YES")
else:
print("NO")
def my_tests():
def case0():
return "{[()]}"
def case1():
return "{[(])}"
def case2():
return "{{[[(())]]}}"
def case3():
return "{{[[(())]]}}["
assert is_matched(case0()) == True
assert is_matched(case1()) == False
assert is_matched(case2()) == True
assert is_matched(case3()) == False
my_tests()
| true
|
404d0bb546bbdde263fecebafd3cbc2d692d8539
|
leasoussan/DIpython
|
/week5/w5d2/w5d2xp/w5d2xp.py
| 2,891
| 4.5
| 4
|
# # Exercise 1 : Pets
# # Consider this code
# class Pets():
# def __init__(self, animals):
# self.animals = animals
# def walk(self):
# for animal in self.animals:
# print(animal.walk())
# class Cat():
# is_lazy = True
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def walk(self):
# return f'{self.name} is just walking around'
# def __repr__(self):
# return self.name
# # to get the name in representing
# class Bengal(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# class Chartreux(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# class Persian(Cat):
# def speak(self, sounds):
# return f'{sounds}'
# # #
# # # Add another cat breed
# # # Create a list of all of the pets (create 3 cat instances from the above)
# # my_cats = []
# # # Instantiate the Pet class with all your cats. Use the variable my_pets
# # # Output all of the cats walking using the my_pets instance
# # cat1 = Bengal("Jojo",12)
# # cat2 = Chartreux("Liri",6)
# # cat3 = Persian("loan",3)
# my_cats = [Bengal("Jojo",12), Chartreux("Liri",6), Persian("loan",3)]
# # they inherit form Cat - creat 3 object from 3 a subclass of the class cat
# my_pets = Pets(my_cats)
# my_pets.walk()
# #
#
#
#
# Exercise 2 : Dogs
# Create a class named Dog with the attributes name, age, weight
# Implement the following methods for the class:
# bark: returns a string of “ barks”.
# run_speed: returns the dogs running speed (weight/age *10).
# fight : gets parameter of other_dog,
# returns string of which dog won the fight between them,
# whichever has a higher run_speedweight* should win.
class Dog():
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def bark(self):
print("Barks")
def run_speed(self):
return ((self.weight/self.age) * 10 )
def fight(self, other_dog):
if (self.run_speed() * self.weight) > (other_dog.run_speed()* other_dog.weight):
return f"{self.name} won the battle"
return f"{other_dog.name} wont the battle"
d1 = Dog("Jojo", 12, 12)
d2 = Dog("Riri", 9, 16)
d3 =Dog("Fifi", 4, 2)
# Create 3 dogs and use some of your methods
# TRY WITH CALL
# class Dog():
# def __call__(self, name, age, weight):
# self.name = name
# self.age = age
# self.weight = weight
# def bark(self):
# print("Barks")
# def run_speed(self):
# return ((self.weight/self.age) * 10 )
# def fight(self, other_dog):
# other_dog = Dog()
# if (self.run_speed * self.weight) > other_dog:
# return f"{self.name} won the battle"
# return f"{other_dog.name} wont the battle"
| true
|
a149fd11632bbeca1fe86340029eec23e55cdb1a
|
leasoussan/DIpython
|
/week4/w4d3/w4d3xpninja.py
| 1,665
| 4.15625
| 4
|
# Don’t forget to push on Github
# Exercise 1: List Of Integers - Randoms
# !! This is the continuation of the Exercise Week4Day2/Exercise 2 XP NINJA !!
# 2. Instead of asking the user for 10 integers, generate 10 random integers yourself. Make sure that these random integers lie between -100 and 100.
# 3. Instead of always generating 10 integers, let the amount of integers also be random! Generate a random positive integer no smaller than 50.
# 4. Go back and check all of your output! Does your code work correctly for a list of unknown length, or does it only work correctly for a list that has 10 items in it?
# 5.
# Exercise 2: Authentication CLI - Login:
# Create a menu using a while loop and user input (see week 4 day 2 exercise xp7)
# Create a dictionary that contains users: each key will represent a username, and each value will represent that users’ password. Start this dictionary with 3 users & passwords
# Add a menu option to exit
# Add a menu option called login: when a user selects login, take 2 inputs from him and check if they match up with any users in our dictionary
# Print a message on if they logged in successfully or not
# If successful try and store the username in a variable called logged_in so we can track it later
# Exercise 3: Authentication CLI - Signup:
# Continues authentication CLI - login
# Add another option of signup to our menu:
# Take input for username and make sure it doesn’t exist as a key in our dictionary, keep asking the user for a valid username as long as it is required
# Take input for a password (do you want to add criteria to password strength? How would you go about implementing that?)
| true
|
4f96e87e1178254694b5e1beafafe6599d25dc97
|
Ehotuwe/Py111-praktika1
|
/Tasks/a3_check_brackets.py
| 951
| 4.3125
| 4
|
def check_brackets(brackets_row: str) -> bool:
"""
Check whether input string is a valid bracket sequence
Valid examples: "", "()", "()()(()())", invalid: "(", ")", ")("
:param brackets_row: input string to be checked
:return: True if valid, False otherwise
"""
brackets_row = list (brackets_row)
a = ')'
b = '('
check = True
if len(brackets_row) % 2:
check = False
else:
while len (brackets_row) and check:
if brackets_row[0] == b and brackets_row[1] == a:
brackets_row.pop(0)
brackets_row.pop(0)
elif brackets_row[-1] == a and brackets_row[-2] == b:
brackets_row.pop(-1)
brackets_row.pop(-1)
elif brackets_row[0] == b and brackets_row[-1] == a:
brackets_row.pop(0)
brackets_row.pop(-1)
else:
check = False
return check
| true
|
329f9021dc36cb1c1f29b986aa1ec9377c9b351d
|
dkaimekin/webdev_2021
|
/lab9/Informatics_4/d.py
| 223
| 4.21875
| 4
|
number = int(input("Insert number: "))
def is_power(number):
if number == 1:
print("YES")
elif number < 1:
print("NO")
else:
is_power(number/2)
return 0;
is_power(number)
| false
|
b781edf2a60aca47feb2a0800a8f3e2c8c27a2de
|
dkaimekin/webdev_2021
|
/lab9/Informatics_4/e.py
| 220
| 4.46875
| 4
|
number = int(input("Insert number: "))
def find_power_of_two(number):
temp = 1
power = 0
while temp < number:
temp *= 2
power += 1
return power
print(find_power_of_two(number))
| true
|
ef068651162e5a8954b8a0a9880c4810245f0d6e
|
hemanth430/DefaultWeb
|
/myexp21.py
| 1,462
| 4.40625
| 4
|
#sentence = "All good things come to those who wait"
def break_words(stuff):
"""This funciton will break up words for us."""
words = stuff.split(' ')
return words #This is used to split sentence into words , ouput = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
def sort_words(words):
"""Sorts the words"""
return sorted(words) #This is used to sort words , ['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word #Used to print the first word after popping it off , All
def print_last_word(words):
"""Prints the last word after popping it off"""
word = words.pop(-1)
print word #Used to print the last word after popping it off , wait
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words) #Takes a full sentence and return the sorted words
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words) #returns the first and last word of the sentece
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words) #prints the first and last word of the sorted sentence
| true
|
d09a68f92d09bcac8a5fedeb0455aa125d17921f
|
adonispuente/Intro-Python-I
|
/src/14_cal.py
| 2,500
| 4.53125
| 5
|
"""
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
import sys
import calendar
from datetime import datetime
# bring in current day and time
today = datetime.now()
# print(today)
# count the number of sys.argv arguments
num_args = len(sys.argv)
# print(num_args)
# store the sys.argv arguments in an array
arguments = sys.argv
# print(arguments)
# print(calendar.month)
# - if no input
# print the calendar for the current month
if num_args == 1:
print(calendar.month(today.year, today.month))
print(today)
# - elif one input
# assume the additional argument is the month and print that month for current year
elif num_args == 2:
month_num = int(sys.argv[1])
print(calendar.month(today.year, month_num))
# - elif two inputs
# the fist will be the month, 2nd will be the year. We'll use those for the calendar.
elif num_args == 3:
month_num = int(sys.argv[1])
year_num = int(sys.argv[2])
print(calendar.month(year_num, month_num))
# - else more than 2 inputs
# send error message
else:
# print a usage statement
print(
"Please provide numerical dates in the following format: 14_cal.py [month] [year]")
# exit the program
sys.exit(1)
| true
|
16d8fd7a76d8d9c662e3b4ae81ece990542d0496
|
Colin0523/Ruby
|
/Ruby/Advanced Topics in Python.py
| 1,033
| 4.125
| 4
|
my_dict = {
"Name": "Colin",
"Age": 20,
"A": True
}
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key,my_dict[key]
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0]
# Complete the following line. Use the line above for help.
even_squares = [x**2 for x in range(1,11) if x % 2 == 0]
print even_squares
cubes_by_four = [x ** 3 for x in range(1,11) if x ** 3 % 4 == 0]
print cubes_by_four
to_21 = [x for x in range(1,22)]
odds = to_21[::2]
middle_third = to_21[7:14]
my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages)
threes_and_fives = [x for x in range(1,16) if x % 3 == 0 or x % 5 == 0]
print threes_and_fives
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[-1::-2]
print message
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x: x != 'X',garbled)
print message
| false
|
afa43852fca155cd5aaad6d2bb91a02cbe4fd2e3
|
dnguyen289/Python
|
/nguyen_dana_payment.py
| 752
| 4.375
| 4
|
# Variables and Calculations 2
# Dana Nguyen June 22 2016
# Part 1: Monthly interest Rate Calculator
# Calculate monthly payments on a loan
# Variables: p = initial amount
# Variables: r = monthly interest rate
# Variables: n = number of months
# Print, properly labeled the monthly payment ( m )
from math import pow
inital = input('Enter the initial amount on a loan: $' )
rate = input('Enter the monthly interest rate (in decimal form): ' )
months = input ('Enter the number of months of the loan: ' )
p = float(inital)
r = float(rate)
n = int(months)
top = r * pow(1+r , n)
bottom = pow (1+r, n) - 1
fraction = top / bottom
payment = p * fraction
m = format(payment , '7.2f')
print('Monthly payment: $' , m )
| true
|
e4e9f100067fc2b5dd8a1feb50deccd35c3a0614
|
CatherineBose/DOJO-Python-Fundametals
|
/mul_sum_average_Range.py
| 716
| 4.59375
| 5
|
# Multiples
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
# Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
# Sum List
# Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
# Average List
# Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
#multiples A
for count in range(1, 1001, 2):
print count
#multiples B
for count in range(5,1000001,5):
print count
#sum list
my_numbers = [1, 2, 5, 10, 255, 3]
sum = 0
for i in my_numbers:
sum += i
print sum
#average list
print sum/len(my_numbers)
| true
|
c3d7ed0322ad497f78590ab3c6d770e9571b7718
|
Shubh0520/Day_2_Training
|
/Dict_1.py
| 405
| 4.28125
| 4
|
""" Write a Python program to sort (ascending and descending) a dictionary by value. """
import operator
dict_data = {3: 4, 2: 3, 5: 6, 0: 1}
print(f"Dictionary defined is {dict_data}")
ascend = sorted(dict_data.items())
print(f"Sorted Dictionary in ascending order is: {ascend}")
descend = sorted(dict_data.items(), reverse=True)
print(f"Sorted Dictionary in Descending order is: {descend}")
| true
|
fafb4a235295ff42f74933c70b48ff8e2aa1072e
|
EvanZch/PythonNoteEvanZch
|
/6、函数与变量作用域/4、序列解包和链式赋值.py
| 320
| 4.4375
| 4
|
"""
序列解包和链式赋值
两个也有一定的关系
"""
a = 1
b = 2
c = 3
# 改进, 链式赋值
a, b, c = 1, 2, 3
# 一个变量接收三个赋值
d = 1, 2, 3
print(type(d)) # <class 'tuple'> 结果是一个元组
# 序列解包
# a,b,c = d
d = 1, 2, 3, 4
x, y, z, q = d
print(x, y, z, q) # 1 2 3 4
| false
|
ec867013d462774255852078e48002a7ec645caf
|
EvanZch/PythonNoteEvanZch
|
/1、Python基本类型/1、Number.py
| 1,371
| 4.4375
| 4
|
# 基本类型:数字 Number (大分类)
# 整数:int
# 浮点数:float
# type() : 查看某个变量的基本类型
print(type(1)) # <class 'int'>
print(type(1.1)) # <class 'float'>
print(type(1.111111111111111111111)) # <class 'float'>
print(type(1 + 1)) # <class 'int'>
print(type(1 + 1.0)) # <class 'float'>
print(type(1 + 0.1)) # <class 'float'>
print(type(1 * 1)) # <class 'int'>
print(type(1 * 1.0)) # <class 'float'>
print(type(1 / 1)) # <class 'float'>
# 除法,结果是浮点数
print(1 / 1) # 1.0 除法,结果转为float
# 整除
print(1 // 1) # 1 整除,保留整数部分
# 取余
print('取余')
print(3 % 2) # 1
# 幂运算
print('幂运算')
print(2 ** 3) # 8 = 2的三次方
print(type(1 // 1)) # <class 'int'>
# bool : 表示真假
print(True)
print(False)
# print(true) 错误写法,必须区分大小写
print(type(True))
print(type(False))
## 为什么把 bool划到 Number这个分类下?
# 把True和False转为十进制
print(int(True)) # 1
print(int(False)) # 0
print(bool(1)) # True
print(bool(0)) # False
print(bool(1213)) # True
print(bool(-1213)) # True
print(bool(-1.1)) # True
print('-----------')
print(bool('abc')) # True
print(bool('')) # False
print(bool(None)) # False
## complex 复数
# 数字后面用小写j表示
print(30j) # 30j
print(type(30j)) # <class 'complex'>
| false
|
87553f24b3a74d2e2db1242aa4af7784c8324356
|
EvanZch/PythonNoteEvanZch
|
/6、函数与变量作用域/5、必须参数和关键字参数.py
| 732
| 4.5
| 4
|
"""
函数的参数
必须参数和关键字参数
区别在函数的调用上而不是在定义上
"""
# 1、必须参数
#这里的x和y就是必须参数,如果调用的时候不传入或者少传就会报错,参数有顺序
# x 和 y 称之为形参
def add (x,y):
return x+y
# 我们在调用的时候传入的值称为实参
# 这里的1,和2就是实参
add(1,2)
# 2、关键字参数
# 作用:方便,代码的可读性
# 我们知道参数是有顺序的,但是我们在调用的时候,可以通过关键字传入参数,如下
# 一样可以正常运行
def add (x,y):
return x+y
# 我们这里通过指定关键字参数传值,这个时候跟顺序没有关系
c = add(y=10,x=2)
print(c) # 12
| false
|
f3115da63107ac4ada00fe11e58270a621d4c312
|
Infra1515/edX-MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python---May-August-2017
|
/midterm_exam + extra problems/print_without_vowels.py
| 425
| 4.3125
| 4
|
def print_without_vowels(s):
'''
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
'''
vowels = 'aeiou'
no_vowels = []
for letter in list(s):
if letter not in vowels and letter not in vowels.upper():
no_vowels.append(letter)
print(''.join(no_vowels))
| true
|
2fa6f16a91a36b179931fce892595a8d4a85c72c
|
sekR4/random_walk
|
/Codewars/python/quest20190802.py
| 508
| 4.25
| 4
|
#Find the missing letter
# Example:
#
# ['a','b','c','d','f'] -> 'e'
# ['O','Q','R','S'] -> 'P'
def find_missing_letter(chars):
alphabet = list(set('abcdefghijklmnopqrstuvwxyz'))
alphabet.sort()
# for letter in alphabet:
# print(letter)
for i in range(len(alphabet)):
print(i,alphabet[i])
# print(alphabet)
return
# alphabet = list(set('abcdefghijklmnopqrstuvwxyz'))
# alphabet.sort()
# print(alphabet)
letters = ['a','b','c','d','f']
find_missing_letter(letters)
| false
|
235ac2bf53b66b2df9d10a07bdfe0ccc66181a97
|
rajal123/pythonProjectgh
|
/LabExercise/q7.py
| 897
| 4.40625
| 4
|
''' you live 4 miles from university. The bus drives at 25mph but spends 2 minutes at each of the 10 stops on the way.
How long will the bus journey take? Alternatively,you could run to university.you jog the first mile at 7mph;then run
the next two at 15mph;before jogging the last at 7mph again.Will this be quicker or slower than the bus?'''
living_miles_apart = 4
drives_velocity = 25
time_taken = ((living_miles_apart/drives_velocity) * 60)
# 2 minutes in each stop
time_spends = 20
total_time = time_taken + time_spends
print(f"Total time taken by bus is {total_time}")
jog_one = ((1/7)*60)
jog_two = ((2/15)*60)
jog_three = ((1/7)*60)
total_walk_time = jog_one + jog_two + jog_three
print(f"time taken by running is {total_walk_time}")
if(total_time > total_walk_time):
print("taking bus is slower than running")
else:
print("taking bus is quicker than running")
| true
|
56b5482b39acc25c53af9dde98302db19a5106b2
|
TAMU-IEEE/programming-101-workshop
|
/Workshop 2/decisions_2.py
| 676
| 4.4375
| 4
|
'''Gets a number from the user, and prints “yes” if that number is divisible by
4 or 7, and “no” otherwise.
Test Suite:
inputs: outputs: domain:
-7 "yes" Negative factors
1 "no" Positive integers, nonfactors
0 "no" Zero (border case)
4 "yes" Positive integers, factors of 4
7 "yes" Positive integers, factors of 7
28 "yes" Positive integers, factors of both (border case) '''
# Get input from the user
number = int(input("Enter a number to check:"))
# Conditionals
if number % 7 == 0:
print("yes, because it is divisible by 7")
elif number % 4 == 0:
print("yes,because it is divisible by 4")
else:
print("no, it is not divisible by either 4 or 7")
| true
|
7b580887c8858cc36fa63eed979dedabb981e5f4
|
TAMU-IEEE/programming-101-workshop
|
/Workshop 3/funcs_2.py
| 589
| 4.3125
| 4
|
'''Write a function that returns two given strings in alphabetical order.
Test suite:
input: output: domain:
"hi", "man" "hi man" ordered
"zz", "aa" "aa zz" unordered '''
# think about how we compare characters and their hidden ascii value!
def alphabetizeMe(string1, string2):
for i in range(0, len(string1)):
if string1[i] < string2[i]:
return '{0} {1}'.format(string1, string2)
elif string2[i] < string1[i]:
return '{0} {1}'.format(string2, string1)
# it's possible that there is a more elegant solution
print(alphabetizeMe('rocks', 'oneal'))
| true
|
e5f75a207712c3866750c0e4ff1392054d9a990e
|
ShriPunta/Python-Learnings
|
/Python Basics/Phunctions.py
| 1,507
| 4.1875
| 4
|
#Each Function named with keyword 'def'
def firstFuncEver(x,y,z):
sum=x+y+z
return sum
#Scope of Variable is defined by where its declaration in the program
#Higher (higher from start of program) declarations means greater scope of variable
#if you give value in the function start, it is the default value
def secFuncEver(x,y=2,z=1):
return firstFuncEver(x,y,z+6)
for x in range(0,10):
print("Add ", x,"them",secFuncEver(x,y=45), " ")
print(secFuncEver(x))
print('\n')
#This gives Flexibility, it means whatever number of variables there are
#they will be taken in an array format
def flexi_Param(*args):
sum = 2
print(args)
print(type(args))
for n in args:
sum+=n
return sum
print(flexi_Param(1))
print(flexi_Param(1,2,4))
flexi=[9,8,7]
def Flexi_Args(add1,add2,add3):
print(add1,add2,add3)
sum1=add1+add2+add3
return sum1
#Flexi is sent as a an array itself, and taken up 1 by 1
#The number of elements should perfectly match number of parameters
#Called UnPacking of Arguments
Flexi_Args(*flexi)
import Collecshuns
Collecshuns.modu()
#Using Unpacking of variables
#We can use this unpacking if we do not know the variables
#What it does is, it stores the first number in 'first' and last number in 'last'
#All the middle numbers are stored in 'middle'
def Flexi_Args(grades):
first, *middle, last = grades
avg = sum(middle)/len(middle)
print(avg)
Flexi_Args([1,2,3,4,5,6,7,8,9])
Flexi_Args([200,1,1,1,1,1,1,1,200])
| true
|
47c450984b7263d1072fd232397d3c6645b3edc0
|
Basileus1990/Receipt
|
/ShopAssistant.py
| 2,435
| 4.15625
| 4
|
import Main
from ChosenProducts import ChosenProduct
# class meant to check which and how many products you want to buy. then he displays a receipt
def ask_for_products():
list_of_chosen_products = []
while True:
Main.clear_console(True)
chosenNumber = chose_product()
if chosenNumber == 0:
break
howMany = chose_how_many()
if howMany == 0:
continue
list_of_chosen_products.append(ChosenProduct(Main.selectedProducts[chosenNumber - 1], howMany))
write_receipt(list_of_chosen_products)
def chose_product():
while True:
print('\n' + ('#'*61))
print('Which product do you want to buy? Chose a number from above. If no more of them write \"0\"')
try:
chosenNumber = int(input())
if chosenNumber < 0 or chosenNumber > Main.selectedProducts.__len__():
raise Exception
except(Exception):
Main.clear_console(False)
print('You wrote a wrong number!!! Please try again (: Hit enter to continue')
input()
Main.clear_console(True)
continue
break
return chosenNumber
def chose_how_many():
while True:
print('How much of it you want to buy? Write 0 to go back')
try:
howMany = int(input())
if howMany < 0:
raise Exception
except(Exception):
Main.clear_console(False)
print('You wrote a wrong number!!! Please try again (: Hit enter to continue')
input()
Main.clear_console(True)
continue
break
return howMany
def write_receipt(list_of_chosen_products):
Main.clear_console(False)
if list_of_chosen_products.__len__() == 0:
print('You didn\'t chose any product!')
return
print('You bought those products:')
for i in list_of_chosen_products:
print(i.product.name + ' in amount of ' + i.amountOfProduct.__str__() +
' Total cost equals: ' + (float(i.amountOfProduct) * float(i.product.price)).__str__())
# calculates sum cost of every product
total_cost = 0.0
for i in list_of_chosen_products:
total_cost += float(i.amountOfProduct) * float(i.product.price)
print('In total you will have to pay: ' + total_cost.__str__())
| true
|
1d86e2c7234b1659cfb9ec11c3421f8e6f9333fb
|
SAN06311521/compilation-of-python-programs
|
/my prog/sum_of_digits.py
| 259
| 4.21875
| 4
|
num = int(input("enter the number whose sum of digits is to be calculated: "))
def SumDigits(n):
if n==0:
return 0
else:
return n % 10 + SumDigits(int(n/10))
print("the sum of the digits is : ")
print(SumDigits(num))
| true
|
a7fca4dd7d6e51fa67c3e22770a6a7b9cbb24fb3
|
SAN06311521/compilation-of-python-programs
|
/my prog/leap_yr.py
| 439
| 4.1875
| 4
|
print("This program is used to determine weather the entered year is a leap year or not.")
yr = int(input("Enter the year to be checked: "))
if (yr%4) == 0 :
if (yr%100) == 0 :
if (yr%400) == 0 :
print("{} is a leap year.".format(yr))
else:
print("{} is not a leap year.".format(yr))
else:
print("{} is a leap year.".format(yr))
else:
print("{} is not a leap year.".format(yr))
| true
|
9012204f8bde854d3d50139ded69bb038aa58f66
|
SAN06311521/compilation-of-python-programs
|
/my prog/class_circle.py
| 475
| 4.375
| 4
|
# used to find out circumference and area of circle
class circle():
def __init__(self,r):
self.radius = r
def area(self):
return self.radius*self.radius*3.14
def circumference(self):
return 2*3.14*self.radius
rad = int(input("Enter the radius of the circle: "))
NewCircle = circle(rad)
print("The area of the circle is: ")
print(NewCircle.area())
print("The circumference of the circle is: ")
print(NewCircle.circumference())
| true
|
0089887361f63ff82bfb55468aa678374c562513
|
Drabblesaur/PythonPrograms
|
/CIS_41A_TakeHome_Assignments/CIS_41A_UNIT_B_TAKEHOME_SCRIPT2.py
| 2,090
| 4.125
| 4
|
'''
Johnny To
CIS 41A Fall 2019
Unit B take-home assignment
'''
# SCRIPT 2
'''
Use three named "constants" for the following:
small beads with a price of 9.20 dollars per box
medium beads with a price of 8.52 dollars per box
large beads with a price of 7.98 dollars per box
'''
SMALL_BEADS_PRICE = 9.20
MED_BEADS_PRICE = 8.52
LARGE_BEADS_PRICE = 7.98
# Ask the user how many boxes of small beads, how many boxes of medium beads, and how many large beads they need
# (use the int Built-in Function to convert these values to int).
smallBeads = int(input("How many Small Beads? :"))
medBeads = int(input("How many Medium Beads? :"))
largeBeads = int(input("How many Large Beads? :"))
# Calculation
smallTotal = round((smallBeads*SMALL_BEADS_PRICE),2)
medTotal = round((medBeads*MED_BEADS_PRICE),2)
largeTotal = round((largeBeads*LARGE_BEADS_PRICE),2)
finalTotal = round((smallTotal + medTotal + largeTotal),2)
# Print the invoice
print("SIZE QTY COST PER BOX TOTALS")
print(f"Small {str(smallBeads).rjust(3)} {str(SMALL_BEADS_PRICE).rjust(5)} {str(smallTotal).rjust(6)}")
print(f"Medium {str(medBeads).rjust(3)} {str(MED_BEADS_PRICE).rjust(5)} {str(medTotal).rjust(6)}")
print(f"Large {str(largeBeads).rjust(3)} {str(LARGE_BEADS_PRICE).rjust(5)} {str(largeTotal).rjust(6)}")
print(f"TOTAL {str(finalTotal).rjust(10)}")
'''
Execution Results:
TEST 1
How many Small Beads? :10
How many Medium Beads? :9
How many Large Beads? :8
SIZE QTY COST PER BOX TOTALS
Small 10 9.2 92.0
Medium 9 8.52 76.68
Large 8 7.98 63.84
TOTAL 232.52
TEST 2
How many Small Beads? :5
How many Medium Beads? :10
How many Large Beads? :15
SIZE QTY COST PER BOX TOTALS
Small 5 9.2 46.0
Medium 10 8.52 85.2
Large 15 7.98 119.7
TOTAL 250.9
'''
| true
|
e430729e07dc10717ef0be62f96ab9ac9278670b
|
dylanbrams/Classnotes
|
/practice/change/pig_latin.py
| 2,056
| 4.40625
| 4
|
'''
Pig Latin: put input words into pig latin.
'''
VOWELS = 'aeiouy'
PUNCTUATION = '.,-;:\"\'&!\/? '
def find_consonant(word_in):
"""
:param word_in:
:return:
>>> find_consonant("Green")
2
>>> find_consonant("orange")
0
>>> find_consonant("streetlight")
3
>>> find_consonant("aardvark")
0
>>> find_consonant("a")
0
"""
vowel_place = 0
current_iteration = 0
for current_letter in word_in:
if current_letter in VOWELS:
vowel_place = current_iteration
break
else:
current_iteration += 1
return vowel_place
def to_pig_latin(word, vowel_place):
"""
Inputs a string to make pig latin, along with where in the word the vowel is. Returns the word in pig latin.
:param word:
:param vowel_place:
:return:
"""
word_out = ''
if vowel_place == 0:
word_out = word + 'way'
elif vowel_place != None:
word_out = (word[vowel_place:] + word[:vowel_place] + 'ay')
else:
word_out = None
return word_out
def match_format(word_to_match, word_to_modify):
"""
Matches punctuation and capitalization from one word to another.
:param word_to_match:
:param word_to_modify:
:return:
"""
if word_to_match[-1] in PUNCTUATION:
word_to_modify += word_to_match[-1]
if word_to_match[0].isupper():
word_to_modify = word_to_modify.capitalize()
return word_to_modify
def main():
input_string = input ('Please enter a word to put into pig latin: ')
output_string = input_string.lower().strip(PUNCTUATION)
vowel_place = find_consonant(input_string)
if vowel_place > len(output_string):
print("Invalid word.")
output_string = to_pig_latin(output_string, vowel_place)
final_string = match_format(input_string, output_string)
print (input_string + " in Pig Latin is " + final_string)
if __name__ == '__main__':
main()
# import doctest
# doctest.testmod(extraglobs={'t': ConversionClass()})
| true
|
7a9a7a54b79ad81ce6c7e1dcacb1e51de53f3043
|
sshashan/PythonABC
|
/factorial.py
| 491
| 4.375
| 4
|
print("Factorial program")
num1= int(input("Enter the number for which you want to see the factorial: "))
value=1
num =num1
while(num > 1):
value=value*num
num =num - 1
print("Factorial of "+str(num1)+" is: " ,value)
def factorial(n):
return 1 if(n==1 or n==0) else n * factorial(n-1)
print(factorial(num1))
def fact(x):
if (x == 0):
return 1
else:
return x * fact(x-1)
print(fact(num1))
| true
|
d337fc0ae229454fb657c1830189c31bb12d2f2e
|
sshashan/PythonABC
|
/Person_dict.py
| 353
| 4.25
| 4
|
print("This program gets the property of a person")
person={"name":"Sujay Shashank","age":30,"phone":7744812925,"gender":"Male","address":"Mana tropicale"}
print("What information you want??")
key= input("Enter the property (name,age,phone,gender,address):").lower()
result=person.get(key,"Info what you are looking for is not present")
print(result)
| true
|
d86c1fbb67e71e269e118cc9a6565456c57cd39c
|
sshashan/PythonABC
|
/calculator.py
| 713
| 4.34375
| 4
|
print("Calculator for Addition/Deletion/Multiplication/Subtraction")
print("Select the operation type")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
user_opt=int(input("Enter your operation number: "))
num1= int(input("Enter the first number :"))
num2= int(input("Enter your second number:"))
if (user_opt==1):
print("Sum of two numbers are: ",num1+num2)
elif (user_opt==2):
print("Subtraction of two numbers are:", num1-num2)
elif (user_opt==3):
print("Multiplication of two numbers are :",num1*num2)
elif (user_opt==4):
print("Division of two numbers are: ",num1/num2)
else:
print("Enter a valid option")
| true
|
afde2cea346697fc1f75f8427d574514d9941d76
|
greenfox-zerda-lasers/gaborbencsik
|
/week-03/day-2/38.py
| 259
| 4.125
| 4
|
numbers = [7, 5, 8, -1, 2]
# Write a function that returns the minimal element
# in a list (your own min function)
def find_min(list):
mini = list[0]
for x in list:
if x < mini:
mini = x
return mini
print find_min(numbers)
| true
|
051d2effa49713986d3bc82a296ceb18f3b825ef
|
greenfox-zerda-lasers/gaborbencsik
|
/week-04/day-3/09.py
| 618
| 4.25
| 4
|
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
# create a 300x300 canvas.
# create a square drawing function that takes 1 parameter:
# the square size
# and draws a square of that size to the center of the canvas.
# draw 3 squares with that function.
from tkinter import *
root = Tk()
size = 300
canvas = Canvas(root, width=size, height=size)
canvas.pack()
def square_drawing(x):
canvas.create_rectangle(size/2 - x/2, size/2 - x/2, size/2 + x/2, size/2 + x/2, fill="green")
print (size/2-x)
print (size/2)
square_drawing(120)
square_drawing(50)
square_drawing(20)
root.mainloop()
| true
|
730dabc7497180a3b6314421119d89d7735e2684
|
greenfox-zerda-lasers/gaborbencsik
|
/week-04/day-4/04-n_power.py
| 337
| 4.1875
| 4
|
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
# 4. Given base and n that are both 1 or more, compute recursively (no loops)
# the value of base to the n power, so powerN(3, 2) is 9 (3 squared).
def powerN(base,n):
if n < 1:
return 1
else:
return base * powerN(base,(n-1))
print (powerN(3,1))
| true
|
d585e697fde25956f65403c02cfd5d10bc04b530
|
greenfox-zerda-lasers/gaborbencsik
|
/week-03/day-2/37.py
| 296
| 4.1875
| 4
|
numbers = [3, 4, 5, 6, 7]
# write a function that filters the odd numbers
# from a list and returns a new list consisting
# only the evens
def filter(list):
new_list = []
for x in list:
if x % 2 == 0:
new_list.append(x)
return new_list
print filter(numbers)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.