blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
fd4c09a28b1f23da855bca68fbc587836f902a83 | Igorprof/python_git | /HW_3/1.py | 462 | 4.125 | 4 | def divide(x, y):
result = x/y
return result
try:
a = float(input('Введите делимое: '))
b = float(input('Введите делитель: '))
except ValueError:
print('Вводимые значения должны быть числами!')
else:
try:
res = divide(a, b)
print(f'Результат: {res}')
except ZeroDivisionError:
print('Деление на ноль невозможно!')
| false |
7e3f1aaf503160b024d65b435ea8c885d2564a00 | Emmandez/The-Python-Mega-Course | /Sección 6/openWritting.py | 921 | 4.5625 | 5 | '''
first of all, we open the file.
if we call a non-existing file inside the open method,
a new file is created
what the write() method does, is write inside a file. If we use it in a "session"
without closing the file, write() will work as an appending method, but if we
close the file, open it again and use write(), the "old" data will be replace
with the new data.
When using write() is recommended to write \n at the end of the text, to
keep an order
we will only be able to see line 2, because this method is a writting method,
not a appending method.
if we have a list or a CSV file, using a for-each loop is the best way to write
IMPORTANT: write() method takes only strings datatypes. We need to convert
integers or float to strings using the str() method
There is an append method, that adds new information keeping the old one.
'''
file = open('exampleWr.txt','w')
file.write("Line 1")
file.close()
| true |
faa52fc501307a7a9ba3b9ed5afcb1c3e8293783 | madhumitha01/cpp | /data-structures/LinkedList.py | 2,228 | 4.28125 | 4 | class LinkedList:
"""Defines a Singly Linked List.
attributes: head
"""
def __init__(self):
"""Create a new list with a Sentinel Node"""
self.head = ListNode()
def insert(self, x, p):
"""Insert element x in the position after p"""
temp = ListNode()
temp.value = x
temp.next = p.next
p.next = temp
def delete(self, p):
"""Delete the node following node p in the linked list."""
p.next = p.next.next
def show(self):
""" Print all the elements of a list in a row."""
i = self.head
while i is not None:
print(str(i.value))
i = i.next
def insertAtIndex(self, x, i):
"""Insert value x at list position i. (The position of the first element is taken to be 0.)"""
m = self.head
if m.next is None:
z = ListNode()
z.value = x
m.next = z
else:
n = ListNode()
t = ListNode()
n.value = x
t.next = self.head
for d in range(i + 1):
t = t.next
n.next = t.next
t.next = n
def search(self, x):
h = self.head
while h.next:
h = h.next
if h.value == x:
return h
return None
def len(self):
"""Return the length (the number of elements) in the Linked List."""
i = self.head
j = 0
while i.next:
j = j + 1
i = i.next
return j
def isEmpty(self):
"""Return True if the Linked List has no elements, False otherwise."""
i = self.head
if i.next is None:
return True
else:
return
class ListNode:
"""Represents a node of a Singly Linked List.
attributes: value, next.
"""
def __init__(self, val=None, nxt=None):
self.value = val
self.next = nxt
def main():
L = LinkedList()
L.insert(1, L.head)
L.insert(2, L.head)
L.insert(3, L.head)
L.insert(4, L.head)
L.insert(5, L.head)
L.insert(7, L.head)
print('List is: ')
L.show()
if __name__ == '__main__':
main()
| true |
742bda386912ec7870fc0b23151325d3cbb9f3f2 | MissYourYE/python_notes | /高级特性/Slice.py | 1,232 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# 使用切片获取List的前3个元素
# L[0:3]代表从索引为0开始取,直到索引3为止,但是不包括索引3。即索引0、1、2
L = ['zs', 'ls', 'ww', 'zl', 'tom', 'jerry']
# ['zs', 'ls', 'ww']
print(L[0:3])
# 如果第一个索引是0,还可以省略
# ['zs', 'ls', 'ww']
print(L[:3])
# ['ls', 'ww']
print(L[1:3])
# 倒数切片
# ['tom', 'jerry']
print(L[-2:])
# 记住倒数第一个元素的索引是-1。
# ['tom']
print(L[-2:-1])
# 取前5个数
# ['zs', 'ls', 'ww', 'zl', 'tom']
print(L[:5])
# 取后5个数
# ['ls', 'ww', 'zl', 'tom', 'jerry']
print(L[-5:])
# 取前2-5个数
# ['ls', 'ww', 'zl', 'tom']
print(L[1:5])
# 前4个数每2个取一个
# ['zs', 'ww']
print(L[:4:2])
# 所有数每3个取一个
# ['zs', 'zl']
print(L[::3])
# 什么都不写,复制一个List
# ['zs', 'ls', 'ww', 'zl', 'tom', 'jerry']
print(L[:])
# tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
print((0, 1, 2, 3, 4, 5)[:3])
# 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
# ABC
print('ABCDEFG'[:3])
| false |
88404dd4fda6e2890e426e46a2c2b3ac33ad3daa | preetha-mani/IBMLabs | /PrimeNumber.py | 258 | 4.125 | 4 | n=int(input('Enter a number:'))
if n>1:
for i in range (2,n):
if(n%i==0):
print(n,'is not a prime number')
break
else:
print(n,'is a prime number')
else:
print('{} is not a prime number'.format(n)) | false |
b6faccee5b5dc198a6e7821a3c7532f5a11b84dd | abaker-ssf/python_Practice | /workspace/highLowGame/game.py | 1,795 | 4.34375 | 4 | import random
quit = 1
print("Hi! This is Alexander Baker's Guessing Game! Here are some instructrions: \n")
print("I am going to choice a number from 1 to 100. And your going to guess the number. \nDon't worry I'll keep track of your guesses and give you a hint if the number is \nhigher or lower from your guess.")
def Higher_or_Lower(target, guess, numGuess):
if target < guess:
print("You guessed lower than the number i chose.")
elif target > guess:
print("You guessed higher than the number i chose.")
numGuess += 1
return numGuess
while quit == 1:
#prepping the game to run multiple times
targetNum = random.randrange(1,100)
numOfGuess = 1
print("\nAlright i have chosen a number!")
#i need to write a while loop or function here to handle continously repeating need for guesses and response hints
while True:
guess = input("guess a number: ")
if targetNum == guess:
print("congragulations!!! you guess the number!. I chose %d" % guess)
print("It took you %d guesses!" % numOfGuess)
break
else:
#this is where the continuly repeating guesses and hints are written
numOfGuess = Higher_or_Lower(targetNum, guess, numOfGuess)
quit = input("\nCongrats again :) would you like to play again? (Enter 1 to play again or 0 to stop playing): ")
if quit == 0:
print("Alright see you later :)!")
elif quit == 1:
print("YES! YOUR PLAYING AGAIN! ALRIGHT LET ME THINK OF A NUMBER!!!!")
else:
print("OPPS you didnt enter 1 or 0. I don't know what to do.\nI am only a computer program not a smarty pants human ;) :P")
quit = input("\nWould you like to leave or stay (enter 1 or 0): ") | true |
44a7d5b43bbc679911778c38cb4639b3ba604dfc | mbutkevicius/FlowControl | /guessinggame.py | 1,479 | 4.25 | 4 | import random
highest = 1000
answer = random.randint(1, highest)
print(answer) # TODO: Remove after testing
print("Please guess a number between 1 and {}: ".format(highest))
guess = int(input())
while guess != answer:
if guess == 0: # Can use multiple "if" statements
print("You suck. Game over")
elif guess < answer:
print("Please try again and guess higher")
else:
print("Please try again and guess lower")
guess = int(input())
print("Well done, you guessed it!")
# I JUST COMMENTED THIS OUT SO I COULD PRACTICE WHILE LOOPS
# if guess != answer:
# if guess < answer:
# print("Please guess higher")
# else: # guess must be greater than answer
# print("Please guess lower")
# guess = int(input())
# if guess == answer:
# print("Well done, you guessed it")
# else:
# print("Sorry, you have not guessed it")
# else:
# print("You got it the first time!")
# THIS IS INEFFICIENT CODE
# if guess < answer:
# print("Please guess higher")
# guess = int(input())
# if guess == answer:
# print("Well done, you guessed it")
# else:
# print("Sorry, you have not guessed correctly")
# elif guess > answer:
# print("Please guess lower")
# guess = int(input())
# if guess == answer:
# print("Well done, you guessed it")
# else:
# print("Sorry, you have not guessed correctly")
# else:
# print("You got it first try!") | true |
11beb04fed2206a2e9af71d7e2d39793f08c13cf | RandomUser171/Umschulungsprojekte | /12. Menu Calculator.py | 1,779 | 4.34375 | 4 | # This script calculates the total value order according the the user's input
# Menu list
menu_items = [
('Chicken Strips' , 3.50),
('French Fries' , 2.50),
('Hamburger' , 4.00),
('Hotdog' , 3.50),
('Large Drink' , 1.75),
('Medium Drink' , 1.50),
('Milk Shake' , 2.25),
('Salad' , 3.75),
('Small Drink' , 1.25)]
# Valid input
numbers = '123456789'
def menu_calculator():
# Prints the Menu
for i in range(len(menu_items)):
print(str(i+1)+'.', menu_items[i][0],' '*2,'-',' '*2, menu_items[i][1])
print('Please enter the order.')
is_it_ok = False
quantity_of_items = {}
# Loop to check if input is valid
while is_it_ok == False:
order = input()
is_it_ok = True
# Checks if the input is valid
for i in order:
if i not in numbers:
print('Please enter positive integers only.')
is_it_ok = False
break
order_value = 0
# Calculates and prints the total value of the order
for i in set(order):
quantity_of_items[menu_items[int(i)-1][0]] = 0
for i in order:
quantity_of_items[menu_items[int(i)-1][0]] += 1
order_value += menu_items[int(i)-1][1]
for i in quantity_of_items:
print(i)
print(quantity_of_items[i],' : ',quantity_of_items[i])
print('$%.2f'%(order_value))
# Asks the user if they want to repeat the program
print('Would you like to enter another order? Type "y" to repeat.')
repeat = input()
if repeat.lower() == 'y':
menu_calculator()
menu_calculator()
| true |
c83e1c321e155a74750214c421225a66ed25e283 | RandomUser171/Umschulungsprojekte | /3. Pythagorean Triples Checker.py | 1,251 | 4.1875 | 4 | """
@author: Thanasis
"""
# Receives the user's input, converts it to integer (c)
def user_input():
xAsInteger = None
while isinstance(xAsInteger, int) == False:
x = input()
try:
xAsInteger = int(x)
except:
print('Please enter an integer.\n')
return xAsInteger
# Asks the user for the 3 sides of the triangle
# and sorts the hypotenuse (c)
def questionPrompter():
print('Please enter the first side of the triangle:')
a = abs(user_input())
print('Please enter the second side of the triangle:')
b = abs(user_input())
print('Please enter the third side of the triangle:')
c = abs(user_input())
triangleSides = [a, b, c]
triangleSides.sort()
if (triangleSides[2] ** 2) == (triangleSides[1] ** 2) + (triangleSides[0] ** 2):
print('Ya did it')
else:
print("ya didn't do it")
print('Would you like to try again? (y/n)')
x = input()
while x != 'y' and x != "n":
print('Would you like to try again? (y/n)')
x = input()
if x == 'y':
questionPrompter()
else:
return
questionPrompter()
| true |
6ec5f21844fbb79df03218ce0993fb95524c84e6 | francesco-dorati/sorting-visualizer | /src/assets/algorithms/algorithms.py | 1,544 | 4.3125 | 4 | def bubble_sort(array: list):
swaps = -1
while swaps != 0:
swaps = 0
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
tmp = array[i]
array[i] = array[i + 1]
array[i + 1] = tmp
swaps += 1
def selection_sort(array: list):
for i in range(len(array)):
minimum = i
for j in range(i, len(array)):
if array[j] < array[minimum]:
minimum = j
tmp = array[minimum]
array[minimum] = array[i]
array[i] = tmp
def insertion_sort(array: list):
for i in range(1, len(array)):
# Swap the firt unsorted element until it finds it's place
for j in reversed(range(i)):
if array[j + 1] < array[j]:
tmp = array[j + 1]
array[j + 1] = array[j]
array[i] = tmp
else:
break
from math import floor
def merge_sort(array: list, start: int = 0, end: int = None):
if end is None:
end = len(array)
if start == end - 1: return # sorted
middle = floor((start + end)/2)
# Sort each part
merge_sort(array, start, middle)
merge_sort(array, middle, end)
tmp, l, r = [], start, middle
# Merge the two parts
while l < middle and r < end:
if array[r] < array[l]:
tmp.append(array[r])
r += 1
else:
tmp.append(array[l])
l += 1
while l < middle:
tmp.append(array[l])
l += 1
while r < end:
tmp.append(array[r])
r += 1
for i in range(len(tmp)):
array[start + i] = tmp[i]
array = [4, 3, 1, 6, 2, 0, 5]
merge_sort(array)
print(array)
| true |
b0bcf8617c3f40083b3ac750a90221abe7e1be63 | essneider0707/andres | /ejercicio_23.py | 210 | 4.15625 | 4 | numero =float(input("ingresa el numero para saber si es negativo o positivo \n"))
if numero < 0 :
print(f"este numero {numero} es negativo")
else:
print(f"este numero {numero} es positivo")
print("fin") | false |
a5059102ffb5e752d421743ea18c7fc0dfeb59d0 | AdamaTG/Machine-Learning | /Part 4 - Clustering/Section 24 - K-Means Clustering/Kmeans_MyProgram.py | 2,173 | 4.28125 | 4 | #K means clustering
#Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing model dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3,4]].values #The company is only interested in the relationship b/w Income and Spending score, not other metrics like age and gender
#Using the elbow method to find optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11): #To use the elbow method, we need to compute wcss for 10 iterations, we use 11 as upper bound is excluded
kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) #init means initialising the clusters, we use k-means++ to avoid random initialization trap
kmeans.fit(X)
wcss.append(kmeans.inertia_) #Wcss is also called inertia hence, we are appending the wcss values to our wcss array we created in line 14
plt.plot(range(1,11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#Applying k-means to the null dataset
kmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) #No of optimal clusters is 5
y_kmeans = kmeans.fit_predict(X)
#visualizing the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans ==0,1], s= 100, c='red', label = 'Cluster1 - Careful') #s = size, X[y_kmeans == 0, 0] represents the first cluster, here the 0 after the comma indicates first column in X (Annual income)
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans ==1,1], s= 100, c='blue', label = 'Cluster2 - Standard')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans ==2,1], s= 100, c='green', label = 'Cluster3 - Target')
plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans ==3,1], s= 100, c='cyan', label = 'Cluster4 - Careless')
plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans ==4,1], s= 100, c='magenta', label = 'Cluster5 - Sensible')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroid')
plt.title('Clusters of Clients')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show() | true |
9113aadb2f7448b9a9bc453f5803641484fd75cf | hanchen826/PythonCrashCourse2016 | /Ch8: Functions/8-7 album.py | 674 | 4.1875 | 4 | def make_album(artist_name, album_title, num_tracks=''):
"""Return a dictionary of an artist"""
artist = {'artist name': artist_name, 'album': album_title}
if num_tracks:
artist['tracks'] = num_tracks
return artist
while True:
print("\nEnter artist, album, and optionally number of tracks.")
print("enter 'q' at any time to quit")
artist = input("artist: ")
if artist == 'q':
break
album = input("album: ")
if album == 'q':
break
tracks = input("optionally number of tracks: ")
if tracks == 'q':
break
dictionary = make_album(artist, album, tracks)
print("\nHere it is", dictionary)
| true |
854276002e79c1ff447e764db305c09f3bf54168 | bohanchen/Python-Bootcamp | /Notes/formatting_strings.py | 493 | 4.28125 | 4 | print ('This is a string {}'.format('inserted'))
print ('the {} {} {} '.format('fox', 'brown', 'quick'))
print ('the {2} {1} {0} '.format('fox', 'brown', 'quick'))
print ('the {0} {0} {0} '.format('fox', 'brown', 'quick'))
print ('the {q} {b} {f} '.format(f = 'fox', b = 'brown', q = 'quick'))
#float formatting
result = 100/777.0
print ('the result was {r} '.format(r = result))
print ('the result was {r:1.3f} '.format(r = result))
name = "bohan"
print (f"hello his name is {name}")
| false |
8ea45b9e5e0cacdc3852814c42fbfbc260459775 | ketulsuthar/Leetcode | /231.py | 863 | 4.15625 | 4 | '''
231. Power of Two
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
'''
#Solution-1
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
i = 0
while True:
i_power = 2 ** i
if i_power == n:
return True
else:
if i_power > n:
return False
i+=1
#Solution-2
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
else:
return (n & (n-1)) == 0
| true |
91d6a084826d12de4323d1ef6f27fb50515cd402 | thmaan/PPI-2 | /lista-105.py | 2,128 | 4.15625 | 4 | ###
# Exercicios
###
## Usando a lista: ['a','b','c']
# 1) Faca um loop para retornar: ['A','B','C']
list = ['a','b','c']
for i in list:
print(i.upper())
## Usando os numeros: [0, 1, 3, 4, 5]
# 2) Faca um loop para retornar a soma de todos os elementos da listas
# 3) Faca um loop para retornar apenas os numeros impares
numeros = [0, 1, 3, 4, 5]
soma = 0
for i in numeros:
soma += i
print(soma)
for i in numeros:
if i % 2 == 1:
print(i)
## usando a string: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
# 4) Conte quantas palavras de tamanho >= 5 existe nessa string
string = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''
c = 0
for i in string.split():
if(len(i)>= 5):
c += 1
print(c)
# 5) Usando list comprehension, crie uma lista com os multiplos de 3 de 0 ate 100
multiplos3 = [i for i in range(100) if i % 3 == 0]
multiplos3 = [i for i in range(0, 100, 3)]
# Faca uma funcao para encontrar os numeros primos no intervalo [2, 10), mas nao utilize a clausula else do for
def isPrimo(num):
contador = 0
for i in range(1, num + 1):
if num % i == 0:
contador += 1
if contador == 2:
print(" O número é primo")
else:
print(" O número não é primo")
for i in range(2, 10):
print(i, end='')
isPrimo(i) | false |
e7fa82920bb08ce89ef1b9593e9a80578a767e09 | aniketmlk6/python-class | /input.py | 2,550 | 4.65625 | 5 | # input
# used to take user input from pyhon
# that means we are able to ask the user for input from the user
# example 1
# print("welcome to the dominoes!!")
# inp=input("what will you like to have?")
# print("you ordered for "+inp)
# example 2
# import time
# print("welcome to the dominoes!!")
# time.sleep(1)
# inp=input("what will you like to have?")
# time.sleep(1)
# print("you ordered for "+inp)
# example 2.5
# VIP (very important point) -> the datatype of input is always string
# inp=int(input("enter a number : "))
# print he datatype of inp
# print(type(inp))
# example 2.7
number=input("enter a number: ")
number=int(number)
number-number+1
print(number)
# or
inp=int(input("enter a number : "))
print(inp + 1)
# -------------------------------------------
# Small Assignment
# Take input for a number in a
# Take input for a number in b
# # Take input for a number in c
# print the value of (a+b+c)+2(a)+2(b)+abc
a=float(input("enter number: "))
b=float(input("enter number: "))
c=float(input("enter number: "))
print((a+b+c)+2*(a)+2*(b)+a*b*c)
# -------------------------------------------
# example 3
import time
print("Welcome to the Domionoes!!")
time.sleep(1)
inp=input("What will you like to have? ")
time.sleep(1)
inp2=int(input("What many? "))
time.sleep(1)
print(f"you ordered {inp2} {inp}")
inp3=bool(input("confirm your order:"))
time.sleep(1)
print("your order has been confirmed your food will arrive soon")
username=input("please tell your username?")
print(username+" is username")
# 1.
# Take input for first number as a
# Take input for second number as b
# Multiply a and b and put the value in c
# print c
a=int(input("enter a:"))
b=int(input("enter b:"))
c=a*b
print(c)
# 2.
# Take input for the first number
# # Take input for the second number
# # Take input for the third number
# # add them
# # AND THEN PRINT IN THE FOLLOWING FORMAT
# # The sum of these numbers is ""
a=int(input("enter a:"))
b=int(input("enter b:"))
c=int(input("enter c:"))
d=a+b+c
print("the sum of these numbers is "+str(d))
# Take full name, roll number and field of interest from user and print in the below format :
# Hey, my name is xyz lmn and my roll number is xyz. My field of interest is xyz
a=(input("enter your full name:"))
b=int(input("enter your roll number:"))
c=(input("enter your field of interest:"))
print(f"hello my name is {a} and my roll number is {b}. My field of interest is {c}.")
| true |
d92d1e0720411c5d3dd7e285e134769b2f73649d | lennox-davidlevy/practice | /6 Misc/path_sum.py | 1,698 | 4.125 | 4 | # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
# return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, sum_int: int) -> bool:
if root == None:
return False
elif root.left == None and root.right == None and sum_int - root.val == 0:
return True
else:
return hasPathSum(self, root.left, sum_int - root.val) or hasPathSum(
self, root.right, sum_int - root.val
)
class Solution:
def hasPathSum(self, root: TreeNode, sum_int: int) -> bool:
if root == None:
return False
sum_int -= root.val
if root.left == None and root.right == None:
return sum_int == 0
left = self.hasPathSum(root.left, sum_int)
right = self.hasPathSum(root.right, sum_int)
return left or right
class Solution:
def has_path_sum(self, root, sum_int):
if root == None:
return False
sum_int -= root.val
if root.left == None and root.right == None:
return sum_int == 0
left = self.has_path_sum(root.left, sum_int)
right = self.has_path_sum(root.right, sum_int)
return left or right
| true |
4abb670a17465a8f7f958f6aa354c3f8246eb8b7 | kevin7lou/dsml-learning-roadmap-x | /01_Python Elementary/零基础学Python语言-嵩天-北理/【第4周】Python编程之代码复用/drawtree.py | 1,997 | 4.46875 | 4 | # drawtree.py
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5: #
lst = []
for p in plist:
p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
p.left(a) #Turn turtle left by angle units
q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
lst.append(p)#将元素增加到列表的最后
lst.append(q)
tree(lst, l*f, a, f)
def main():
p = Turtle()
p.color("green")
p.pensize(5)
#p.setundobuffer(None)
p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
#because hiding the turtle speeds up the drawing observably.
#p.speed(10)
# p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
p.speed(10)
#TurtleScreen methods can then be called for that object.
p.left(90)# Turn turtle left by angle units. direction 调整画笔
p.penup() #Pull the pen up – no drawing when moving.
p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
#否则turtle一移动就会自动的把线画出来
#t = tree([p], 200, 65, 0.6375)
t = tree([p], 200, 65, 0.6375)
main()
| true |
8b33c235189b14d0750e6068d15277d58b536ff3 | benefice-bytes/Python | /03_conditional_and_boolean_if_else_and_elif/if_elif_else.py | 658 | 4.125 | 4 | """
condition = True
if condition:
print('condtion is true')
else:
print('condition is false')
"""
##########
"""
name = 'Nagesh'
age = 18
if name == 'Satish' or age >= 18:
print('valid voter')
else:
print('invalid voter')
"""
##############
"""
mesg = []
if mesg:
print('condtion is true')
else:
print('condition is false')
"""
# difference between == and is operator
a = [1,2,3]
b = [1,2,3]
print(a == b) # True
print(id(a)) # ref of a
print(id(b)) # ref of b
print(id(a) == id(b)) # compares ref
print(a is b) # compares ref a and ref b
| true |
c5685888db963effbbd81e8706ccc7b0d1f62a80 | parvathimandava/Geeksforgeeks | /Mathematical_geeksforgeeks/Sieve of Eratosthenes.py | 2,375 | 4.1875 | 4 | '''
Given a number N, calculate the prime numbers upto N using Sieve of Eratosthenes.
Input:
The first line of the input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input containing N.
Output:
For all testcases, in a new line, print all the prime numbers upto or equal to N.
Constraints:
1 <= T<= 100
1 <= N <= 104
Example:
Input:
2
10
35
Output:
2 3 5 7
2 3 5 7 11 13 17 19 23 29 31
'''
'''
Sieve Algorithm:
Sieve of Eratosthenes is used to get all prime number in a given range and is a very efficient algorithm. You can check more about sieve of Eratosthenes on Wikipedia. It follows the following steps to get all the prime numbers from up to n:
Make a list of all numbers from 2 to n.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ……., n]
Starting from 2, delete all of its multiples in the list, except itself.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,……., n]
Repeat the step 2 till square root of n.
For 3 – [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20……., n]
For 5 – [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20……., n]
Till sqrt(n)
The remaining list only contains prime numbers.
'''
#code with more execution time
import math
T=int(input())
for _ in range(T):
n=int(input())
sqroot=int(math.sqrt(n))
l=[]
notprime=[]
for i in range(2,n+1):
l.append(i)
for i in range(len(l)):
for j in range(2,sqroot+1):
if(l[i]%j==0):
notprime.append(l[i])
list3=[item for item in l if item not in notprime]
list3.append((2))
list3.append((sqroot))
list3= sorted(list3)
print(' '.join([str(elem) for elem in list3]))
#code with less execution time
t = int(input())
for test in range(t):
n = int(input())
n += 1
is_prime = [True for i in range(n)]
is_prime[0] = False
is_prime[1] = False
i = 2
while i * i <= n:
if is_prime[i]:
# Start from i*i since i*2 would be marked already
for j in range(i * i, n, i):
is_prime[j] = False
i += 1
numbers = [str(i) for i, p in enumerate(is_prime[2:], 2) if p]
print(' '.join(numbers))
| true |
2ecc776352897bfe1523dc7fea4204708f5c76fc | parvathimandava/Geeksforgeeks | /Mathematical_geeksforgeeks/Amstrong Number.py | 877 | 4.25 | 4 | '''
For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 33 + 73 + 13 = 371
Input:
First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case contains a positive integer N.
Output:
For each testcase, in a new line, print "Yes" if it is a armstrong number else print "No".
Constraints:
1 <= T <= 31
100 <= N < 1000
Example:
Input:
1
371
Output:
Yes
'''
k=int(input())
def Amstrong(k):
n = int(input())
m=list(map(int,str(n)))
r=len(m)
sum=0
for i in range(r):
number=m[i]**r
sum=sum+number
if(sum==n):
print("Yes")
else:
print("No")
Amstrong(k)
| true |
6ed079958024555ddfa649c4ec01bdb64f83e2c8 | Samson300/Python_Exercises | /blastoff.py | 358 | 4.15625 | 4 | # Counts down from user input, 1 second delay
import time
user_input = int(input("Where do you want to start the count 1-20? "))
if user_input > 20:
user_input = int(input("Ooops did you pick a number between 1-20? "))
while user_input >=1:
print(user_input)
time.sleep(1)
user_input -= 1
if user_input == 0:
print("Blastoff!") | true |
c80c9ab647466428fdce28343485f00cf60af904 | skyla15/HireMeProject- | /1_DataStructure_Algo/PythonDataStructure(Mia_Stein)/7_1_Stack/7_1_1_LinkedList_stack.py | 1,846 | 4.15625 | 4 | ##############
# Stack ADT ##
############################
# 시간 복잡도 : O(1)
# Last In First Out (선입선출)
############################
# empty : 스택이 비었는 지 확인
# push : 맨 끝에 데이터 삽입
# pop : 스택 마지막 값 제거, 반환
# top / peek : 마지막 값 확인
# size : 스택 사이즈 확인
class StackNode(object) :
def __init__(self, item=None, next=None):
self.item = item
self.next = next
class Stack(object) :
# Creates an empty stack
def __init__(self):
self.top = None
self._size = 0
# Returns True if the Stack is empty otherwise False
def isEmpty(self):
return self.top is None
def size(self):
return self._size
def push(self, item):
# Creates a Node and set it to the top
self.top = StackNode(item, self.top)
self._size += 1
def pop(self):
# Removes and returns the top item on the Stack
assert not self.isEmpty(), 'Cannot pop from an Empty Stack'
node = self.top
self.top = self.top.next
self._size -= 1
return node.item
def peek(self):
assert not self.isEmpty(), 'Cannot peek from an Empty Stack'
return self.top.item
def size(self):
return self._size
def printStack(self):
node = self.top
while node :
print(node.item, end=' ')
node = node.next
print()
if __name__ == '__main__':
stack = Stack()
print('is Stack Empty? : {0}'.format(stack.isEmpty()))
print('pushing 1~9..')
for i in range(10) :
stack.push(i)
stack.printStack()
print('Peek : {0}'.format(stack.peek()))
print('pop : {0}'.format(stack.pop()))
print('Peek : {0}'.format(stack.peek()))
print('size : {0}'.format(stack.size()))
| true |
4d026d2baa0b309ad1454fd506ce15f37ed6369e | olorin-grey/getting_started_with_python | /If_Then_Else.py | 895 | 4.15625 | 4 | # If... Then... Else
# If-Then-Else statements are conditional statements inside of Python. Almost every
# language has some variation of this and it's an important logical clause inside
# of programming. They allows you to set up multiple blocks of code that may or may
# not be executed depending on the state of your program, or the context that it's
# running in, the value of a variable. So it's a really important logical structure
# inside of any programming language and I'm going to demonstrate an example here.
name = input('Hi! What is your name?: ')
age = int(input('How old are you?: '))
if age >= 21:
print('Thank you', name,'!', 'You are old enough to party here!')
elif age >= 18:
print('Thanks', name,'! You are allowed to come in, but you are not old enough to drink.')
else:
print('Sorry', name, 'but you are not old enough to party in this club.') | true |
d850f1f2df2edbb6c1ef1ec4b751660fd2e9fe67 | jsshim24/school-work | /Intro to Programming/Assignments/Assignment 5/ShimJunSeob_assign5_part3a.py | 1,195 | 4.15625 | 4 | """
Assignment #5, Part 3a
Jun Seob Shim
15/10/2020
Intro to Programming Section 012
Prime Number Finder
"""
import math
invalidnum = True
#ask for number to test
while invalidnum:
num = int(input("Enter a positive number to test: "))
if num > 0:
invalidnum = False
else:
print("Invalid, try again")
#account for 1 and 2
if num == 1:
print("1 is technically not a prime number.")
elif num == 2:
print("2 is a prime number!")
#test whether number is prime
else:
#for determining whether number is prime at the end
prime = True
#divide by integers up to the square root of the number until a divisor is found
for i in range(2,math.ceil(num**(1/2))+1):
#if i is not a factor
if num % i != 0:
print(i,"is NOT a divisor of",num,"... continuing")
#if i is a factor
else:
print(i,"is a divisor of",num,"... stopping")
prime = False
break
print()
#print if prime or not
if prime == True:
print(num,"is a prime number!")
else:
print(num,"is not a prime number.")
| true |
e8d0f48b533bdc41112a473a29d4143d40f8f3da | ZakFarmer/RandomPyProjects | /Birthday Checker/birthday.py | 518 | 4.15625 | 4 | from datetime import datetime
def birthdayCheck():
dateNow = datetime.now()
day = int(input("Day: "))
month = int(input("Month (Number): "))
year = int(input("Year: "))
age = datetime(year, month, day, 0, 0)
difference = datetime.now() - age
days = difference.total_seconds() / 60 / 60 / 24
years = days / 365.2425
if (years >= 18):
return True
else:
return False
if (birthdayCheck() == True):
print("You can enter this website!")
else:
print("You must be 18 or over to enter this website!")
| true |
7da595327a3fa9fbeac8582c5817328d451b7803 | edwinlara/python-programming | /unit-1/variables.py | 699 | 4.125 | 4 | '''
#integer
age = 41
#float
gpa = 3.0
#boolean
has_kids = True
#check the type of a variable
print(type(age))
print(type(gpa))
print(type(has_kids))
#check if a number is even
num = 10
if num % 2 == 0:
print('It is even!')
else:
print('It is odd')
#comparison operators
# > - greater than
# < - less than
# >= - greater than or equal to
# <= - less than or equal to
# == - equal to
# != not equal to
# = assin to
#truthiness
x = 10 # a non zero value is truthy
y = 0 #zero or negative value is falsy
z = 'Python' # a string of non zero length is truth
p = '' # as string of zero is falsy
q = [] #an empty list is falsy
if q:
print('yes')
else:
print('no')
''' | false |
013d5ff66ea2fb286bd5d1441461ddbbc6c8830d | pinky0916/python_Basics | /OOPS_1/Inner_Class.py | 696 | 4.3125 | 4 | #Creating objects of inner class outside of Outer class
class College:
def __init__(self):
print("Outer class constructor")
def displayC(self):
print("Outer class Method")
class Student:
def __init__(self):
print("Inner class constructor")
def displayS(self):
print("Inner class method")
# To access Outer class
c1=College()
c1.displayC()
#To access inner class methods-Method 1
s2=c1.Student()
s2.displayS()
print('**********Method2*******************')
#Method2:
s3=College().Student()
s3.displayS()
#s3.displayC() -Throws Error
print('**********Method3*******************')
#Method 3
s4=College.Student()
s4.displayS()
| false |
520bf0533f11c99d1e52d8c7cf4eda65e524ed26 | pinky0916/python_Basics | /Dictionaries.py | 741 | 4.40625 | 4 | #Dictionaries are unordered objects with key value pairs,can hold of mixed object types
#easy retriveable by keys ,not by index,Unordered,cannot sort
#List-retrievable by index,ordered,sorting is possible,indexing and slicing,
#Key should always be string
d={'key1':'value1','key2':'value2'}
print(d['key1'])
d1={'k1':123,'k2':[0,1,2],'k3':{'insidekey':100}}
print(d1['k3']['insidekey'])
d2={'k1':['a','b','c']}
print(d2['k1'][2].upper())
#Insert new values at the end .
d3={'k1':1,'k2':2,'k3':3}
d3['k4']=4
print(d3)
#to change the key or the value
d3['k2']='Changed value'
print(d3)
#to change the key:
#to retrive all the keys
print(d3.keys())
#to retrieve the values
print(d3.values())
#to retrieve as pairings
print(d3.items())
| true |
2d888b6607b4076815b96cabac4e68046f70703a | lilpsj/learning_python | /chapter4/ex4.py | 1,022 | 4.125 | 4 | '''
비교연산자 - 두 수를 비교할 때 사용
결과 -> bool(논리값)
bool 타입의 데이터 -> True / False
비교 연산의 기준은 왼쪽!
1. == 같다
2. != 다르다
3. > 크다(초과)
4. < 작다(미만)
5. >= 크거나 같다(이상)
6. <= 작거나 같다(이하)
'''
value1 = 10
value2 = 5
eqResult = value1 == value2
neqResult = value1 != value2
gtResult = value1 > value2
ltResult = value1 < value2
gteResult = value1 >= value2
lteResult = value1 <= value2
print("eqResult = ", eqResult)
print("neqResult = ", neqResult)
print("gtResult = ", gtResult)
print("ltResult = ", ltResult)
print("gteResult = ", gteResult)
print("lteResult = ", lteResult, "\n")
#예제
a = 17
b = 10
etrequest = a > b
print("etrequest = ", etrequest, "\n")
oddSum = 1+3+5+7+9
evenSum = 2+4+6+8+10
erRequest = oddSum > evenSum
print("erRequest = ", erRequest, "\n")
print("수 입력 : ", end="")
num = int(input())
print(num % 2==1)
print(num % 2!=0, "\n")
'''print((num % 2) == 1)'''
'''print((num % 2) != 1)''' | false |
168d2c1acfe69de16dd7e9a8e15c8a6d756e3f65 | kgdin3/python_projects | /paint_job_estimator_dinning.py | 1,675 | 4.28125 | 4 | # Author: Keith Dinning
# Assignment Number: Lab 3
# File Name: paint_job_estimator_dinning.py
# Course/Section: COSC 1336 Section 002
# Date: 2-2-14
# Instructor: Dr. B. Hohlt
# This program determines and displays the cost and amount
# of paint neeeded and the hours of labor required and
# calculates the total cost of the paint job
# main function
def main():
# get input
wall_space = float(input('How many square feet of wall space need painted?'))
paint_price = float(input('What is the price of paint per gallon?'))
# calculate gallons of paint needed
gallons = (wall_space/115)
print('The number of gallons of paint needed is', \
format(gallons, '.2f'))
# calculate labor hours needed
labor = ((wall_space/115)*8)
print('The hours of labor required is', \
format(labor, '.2f'))
# calculate total cost of paint
total_paint_cost = (gallons*paint_price)
print('The total cost of the paint required is', \
format(total_paint_cost, '.2f'), 'dollars')
# calculate labor cost
labor_cost = (labor*20)
print('The total cost of labor is', \
format(labor_cost, '.2f'), 'dollars')
# calculate the total cost estimate
show_cost_estimate(total_paint_cost,labor_cost)
input('press enter to continue')
# define the show_cost_estimate function
def show_cost_estimate(total_paint_cost,labor_cost):
total = (total_paint_cost + labor_cost)
print('The total cost of the paint job is', \
format(total, '.2f'), 'dollars')
# call the main function
main()
# Tested with values:
# 1000
# 20
# Outputs:
# 8.70
# 69.57
# 173.91
# 1391.30
# 1565.22
| true |
62ae10dd89267b9506d43b776defff003961f328 | nabeelnh/Python_Certificate | /PCEP/typcasting_n_inputoutput_operations/typcasting.py | 807 | 4.3125 | 4 | #!/usr/local/bin/python3.8
# The process of converting type of thing to another
### find the type by using the function type()
## Converting int to float and vice versa
print ( float(1) ) # 1.0
print ( int(1.0) ) # 1
## Convertibg int/float to string
print ( str(1) ) # '1'
print ( str(1.0) ) # '1.0'
## Converting string to int
print ( int('1') ) # 'False'
## Converting Boolean to string
print ( str(False) ) # 'False'
# Most things in Boolean bool() are true including strings, expect bool(Flase) and
### anything with the result of 0 e.g. bool(0), bool(0.0) or bool('')
'Nabeel' and 'Seif'
# 'and' searches for the first False to return, or it'll return last True answer
# 'or' searches for the first True to return, or it'll return last False answer | true |
65a4aeb3dce742fe4176de7a81e4b1ecf1f7658a | nabeelnh/Python_Certificate | /PCEP/typcasting_n_inputoutput_operations/users_input.py | 744 | 4.15625 | 4 | #!/usr/local/bin/python3.8
name = input('What is your name: ')
colour = input('What is your favourite colour: ')
age = int(input('How old are you today: '))
print (name )
print ('is ' + str(age) + ' year old' )
print ('and his favourite colour is ' + colour )
print ("")
# Making it one line
## 'end' --> e.g adds space after each comma and puts the next line down to the top
print (name, end=" ")
print ('is ' + str(age) + ' year old', end=" ")
print ('and his favourite colour is ' + colour )
## 'sep' --> e.g adds space after each comma
print (name, 'is', age, 'years old and loves the colour', colour + '.', sep=" ")
print (name, 'is', age, 'years old and loves the colour', colour + '.', sep=": ") # add : under each separation | true |
61c368c37e7898bffc7611473f708e1c653d5c7a | nabeelnh/Python_Certificate | /PCEP/looping/controlling_loop_with_BREAK_n_CONTINUE.py | 1,537 | 4.375 | 4 | #!/usr/local/bin/python3.8
print ('\nBreak and Continue\n')
# Controlling loop execution with 'break' and 'continue'
##################################
# CONTINUE
##################################
'''
Continue: you go to the next iteration of the loop
and you won't go further with anything after the 'continue' keyword
i.e. it'll stop the current iteration of the loop and go to the next
'''
print ('CONTINUE CONDITION')
count = 0
while count <= 10:
if count % 2 == 0:
count += 1
continue
print(f'This is an odd number: {count}') # is a short hand for doing string formatting
count += 1
# print('This is an odd number:', count) == print(f'This is an odd number: {count}')
##################################
# BREAK
##################################
'''
Break: stops the execution of the loop entirely
i.e. it will not go to the next itteration.
'''
print ('\nBreak CONDITION\n')
count = 1
while count < 10:
if count % 2 == 0:
count += 1
break
print(f'This is an odd number: {count}')
count += 1
##################################
# EXAMPLE
##################################
colours = ['red', 'pink', 'blue', 'purple']
for colour in colours:
if colour == 'red':
continue
elif colour == 'blue':
break
else:
print(f'\nThe colour: {colour}\n')
# only 'pink' should be printed
# red ==> continue = cancel current itteration
# pink ==> print the colour
# blue ==> break = cancel the entire parent looping system | true |
fa247ee2a2c14ee7315530c4943f73b591969405 | nabeelnh/Python_Certificate | /PCEP/looping/else_in_loops.py | 966 | 4.1875 | 4 | #!/usr/local/bin/python3.8
##################################################
print('While loop')
##################################################
count = 1
while count <= 3:
print (count)
count += 1
else:
print('while loop has completed')
##################################################
print('\nElse loop')
##################################################
for each_number in (1, 2, 3):
print(each_number)
else:
print('for loop has completed')
##################################################
print('\nReal life applications and use\n')
##################################################
colours = ['red', 'white', 'blue', 'purple', 'orange']
for colour in colours:
if colour == 'purple':
print('The colour', colour, 'is in the list')
break
else:
print('The colour purple is not in the list')
# You should only really use the else statement in the for loop if you're using break inside the for loop.
| true |
ea1da4f29a8a539b7f1fd784632478bf1f454bda | nabeelnh/Python_Certificate | /PCEP/scoping/scopes.py | 1,148 | 4.3125 | 4 | #!/usr/local/bin/python3.8
'''
The variables and objects that we're working with are only accessible within certain scopes.
When we say that we're working in a different "scope" in Python, we mean that we're within the
boundaries of a function or a class. This is important because while within the body of a
function or class, the variables that we create are not automatically accessible outside of that context.
'''
#################################
print('Without Scope:')
#################################
'the variables at the top are accessible to the rest of the script'
if 1 < 2:
x = 5
while x < 6:
print(x) # 5
x += 1
print(x) # 6 (as it exited the loop at 6)
#################################
print('\nWith Scope:')
#################################
del x # make x undefined
def setting_x():
x = 5
setting_x()
while x < 6: # the value of x is unknown
print(x)
x += 1
print(x) # name 'x' is not defined
'''Summary: If you define a variable inside a function, you do not have access to it outside
of the function.
''' | true |
9b08c2250e002412255423186fa03ccde88932c2 | nabeelnh/Python_Certificate | /PCEP/strings/string_methods_p2.py | 1,322 | 4.625 | 5 | #!/usr/local/bin/python3.8
print ('\nString methods 2\n')
# Strings can be used as Tokens: a collection of things e.g.
#################
# SPLIT
#################
phrase = 'This is a simple phrase' # a Token
print ( phrase.split() ) # Splits the token into items in a list: ['This', 'is', 'a', 'simple', 'phrase']
# default: split by space
url = 'https://example.com/users/samantha'
users_name = url.split('/') # ['https:', '', 'example.com', 'users', 'samantha']
print ( users_name[-1] ) # Samantha
#################
# JOIN
#################
# Split a token
token = 'This is a simple token'
splitted_token = token.split()
print ( splitted_token ) # ['This', 'is', 'a', 'simple', 'token']
# Join back the splitted token
joined_token = ' '.join(splitted_token) # Joined the line based of the space in between them
print ( joined_token ) # This is a simple token
print('\n')
#################
# FORMAT
#################
# Different inputs in the tuple
print ( 'Hello my name is {} and I am learning {}'.format('Tyson', 'Python') )
# Repeating input in the tuple
print ( 'Hello my name is {0} and I am learning {1}. Much love {0}'.format('Tyson', 'Python') )
| true |
10f8fa288a7de52be86b80f0ebe8929fdb10b3b5 | dimik3/itstep | /Pyhton/ClassRoom/21.03.2017.py | 1,102 | 4.21875 | 4 | class First: #класс, в котором будем менять атрибут
color = "red" #собственно сам атрибут
def out(self): #метод, который выведет результат наших действий
print (self.color + " !") #вывод
f = First() #объявляем первый объект
class change: #класс, методы которого изменят атрибут color в объекте f
def change(self,color): #метод, делающий изменения
f.color = color #в этой строке присваиваем новое значение атрибуту color в объекте f
c = change() #объявляем второй объект
f.out() #смотрим существующее значение атрибута color в объекте f
newcolor = input("цвет?: ") #присваиваем новый цвет
c.change(newcolor) #передаём новое значение в метод change объекта c
f.out() #смотрим результат
| false |
52c9e7ad310e4166c2b46950c9c7b42a9e2bba59 | HendryRoselin/100-days-of-python | /Day03/funcode3.py | 343 | 4.34375 | 4 | ## Code for finding the leap year
year = int(input("Year you want to check?: "))
if (year % 4 == 0):
if (year % 100 ==0):
if (year % 400 ==0):
print ("This is Leap year")
else:
print("This is not a leap year")
else:
print("This is Leap year")
else:
print("This is not a leap year") | false |
72517065a800ed3bddb53b63ec93d3706c6003f5 | rowanpang/noteGit | /python/basic/class.py | 899 | 4.15625 | 4 | #!/usr/bin/python
class twice:
def __init__(self):
self.data = 0
def add(self, x):
self.data += x
def addtwice(self, x):
self.add(x)
self.add(x)
print '-------------class twice-----------------'
b = twice()
print b.data
b.addtwice(5)
print b.data
print '\n\n'
class ctest():
i = '23456'
def func(self):
return 'hello world'
print '-------------class ctest-----------------'
print ctest.i
ct = ctest()
print ct.i
ct.i = '45677'
print ctest.i
print ct.i
print '\n\n'
print '-------------class Dog-----------------'
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
f = Dog('ffff')
e = Dog('eeee')
f.add_trick('rooooo')
e.add_trick('eeeeeee')
print f.tricks
print e.tricks
| false |
b18db7e52bd9541d62f63a76a9996d4852d16d53 | zeng531196248/pythondemo | /demo/dictPm.py | 1,245 | 4.21875 | 4 | #字典的学习
#直接调用函数dict()
fdic=dict(([1,"y"],[2,"x"]))
print(fdic)
#调用函数fromkeys
#fromkeys(Keys,value)
#并不是一一对应。是多对一
#{1: ('x', 2, 3), 2: ('x', 2, 3), 3: ('x', 2, 3)}
fdics={}.fromkeys((1,2,3),("x",2,3))
print(fdics)
#当只有key时候
fdicNovalue={}.fromkeys((1,2))
print(fdicNovalue)
#{1: None, 2: None}
#访问字典中的值
dict2 = {'name': 'earth', 'port': 80}
for key in dict2.keys() :
print("key=%s,value=%s"%(key,dict2[key]))
#key=name,value=earth key=port,value=80
#检测是否包含key
print("name" in dict2) #True
#python3 之前存在has_key()这个函数,但是现在被抛弃了
#更新字典
dict2['name']="1sss" #{'name': '1sss', 'port': 80}
print(dict2)
#删除
del dict2['name'] #删除单一的
del dict2 #删除所有的
dict2 .clear() #清空
dict2.pop("name")#删除并返回
#复制
dict2.copy()
#验证是否可以做key,返回hash值就可以做,
hash("name")
#返回一个包含字典中(键, 值)对元组的列表
dict2.items()
# 返回一个包含字典中所有值的列表
dict2.values()
#字典中部允许一个key对应多个值
dict3={2:2,1:"1"}
dict2.update(dict3)#可以把dict3加入dict2中,key重复的直接覆盖,不存在的直接添加
| false |
bccf8dd93caa78f46f355190e0c36f9546a0d800 | Tnelsonn/planetarium | /planetpt2.py | 603 | 4.1875 | 4 |
from planet import planet
Mars = planet("Mars ", "6.4171×1023 kg", " -82 F", "1000ft", "141.6 million mi")
Earth = planet("Earth", "5.972 * 10^24 Kg","70 F", "3389.5 Km"," 92.96 million mi")
Jupiter = planet("Jupiter", "1.898 × 10^27 kg (317.8 M⊕)","108 C","43,441 mi","483.8 million mi")
Neptune = planet("Neptune", "1.024 × 10^26 kg (17.15 M⊕)", "-201 C", "15,299 mi", "2.793 billion mi")
print("What planet would you like to see?")
p = input()
if(p == "Mars"):
print(Mars)
if(p == "Earth"):
print(Earth)
if(p == "Jupiter"):
print(Jupiter)
if(p == "Neptune"):
print(Neptune)
| false |
e43c03dc4bd0d4df83f4c93d19b3369ca8123f7d | Fernando-Rodrigo/Exercicios | /Ex099.py | 553 | 4.1875 | 4 | """Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa deve anlisar todos os valores e dizer qual deles é o maior. Informar a quantidade de números passados como parâmetros."""
def maior(* v):
print()
print('--' * 30)
print(f'Os valores digitados foram {v}')
print(f'O total de valores digitados foi {len(v)}')
print(f'O maior valor digitado foi {max(v)}')
print('--' * 30)
maior(0, 9, 7, 3, 5)
maior(6)
maior(99, 104, 3, 200, 1, 25, 73, 88, 99, 111)
| false |
0afb25da0cc379a1dff57ab17287142de2ff3682 | Fernando-Rodrigo/Exercicios | /Ex057.py | 403 | 4.1875 | 4 | """Faça um programa que leia o sexo de uma pessoa, mas só aceite os valore 'M' ou 'F'. Caso esteja errado, peça a digitação novamente até ter um valor correto."""
sexo = input('Digite o sexo de uma pessoa [M/F]: ').upper()
while sexo not in 'MF':
sexo = input('Digite corretamente o sexo da pessoa!!! Digite o sexo de uma pessoa [M/F]: ').upper()
print('Você digitou corretamente o sexo!')
| false |
329295c6afa6c482c04d2851e192aa76b15f9dfe | Fernando-Rodrigo/Exercicios | /Ex105.py | 1,406 | 4.28125 | 4 | """Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar e vai retornar um dicionário com as seguntes informações: -Qauntidade de notas; -A maior nota; -A menor nota; -A média da turma; -A situção(opcional(padrão=False)). Adicione também as docstrings da função. Passar várias notas por padrão sem pedir ao usuário para digitar as notas e situação."""
def notas(*notas, situacao=False):
"""
->Função de análise de notas de uma turma
:param *notas: recebe várias notas para serem analisadas
:param situação: recebe True ou False para mostrar ou não a situação da sala
:return: retorna um dicionário com as informações das notas recebidas
"""
nota = {}
media = sum(notas) / len(notas)
nota['Total'] = len(notas)
nota['MaiorNota'] = max(notas)
nota['MenorNota'] = min(notas)
nota['Média'] = media
if situacao == True:
if media < 4:
nota['situação'] = 'Péssima'
if media < 5:
nota['situação'] = 'Ruim'
if media < 7:
nota['situação'] = 'Boa'
if media < 9:
nota['situação'] = 'Muito Boa'
if media >= 9:
nota['situação'] = 'Excelente'
return nota
print(notas(1, 7, 8.5, 6, 2.5, situacao=False))
print(notas(9, 7, 9.1, 8.9, 7.8, 7.9, 6, 8, situacao=True))
| false |
02234d381547cbcccc2452036fd620d3c788bdce | Fernando-Rodrigo/Exercicios | /Ex059.py | 1,188 | 4.40625 | 4 | """Crie um programa que leia dois valores e mostre um menu na tela: [1]Somar [2]Multiplicar [3]Maior [4]novos números [5]Sair do programa Seu programa deverá realizar a operação solicitada em cada caso."""
n1 = float(input('Digite o primeiro valor: '))
n2 = float(input('Digite o segundo valor: '))
opcao = int(input('Qual a opção de operação que deseja realizar: \n[1]Somar\n[2]Multiplicar\n[3]Maior\n[4]Novos números\n[5]Sair do programa. '))
while opcao != 5:
if opcao == 1:
print('A soma dos valores {} com {} é {}'.format(n1, n2, n1 + n2))
elif opcao == 2:
print('O resultado da multiplicação entre {} e {} é {}'.format(n1, n2, n1 * n2))
elif opcao == 3:
if n1 > n2:
print('O maior número digitado é {}'.format(n1))
else:
print('O maior número digitado é {}'.format(n2))
elif opcao == 4:
n1 = float(input('Digite o primeiro valor novo: '))
n2 = float(input('Digite o segundo valor novo: '))
opcao = int(input('Qual a opção de operação que deseja realizar: \n[1]Somar\n[2]Multiplicar\n[3]Maior\n[4]Novos números\n[5]Sair do programa. '))
print('Fim do programa!!!')
| false |
15d20f67e534ee373dbbff2d4f5772d73525a09b | Fernando-Rodrigo/Exercicios | /Ex085.py | 579 | 4.25 | 4 | """Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e impares. No final mostre os valores pares e impares em ordem crescente."""
valores = [[], []]
for i in range(0,7):
num = int(input(f'Digite o {i + 1}º número: '))
if num % 2 == 0:
valores[0].append(num)
elif num % 2 != 0:
valores[1].append(num)
valores[0].sort()
valores[1].sort()
print(f'Os números pares digitados são {valores[0]}')
print(f'Os números impares digitados são {valores[1]}')
| false |
1a13c2b403a2912c31ade626179f609feaad46bb | kiranHR/game | /fibbonaci_series_using_while_loop.py | 280 | 4.125 | 4 | #python program to display first n fibbonaci numbers using while loop
n=int(input("Enter a limit:"))
a=0
b=1
i=3
print("first",n,"fibbonaci series are as follows")
print(a,b)
while i<=n:
c=a+b
print(c)
a=b
b=c
i=i+1
print("End of the program")
| true |
0dd1a913b10a17ac0c6c4fd0f75aa2f7773b824e | VniciusMiranda/Web-Scraping-with-Python | /chapters/chapter7.py | 2,266 | 4.3125 | 4 | """
===> Chapter 7: Cleaning Your Dirty Data <===
--- code samples from the book Web Scraping with Python ---
This chapter title is pretty descriptive. The web is a place
where is easy to get thing that you didn't expect, that's why is
important to write defensive code to handle this bad formatted data
as if you were handling errors.
In linguistic exist the concept of n-grams that is basically a
sequence of words that are usually use in text and the chapter starts
by defining the concept of n-gram and giving a sample code to get n-grams,
in this case it is a 2-gram formatter.
The chapter than just show an example of how to clean the data in the code
and after using a software called OpenRefine.
"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
from collections import OrderedDict
import pprint
import re
import string
def n_grams(input, n):
'''
:param input: text
:param n: number of words
:return: all n-grams of the text
'''
output = list()
for i in range(len(input) + n - 1):
output.append(input[i: i + n])
return output
def clean_input(input):
input = re.sub("\n+", " ", input)
input = re.sub(" +", " ", input)
input = re.sub("\[[0-9]*\]", "", input)
input = bytes(input, "UTF-8")
input = input.decode("ascii", "ignore")
cleanInput = list()
print(type(input))
input = input.split(' ')
for item in input:
item = item.strip(string.punctuation)
if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
cleanInput.append(item)
return cleanInput
if __name__ == "__main__":
try:
html = urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
except HTTPError as error:
print(error.getcode())
soup = BeautifulSoup(html, features="html.parser")
content = soup.find("div", {"id": "mw-content-text"}).get_text()
content = clean_input(content)
ngrams = n_grams(content, 2)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(ngrams)
print("number of n grams of 2 is: {0}".format(len(ngrams)))
| true |
78caef38c0c39454ae2219c6e7ebffb8cc7efac7 | CAaswinraj/python-project | /Bottles_of_Beer_On_the_Wall.py | 1,441 | 4.625 | 5 | # Create a program that prints out every line to the song "99 bottles of beer on the wall." This should be a pretty simple program, so to make it a bit harder, here are some rules to follow.
# RULES
# If you are going to use a list for all of the numbers, do not manually type them all in. Instead, use a built in function.
# Besides the phrase "take one down," you may not type in any numbers/names of numbers directly into your song lyrics.
# Remember, when you reach 1 bottle left, the word "bottles" becomes singular.
# Put a blank line between each verse of the song.
# https://www.reddit.com/r/beginnerprojects/comments/19kxre/project_99_bottles_of_beer_on_the_wall_lyrics/
def print_lyrics():
'''
This function will print the lyrics for 99 bottles of beer on the wall
'''
for x in range(99,2,-1):
#triple quotes for multiline strings
print("{} bottles of beer on the wall,{} bottles of beer.\n\tTake one down and pass it around,{} bottles of beer on the wall.\n".format(x,x,x-1))
#printing last four lines as they are different
print("2 bottles of beer on the wall, 2 bottles of beer.\n\tTake one down and pass it around, 1 bottle of beer on the wall\n1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.")
print_lyrics()
| true |
3978720f00f1ae7514bd58c9be04a11998b202a4 | dalangston/100-Days-of-Code | /Day-002/tip_calc.py | 421 | 4.1875 | 4 | print("Welcome to the Tip Calculator\n")
total = 0
ways_split = 1
percent = 0
while not total > 0:
total = float(input("What was the bill total?\n"))
ways_split = int(input("How many people will split the bill?\n"))
if ways_split < 1:
ways_spllit = 1
percent = float(input("What percentage tip woule you like to give?\n"))
print(f"Each person should pay: ${(total * (1 + (percent/100))) / ways_split:.2f}")
| true |
9d44b9190ce5f73b8c7eb78f45346c6c0820baa7 | jamexvic04/python-programs | /palindrome.py | 265 | 4.21875 | 4 | def ispalindrome():
a_str = str(input("enter any word: "))
a_str = a_str.casefold()
rev_str = reversed(a_str)
if list(a_str) == list(rev_str):
print("it is a palindrome")
else:
print("it is not a palindrome")
ispalindrome() | false |
088e8d29fb70dc86c6c5007700b34b3508263ec3 | codingtao/Python | /廖雪峰_Python/4.py | 263 | 4.21875 | 4 | # 条件判断
# -*- coding: utf-8 -*-
height = 1.75
weight = 73
bmi=weight/(height*height)
if bmi <=18.5:
print("过轻")
elif bmi<=25:
print("正常")
elif bmi<=28:
print("过重")
elif bmi<=32:
print("肥胖")
else:
print("严重肥胖") | false |
a810d6d1855c9a756a5b82c493c93ec8a61af3d9 | alinmuraretu/alin1987 | /programsmad/ifelsestatements.py | 540 | 4.125 | 4 | e = 9
f = 8
if e < f:
print('e is lees than f')
elif e == f:
print('e is equal to f')
else:
print(' e is greater than f')
g = 9
h = 8
if g < h:
print('g is less than h')
else:
if g == h:
print('g is equal to h')
else:
print('g is greater than h')
name = "Alin"
inaltimea_m = 1.8
greutatea_kg = 95
bmi = greutatea_kg / (inaltimea_m ** 2)
print('bmi: ')
print(bmi)
if bmi < 25:
print(name)
print('is not overweight')
else:
print(name)
print('is overweight')
| false |
9ae63c2e2795d461f4b9e6049791476a3ff41dc7 | darlenefung/PowerFunction | /powerFunctionRecursion.py | 395 | 4.21875 | 4 | # Darlene Fung
# 4/11/16
def power(base, exponent): # define the function
''' Takes a base and exponent and calculates the value of base raised to the power of the integer '''
if exponent == 0: # covers special case and last time the exponent needs to be multiplied
return 1
else: # keeps multiplying the base using recursion
return base * power(base, exponent -1) | true |
3719db205b3f9ba802dfb30eb215323eeabcbc68 | sayantan-deb/PythonScripts | /Problemset-02/divisibility.py | 526 | 4.4375 | 4 | # A number, a, is a power of b if it is divisible by b and a/b is a power of b.
# Write a function called is_power that takes parameters a and b and returns True
# if a is a power of b. Note: you will have to think about the base case.
def is_power(a,b):
c = a/b
if ((a%b == 0) and (c%b == 0)):
return True
else:
return False
a=int(input("enter first number: "))
b=int(input("enter second number: "))
if(is_power(a,b)):
print(a," is power of ",b)
else:
print(a, " is not power of ", b)
| true |
004657bca704edb65d43c1fa67d81b68d8cfe722 | sayantan-deb/PythonScripts | /Python-ProblemSet/pow_root.py | 413 | 4.375 | 4 | # 5)Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that
# 0 < pwr < 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists
# , it should print a message to that effect.
n=int(input())
for i in range(1,6):
root=n**(1/i)
print('For ',i)
if int(root)**i==n:
print ("root=",root,"pow=",i)
else:
print('not found')
| true |
7a2963198b0fd67e6173bd678b843517ca3fccaa | ernestoacosta75/python-megacourse | /basics/return_print.py | 301 | 4.15625 | 4 | def converter(original_unit, coefficient):
return original_unit * coefficient
def returning():
return 10
def printing():
print(100)
original_unit = int(input("Enter the original unit: "))
coefficient = float(input("Enter the coefficient: "))
print(converter(original_unit, coefficient)) | true |
9aacf17adb3095d1467d1f87589a2ece3b243547 | 1c3t0y/finalproj-algorithms | /algorithms/numeric/menu_numeric.py | 1,645 | 4.15625 | 4 | import os
import utils.lectura_datos as leer
import algorithms.numeric.fibonacci as fib
import algorithms.numeric.factorial as fac
def menu_numeric():
opcion = '0'
while(opcion != 'q'):
os.system("clear")
print("Algoritmos numéricos: \n")
print("1) Factorial de un número (recursivo)")
print("2) Factorial de un número (iterativo)")
print("3) i-ésimo número de Fibonacci (recursivo)")
print("4) i-ésimo número de Fibonacci (iterativo)")
print("q) Regresar al menu anterior")
opcion = str(input("¿Qué algoritmo desea utilizar?: "))
if(opcion == '1'):
numero = leer.numero_entero("Del que desea obtener su factorial")
res = fac.factorial_r(numero)
print("El factorial de "+ str(numero) + " es: " + str(res))
input("Presione enter para continuar...")
elif(opcion == '2'):
numero = leer.numero_entero("Del que desea obtener su factorial")
res = fac.factorial_i(numero)
print("El factorial de "+ str(numero) + " es: " + str(res))
input("Presione enter para continuar...")
elif(opcion == '3'):
numero = leer.numero_entero("de fibonacci que desea obtener")
res = fib.fibonacci_r(numero)
print("El "+ str(numero) + " de fibonacci es: " + str(res))
input("Presione enter para continuar...")
elif(opcion == '4'):
numero = leer.numero_entero("de fibonacci que desea obtener")
res = fib.fibonacci_i(numero)
print("El "+ str(numero) + " de fibonacci es: " + str(res))
input("Presione enter para continuar...")
elif(opcion == 'q'):
print("Saliendo...")
break
else:
print("Opcion incorrecta, intente de de nuevo")
input("Presione enter para continuar") | false |
57020e7fae4d2814bd86fe457c8d2895ca615d64 | mericbal/Work_Station | /python/python-worksheet.py | 2,535 | 4.21875 | 4 | import random
import sys
print('hello meric')
# Here are some basic argument specifiers you should know:
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
# %x/%X - Integers in hex representation (lowercase/uppercase)
print('5+5 =', 5+5) # => '5+5 = 10'
print('10 % 3 =', 10%3) # => '10 % 3 = 1'
print('10 // 3 =', 10//3 ) # => '10 // 3 = 3'
name= 'meric'
age= 31
knows= 'ruby'
print(" `%s` is `%s` years old and knows `%s` ." % (name, age, knows) )
###
letters = ['a', 'b', 'c', 'd']
print(letters[1:4]) # from '1' to '3' # not includeing '4' => 'b','c','d'
letters.append('e') # => pushed 'e' into letters array
# del letters[0] # deletes letters
letters.insert(1, 'x')
letters.sort
letters.reverse
print(len(letters)) # length
print(max(letters)) # either return the highest or the alphabetically highest
print(min(letters)) # max opposite
obj = {
'a' : '1',
'b' : '2',
'c' : '3',
'd' : '4'
}
print(obj.keys()) # a,b,c,d
print(obj.values()) #1,2,3,4
# if else
age = 31
if age > 21 :
print('Old enough to smoke')
else :
print('NOT old enough to smoke')
if age < 16 :
print('can not drive')
elif age <= 21 :
print('can drive but can not drink')
else :
print('can drink and drive :) ')
if ((age >= 16) and (age < 21 )) :
print('can drive but cannot drink')
# loops
for x in range(0, 10) :
print(x, 'heloooo')
# print('\n')
letters = ['a', 'b', 'c', 'd']
for y in letters :
print(y)
###
random_numbers = random.randrange(0, 10) # to user `random` function we have to import at the top
while(random_numbers != 7) :
print(random_numbers)
random_numbers = random.randrange(0, 10)
##
i = 0;
while(i <= 7):
print(i)
i += 1
#### functions
def sumNums(x,y):
total = x + y
return total
print(sumNums(25,5))
###
print('your name ?')
name = sys.stdin.readline()
print('hello', name)
'meric'.capitalize()
'meric'.split(' ')
###
# basically creates a file and put some text in it
# file = open('text.txt', 'wb') #'wb is for write to the file' ########## 'ab+' to read and append
# print(file.mode)
# print(file.name)
# file.write(bytes('Write me \n'))
# file.close()
file = open('xxx.yaml', 'wb')
file.write(bytes('xxx'))
file.close()
# to read the file we have
file = open('text.txt', 'r+')
print(file.read())
# os.remove('text.txt') # to remove the file
# MB | true |
a03926f96ba2879663eecd3cf0d47a29b42e3cca | Gaiping-Liu/PythonLearning | /GaipingLiu/Basic/05Dict.py | 913 | 4.25 | 4 | # _*_ coding: utf-8 _*_
d = {'a': 95, 'b': 75, 'c': 85}
print(d['a'])
print('d' in d)
# get() 如果key 不存在,返回None 或自己指定的value
print(d.get('Thomas'))
print(d.get('Thomas', -1))
print(d.pop('b')) # delete key 'b' and it's value from dict
'''
dict 根据key来计算value,这个通过key计算位置的算法成为哈希算法,为了保证hash 的正确性,key 的对象就不能变
在python 中,字符串,整数都是不可变的,因此可以作为key,而list 是可变的,就不能作为key
'''
# set 是key值不重复的list,set 是无序的, set 是无序的和无重复元素的集合,因此可以做数学意义上的交集、并集等操作
s = set([1, 1, 2, 2, 3, 3])
print(s)
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
print(s1 & s2)
print(s1 | s2)
testDictTuple = {(1, 2, 3): 10, (2, 3): 5}
testSetTupe = set((1, 2, 3))
print(testDictTuple)
print(testSetTupe)
| false |
677f67aa7d37d3004c143838a0185e5341e895b7 | vjoyner/pythonScripts | /Script1010.py | 2,573 | 4.15625 | 4 | #10/10/19 Valarie Harrison
#Lecture
##def findArea(radius):
## area = 3.14159 * radius ** 2
## return area
##print findArea(3)
#To iterate same program (ex: RPS game),
#def RPS(number): #change "for i in range(100)", to "for i in range(number)".
#code placed here (indent)
#print statement of results placed here
#return sum(ties)
##def RPS(number):
## import random
## option = ["R","P","S"] #each computers' option
## comp1_wins = [] #lists to append the results of each game depending on the results
## comp2_wins = []
## ties = []
## for i in range(number): #iterates 100 games
## comp1_index = random.randrange(0,len(option)) #random choice index position for computer 1
## comp1_choice = option[comp1_index] #actual value of the random choice index position for computer 1
## comp2_index = random.randrange(0,len(option))
## comp2_choice = option[comp2_index]
## if (comp1_choice == "R" and comp2_choice == "S") or \
## (comp1_choice == "S" and comp2_choice == "P") or \
## (comp1_choice == "P" and comp2_choice == "R"): #cases where computer 1 would win
## comp1_wins.append(1) #appends to computer 1 wins list
## elif (comp2_choice =="R" and comp1_choice == "S") or \
## (comp2_choice == "S" and comp1_choice == "P") or \
## (comp2_choice == "P" and comp1_choice == "R"): #cases where computer 2 wins
## comp2_wins.append(1)
## else:
## ties.append(1)
## print "Computer 1 won",sum(comp1_wins),"games, Computer 2 won",sum(comp2_wins),"games.\nThe draw game percentage out of 100 games is",sum(ties),"%."
## return sum(ties)
##
##RPS(100)
##
##def printhello():
## print "Hello world"
##
##printhello()
##
##def returnhello():
## return "Hello world"
##
##def returnhello(name):
## return "Hello, my name is %s"%name
##print returnhello("Val")
##def f(x):
## return x**2 + 1
##print f(4)
##
##
##def get_ing(wd):
## return wd + 'ing'
##print get_ing('walk')
##
##
##def same_initial(wd1, wd2):
## """Tests if two words start with the same character, and returns True/False. Case distinction is ignored."""
## if wd1[0].lower() == wd2[0].lower():
## return True
## else:
## return False
##print same_initial('apple', 'orange')
##print same_initial('Annie','apple')
##
##help(random.randint)
##
##import os
##import sys
##print sys.path
##
##print sys.path[0]
| true |
1dc73edc626e463b05117ff65072e3586de78a2c | yiguming/python_core_progreamming | /chapters5/exe5_8.py | 896 | 4.125 | 4 | #!/usr/bin/python
import math
PI = math.pi
class Square(object):
def __init__(self ,a=5):
self.bianchang = a
def mianji(self):
return self.bianchang ** 2
def tiji(self):
return self.bianchang ** 3
class Ball(object):
# result = 0
def __init__(self, r = 5):
self.banjing = r
def mianji(self):
return PI * (self.banjing ** 2)
def tiji(self):
return (4/3.0) * PI * (self.banjing ** 3)
# print "%.2f" % self.result
num = int( raw_input("Please input a number:"))
testsquare = Square(num)
print "The mianji of Square bianchang %d is %.2f" % (num,testsquare.mianji())
print "The tiji of Square bianchang %d is %.2f" % (num,testsquare.tiji())
testball = Ball(num)
print "The mianji of Ball banjing %d is %.2f" % (num,testball.mianji())
print "The tiji of Ball banjing %d is %.2f" %(num,testball.tiji())
| false |
41ef72aa9a55da73bdd10be8d328b0b0ebc8f157 | R161518/Jyothi-Srirangam | /matrix.py | 1,405 | 4.21875 | 4 | #creating a matrix a(3*3)
#arr=np.asarray(input("enter the matrix elements:")) with this user can enter elements
import numpy as np
arr=np.asarray([[-4.3,5,2],[1,7,-5],[0,-3,3]])
arr2=np.asarray([[3,4,2],[4,4,5],[2,5,6]])
print arr
print arr2
#functions of numpy in matrix
print"rounded values of matrix:\n",np.round(arr)
print"absolute values of matrix:\n",np.absolute(arr)
print"square of matrix:\n",np.square(arr)
print"maximum value of matrix:",np.max(arr)
print"minimum value of matrix:",np.min(arr)
print"transpose of matrix:\n",np.transpose(arr)
print"trace of matrix",np.trace(arr)
print"median of matrix",np.median(arr)
print"addition of two matrices:",np.add(arr,arr2)
print"subtraction of one matrix from another:",np.subtract(arr,arr2)
print"multiplication of two matrices:",np.multiply(arr,arr2)
print"inner product of two matrices:",np.inner(arr,arr2)
#functions of linear algebra in matrix
print"eigen values of matrix:\n",np.linalg.eig(arr)
print"inverse of a matrix:\n",np.linalg.inv(arr)
print"determinant value of given matrix :",np.linalg.det(arr)
print"rank:",np.linalg.matrix_rank(arr)
print"singular values of matrix:",np.linalg.svd(arr)
print"condition number of matrix:",np.linalg.cond(arr)
print"sign and natural logarithm for determinant value:",np.linalg.slogdet(arr)
n=input("enter number to be power of matrix:")
print"power of n to matrix\n",np.linalg.matrix_power(arr,n)
| true |
a49998c09b4b1a4e36236701d99c13a5225f863c | calebm01/PythonUnitOneReview | /get_nameExample.py | 566 | 4.375 | 4 | #Caleb Mouritsen
#9/13/18
#get name function
#def get_name():
#ask user for name
#name = input("what is your name?: ")
#verify name
#display name
#print("the name you entered was", name)
#print("this is our function")
#get_name()
#Finding the area of a circle
def AreaofCircle(radius1):
pi = 3.14159265
#1 get a radius
radius = radius1
#2 compute the area
radius = float(radius)
area = radius*radius*pi
#3 display the area
print("the area of the circle is: ", area)
radiusx=input("what is the radius")
AreaofCircle(radiusx)
| true |
00ce4938f4bfeb3ad36d030d9d5ede47a3942340 | Joziahb141/year-11-prgramming-assesment | /Rock, Paper, Scissors/Rock, Paper, Scissors.py | 2,376 | 4.21875 | 4 | from random import choice
play = True
options = ['ROCK','PAPER','SCISSORS']
bot_score = 0
user_score = 0
print("""
**************************************************
Rock,Paper,Scissor
**************************************************
Welcome to the classic game of Rock,Paper,Scissors
""")
valid = False
while not valid:
try:
games = int(input("How many rounds do you want to play?\n"))
if 0 < games:
valid = True
else:
print("PLEASA TYPE IN A WHOLE NUMBER")
except ValueError:
print("PLEASA TYPE IN A WHOLE NUMBER")
while games > 0 and play == True:
games -= 1
valid = False
while not valid:
try:
user_choice = input("What would you like to choose Rock, Paper or Scissors?\n")
if user_choice.upper() in options:
valid = True
else:
print("PLEASA TYPE IN ROCK, PAPER OR SCISSORS")
except ValueError:
print("PLEASA TYPE IN ROCK, PAPER OR SCISSORS")
bot_option = choice(options)
if user_choice.upper() == options[0]:
if bot_option == options[1]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you lost!!")
bot_score += 1
elif bot_option == options[2]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you won!!")
user_score += 1
else:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} its a draw")
elif user_choice.upper() == options[1]:
if bot_option == options[2]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you lost")
bot_score += 1
elif bot_option == options[0]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you won!!")
user_score += 1
else:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} its a draw")
else:
if bot_option == options[0]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you lost")
bot_score += 1
elif bot_option == options[1]:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} you won!!")
user_score += 1
else:
print(f"the bot chose {bot_option.title()} you did {user_choice.title()} its a draw")
print(f"your score is {user_score}\nthe computers score is {bot_score}")
print("****** Thankyou for playing ******") | true |
65a49b64614faf53f98ef007c6d6c222f6bc3cbc | Roque98/Python-Ejercicios | /parte1/02_circulos.py | 600 | 4.25 | 4 | """
Círculos
Escriba un programa que reciba como entrada el radio de un círculo
y entregue como salida su perímetro y su área:
Ejemplo:
Ingrese el radio: 5
Perimetro: 31.4
Área: 78.5
"""
import math
def getArea(radio):
return math.pi * radio**2
def getPerimetro(radio):
return 2 * math.pi * radio
if __name__ == "__main__":
# Entrada
radio = float(input("Ingrese el radio: "))
# Proceso
perimetro = round(getPerimetro(radio), 2)
area = round(getArea(radio), 2)
# Salida
print(f'Perimetro: {perimetro}')
print(f'Área: {area}') | false |
3a19e32fe7d1f00c3998697ea395e55f8eee38c5 | Darkseidddddd/project | /leetcode/Search_Insert_Position.py | 624 | 4.1875 | 4 | def searchInsert(nums, target):
if not nums:
return 0
n = len(nums)
left, right = 0, n-1
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return left
def searchInsert_(nums, target):
if target in nums:
return nums.index(target)
else:
nums.append(target)
nums.sort()
return nums.index(target)
if __name__ == '__main__':
nums = [1,2,4,5,6]
target = 7
print(searchInsert_(nums, target)) | true |
609360c710ce84c8bcb5e2c67b5601952a2359eb | gkraften/P-Uppgift | /Spel/B-nivå/interface.py | 2,438 | 4.125 | 4 | import reversi
import string
import math
def print_separator(width, offset):
'''Print a line separating two rows in the board.'''
print(" "*offset, end="")
print("—"*width)
def digits(d):
'''Returns the number of digits in d.'''
return int(math.log10(d)) + 1
def get_int(msg, error):
success = False
val = None
while not success:
try:
val = int(input(msg))
success = True
except ValueError:
print(error)
return val
def get_row_col(size):
'''Returns selected row and column. size is the
size of the board.'''
row = get_int("Välj RAD att placera pjäs på: ", "Raden måste vara en siffra")
while not 1 <= row <= size:
print("Raden måste ligga mellan 1 och %d" % size)
row = get_int("Välj RAD att placera pjäs på: ", "Raden måste vara en siffra")
col_input = input("Välj KOLUMN att placera pjäs på: ").upper()
while len(col_input) != 1 or not (col_input in string.ascii_uppercase and string.ascii_uppercase.index(col_input) < size):
print("Kolumnen måste vara en bokstav mellan A och %s" % string.ascii_uppercase[size])
col_input = input("Välj KOLUMN att placera pjäs på: ").upper()
col = string.ascii_uppercase.index(col_input)
return (row-1, col)
def should_skip():
'''Returns whether the user wants to skip its
turn or not.'''
skip = input("Vill du stå över din runda (enter för nej, vad som helst för ja)?")
return len(skip) != 0
def display_board(b):
'''Print the board b. The width must be max 26.'''
board = b.get_board_list()
if len(board) > 26:
raise ValueError("Size of board must not exceed 26.")
n_digits = digits(len(board))
offset = n_digits + 2
print(" "*(offset+1), end="")
width = 0
for i in range(len(board)):
print(string.ascii_uppercase[i % 26], end=" ")
width += 4
width -= 1
print()
print_separator(width, offset)
for index,row in enumerate(board):
print(index+1, end=" "*(n_digits - digits(index+1)) + " | ")
for elem in row:
if elem == reversi.WHITE:
print("○", end="")
elif elem == reversi.BLACK:
print("●", end="")
else:
print(" ", end="")
print(" | ", end="")
print()
print_separator(width, offset) | false |
579cd3d25302325b544c77e34eb28923b3dbc0c3 | subezio-whitehat/CourseMcaPython | /c2python/c2p17.py | 302 | 4.28125 | 4 | #17)Sort dictionary in ascending and descending order.
y={'carl':40,'alan':2,'bob':1,'danny':3}
l=list(y.items())
print("Dictionary:",l)
l.sort()
print('Ascending order is',l)
l=list(y.items())
l.sort(reverse=True)
print('Descending order is',l) | false |
e3f3ad7bd9ff11231e192dce0b69aadd73a044fc | subezio-whitehat/CourseMcaPython | /c3python/c3p1.py | 206 | 4.21875 | 4 | #Factorial of a Number
def factorial():
num = int(input("Enter Number:"))
fact = 1
for i in range(1,num+1):
fact = fact*i
print("Factorial of "+ str(num)+": "+str(fact))
factorial() | true |
053008e2e8f0cf6952f95125151d8223695c802f | daniellebunker/accounting-scripts | /melon_info.py | 659 | 4.15625 | 4 | """Print out all the melons in our inventory."""
# Create a dictionary with the keys being the melon type
# and the values being everything else
from melons import melons
# def print_melon(melons):
# for name, attribute in melons:
# print(name, attribue)
# def print_melon()
def print_all_melons(melons):
"""Print each melon with corresponding attribute information."""
for melon_name, attributes in melons.items():
print(melon_name.upper())
for attribute, value in attributes.items():
print(f'{attribute}: {value}')
print('===================================')
print_all_melons(melons) | true |
56a957cb987031f1b4dc825e69288ba8f8136406 | pkohler01/Training | /Coursera/University of Michigan - Python for Everybody Specialization/Python Data Structures/Week 4/Chapter8_4.py | 933 | 4.53125 | 5 | # 8.4 Open the file romeo.txt and read it line by line. For each line, split
# the line into a list of words using the split() method. The program should
# build a list of words. For each word on each line check to see if the word
# is already in the list and if not append it to the list. When the program
# completes, sort and print the resulting words in alphabetical order.
# You can download the sample data at http://www.py4e.com/code3/romeo.txt
fname = input("Enter file name: ") #romeo.txt
fh = open(fname)
lst = list()
for line in fh:
value = line.rstrip()
value = line.split()
for element in value:
if element not in lst:
lst.append(element)
lst.sort()
print(lst)
fname = input("Enter file name: ") #romeo.txt
fh = open(fname)
lst = list()
for line in fh:
value = line.split()
for element in value:
if element not in lst:
lst.append(element)
print(sorted(lst))
| true |
37fef3888d175bbf3271171581be0443f659beac | inJAJA/Study | /homework/데이터 과학/p034_assert.py | 482 | 4.28125 | 4 | """
# assert
: 지정된 조건이 충족되지 않는다면 AssertionError 반환
"""
assert 1 + 1 ==2
assert 1 + 1 ==2, "1 + 1 should equal 2 nut didn't"
# 조건이 충족되지 않을 때 문구가 출쳑됌
def smallest_item(xs):
return(xs)
# assert smallest_item([10, 20, 5, 40]) == 5 # AssertionError
# assert smallest_item([1, 0, -1, 2]) == -1 # AssertionError
def smallest_item(xs):
assert xs, "empty list has no smallest item"
return min(xs) | false |
1ca1be098819d8a53f8491f6f7f8b809d10f4fd2 | 00agata/PythonLearning | /Lesson2/NumberOfZeros.py | 571 | 4.25 | 4 | '''
Given N numbers: the first number in the input is N, after
that N integers are given.
Count the number of zeros among the given integers and print it.
You need to count the number of numbers that are equal to zero,
not the number of zero digits.
'''
numberOfZeros = 0
while(True):
number = str(input('Provide integer: '))
if type(number) == str:
for i in list(number):
if i == '0':
numberOfZeros = numberOfZeros +1
print('Number of zeros: {}'.format(numberOfZeros))
else:
print('Invalid input value')
| true |
38e8849ffc2bce1f0f6efdb5ff17e10c919a2127 | shaungc-si507/Lab-05-repo-si507 | /Lecture_13___ORMs_and_db_relationships_export/db_insertdata.py | 2,277 | 4.25 | 4 | from models import *
from db import session, init_db
init_db()
# This does the connection all in one step
# After we do that basic setup, it is MUCH easier/is possible to insert data using the code we've built up.
# Insert a university into the database - in the university table
# First create an instance of our model University -- almost coming full circle
new_uni = University(name='University of California - Berkeley',capacity=22000,location="Berkeley, CA")
session.add(new_uni) # A lot like the git add idea
session.commit()
new_college = College(name="iSchool",capacity=2000,university=new_uni)
session.add(new_college)
session.commit()
# Here is some code to add a couple new students. Uncomment when you're ready to use it.
# Assumes students have: firstname, lastname, middle_name, grad_status that can be True or False, and could have an association with a college
# new_student = Student(firstname="Morgan",lastname="Nisibi",middle_name="Aya Blake",grad_status=True)
# ns2 = Student(firstname="Mary",lastname="Smith",middle_name="Kate",grad_status=True)
# session.add(new_student)
# session.add(ns2) # necessary to make it possible to refer to this in the session
# new_college.students.append(new_student)
# new_college.students.append(ns2) # eeach of these adds the new student to the *list of students*
# session.commit()
# IMPORTANT - changes you make via the SQLite DB browser don't truly take effect forever until you *save* the changes made in the browser.
# If you have the DB Browser open and connected to a database, you won't be able to run code using a db Session, because the database can only have one connection. It's like when you open a file in a program and don't close it, you can't open it again...except now everything on the computer that can access the db is playing the metaphorical game, not just one program.
# NOTE -- If we want to add a college for a university ALREADY there (say, before this program was written, which is different from that new_uni which is created IN the program) -- we have to do a query to check if it exists and then refer to that instance
# Super do-able!
# But first, let's just do this -- we'll provide additional resources that show examples like that, and may get a chance to talk about it live!
| true |
3e0767c0adf683cd9f29922df144cf42d0b6047d | Rerikhn/CheckArifmProgression | /Progression.py | 608 | 4.125 | 4 | # python 3.5.2
# This program determines whether a sequence of array elements is an arithmetic progression.
# Counting matches
count = 1
def arifm(obj):
global count
for i in range(len(obj)):
# Firstly check if index < length of list
if (i + 1) < len(obj):
# Secondly check if sequence matches with arithmetic sequence
if ((obj[2] - obj[1]) + obj[i]) == obj[i + 1]:
count += 1
if count == len(obj):
print("This is arifmetic progression.")
else:
print("This is not arifmetic progression.")
arifm([1, 2, 3, 4, 5]) | true |
6a0e3691ca30584946a0a3d4d4c7e36c70480e49 | kamalsingh-engg/udemy_courses_python | /16. GUI with Twinkter/tkinter_gui_example.py | 1,042 | 4.28125 | 4 | """"
lets see that how we can create GUI
it always returns a name what i am written in it
"""
from tkinter import *
window = Tk()
def my_gui():
print(b2_value.get())
b3.delete(1.0,END)
b3.insert(END,b2_value.get())
b1 = Button(window,text='execute',command=my_gui)
b1.grid(row=0,column=0)
b2_value = StringVar()
b2 =Entry(window,textvariable=b2_value)
b2.grid(row=0,column=1)
b3 = Text(window,height=1,width=20)
b3.grid(row =0 ,column =2)
window.mainloop()
""""
from first line it is import the tkinter so import all
2. next we create the windows which is blank
3. create a button having name of 'execute' and it execute the function which is writteen
4. crate a entry point which is used to provide input
5. grid is the way by which we can define its position
6. StringVar() is the command for getting the value of which we enter in it
6. create a text entry and by default it is degfined its position through its height and weight
7.function is defined and collecting its value from entry and return to text
""" | true |
5742df83cd97596e814fa7c4db30d4c156e6b633 | sanghyukp/Python_algorithm | /027/main2.py | 247 | 4.15625 | 4 | def fact(num):
factorial = 1
if num < 0 :
print("must be positive")
elif num == 0 :
print("factorial = 1")
else:
for i in range(1, num + 1):
factorial = factorial*i
print(num, factorial)
| false |
5488d180dcaa2effb9999ec63dda396dfb46f061 | tsjamm/LPyTHW | /ex21.py | 822 | 4.125 | 4 | def add(a, b):
print "Adding %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "Subtracting %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "Multiplying %d * %d" % (a, b)
return a * b
def divide(a, b):
print "Dividing %d / %d" % (a, b)
return a / b
print "Welcome to Primitive Math Functions"
x = int(raw_input("Enter First Number x = ")) # Converting String to Integer
y = int(raw_input("Enter Second Number y = "))# Converting String to Integer
one = add(x,y)
two = subtract(x,y)
three = multiply(x,y)
four = divide(x,y)
print "one = %d\ntwo = %d\nthree = %d\nfour = %d" % (one, two, three, four)
print "Now For Combination of Functions"
wow = add(one, subtract(two, multiply(three, divide(four, 2))))
print "The Combined Answer is ", wow, " real cool isn't it?"
| true |
20bc4de00cc89ae5bf2a323054dbc49aeb7a49b8 | jmhorcas/famapy-aafms | /montecarlo_framework/models/state.py | 1,422 | 4.25 | 4 | from abc import ABC, abstractmethod
class State(ABC):
"""
Representation of problems for searching strategies.
A representation of a state space must include the representation of the states themselves,
as well as the transitions or set of states directly accessible
from a give state (i.e., the successors).
Each kind of problem must extend this class to represent its states.
"""
@abstractmethod
def successors(self) -> list['State']:
"""All possible successors of this state."""
@abstractmethod
def random_successor(self) -> 'State':
"""Random successor of this state (redefine it for efficiency)."""
@abstractmethod
def is_terminal(self) -> bool:
"""Returns True if the state represents a terminal node (the goal of the problem)."""
@abstractmethod
def __hash__(self) -> int:
"""States must be hashable."""
@abstractmethod
def __eq__(self, other: object) -> bool:
"""States must be comparable."""
@abstractmethod
def cost(self, state: 'State') -> float:
"""Cost of the transition `self` -> state."""
@abstractmethod
def heuristic(self) -> float:
"""Heuristic estimation of the cost from `self` to the goal."""
@abstractmethod
def reward(self) -> float:
"""Assumes `self` is terminal node. Examples of reward: 1=win, 0=loss, .5=tie, etc."""
| true |
65c27fbd2b4f6f96d105f494918815de5c4d5b0b | mohamed-Gamal-Nor/python | /004_Comments.py | 604 | 4.4375 | 4 | # -------------------------------
# Informations About File
# License
# Who Created The File
# When The File Created
# Why The File Created
# Write Beside The Programming Line
# Write Before The Programming Line
# Prevent Code From Run
# -------------------------------
# This is Comment
print("I Love Python") # This is Inline Comment
print("Programming") # I Used This Method Because of Bla Bla Bla
print("Programming") # If You Used Test Method Will Through Error
"""
This is
Not
Multiple
Line
Comments
"""
a = 4
b = 3
print(f"{a//b}\n {a/b} ")
print(range(5))
for i in range(5):
print(i**2)
| true |
a7fe0444a57ed6244d2c075bd049f67556b3def1 | mohamed-Gamal-Nor/python | /107_OOP – Part 5 Class Attributes.py | 1,967 | 4.1875 | 4 | # -----------------------------------------------------
# -- Object Oriented Programming => Class Attributes --
# -----------------------------------------------------
# Class Attributes: Attributes Defined Outside The Constructor
# -----------------------------------------------------------
class Member:
not_allowed_names = ["Hell", "Shit", "Baloot"]
users_num = 0
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
Member.users_num += 1 # Member.users_num = Member.users_num + 1
def full_name(self):
if self.fname in Member.not_allowed_names:
raise ValueError("Name Not Allowed")
else:
return f"{self.fname} {self.mname} {self.lname}"
def name_with_title(self):
if self.gender == "Male":
return f"Hello Mr {self.fname}"
elif self.gender == "Female":
return f"Hello Miss {self.fname}"
else:
return f"Hello {self.fname}"
def get_all_info(self):
return f"{self.name_with_title()}, Your Full Name Is: {self.full_name()}"
def delete_user(self):
Member.users_num -= 1 # Member.users_num = Member.users_num -1
return f"User {self.fname} Is Deleted."
print(Member.users_num)
member_one = Member("Osama", "Mohamed", "Elsayed", "Male")
member_two = Member("Ahmed", "Ali", "Mahmoud", "Male")
member_three = Member("Mona", "Ali", "Mahmoud", "Female")
member_four = Member("Shit", "Hell", "Metal", "DD")
print(Member.users_num)
print(member_four.delete_user())
print(Member.users_num)
print(dir(member_one))
print(member_one.fname, member_one.mname, member_one.lname)
print(member_two.fname)
print(member_three.fname)
print(member_two.full_name())
print(member_two.name_with_title())
print(member_three.get_all_info())
print(dir(Member))
| true |
1e0e8b88334b07e4fcb3ada7e470ea82d342ae5e | Justinas-Ba/Checkio | /Call to Home.py | 2,921 | 4.21875 | 4 | '''
The bill is represented as an array with information about the calls. Help Nicola to calculate the cost for each of Sophia calls. Each call is represented as a string with date, time and duration of the call in seconds in the follow format:
"YYYY-MM-DD hh:mm:ss duration"
The date and time in this information are the start of the call.
Space-Time Communications Co. has several rules on how to calculate the cost of calls:
First 100 (one hundred) minutes in one day are priced at 1 coin per minute;
After 100 minutes in one day, each minute costs 2 coins per minute;
All calls are rounded up to the nearest minute. For example 59 sec ≈ 1 min, 61 sec ≈ 2 min;
Calls count on the day when they began. For example if a call was started 2014-01-01 23:59:59, then it counted to 2014-01-01;
For example:
2014-01-01 01:12:13 181
2014-01-02 20:11:10 600
2014-01-03 01:12:13 6009
2014-01-03 12:13:55 200
First day -- 181s≈4m -- 4 coins;
Second day -- 600s=10m -- 10 coins;
Third day -- 6009s≈101m + 200s≈4m -- 100 + 5 * 2 = 110 coins;
Total -- 124 coins.
Input: Information about calls as a tuple of strings.
Output: The total cost as an integer.
'''
def total_cost(calls):
import math
bill = 0
started = None
for call in calls:
call = call.split()
# Expressing seconds to minutes; Rounding to bigger number
mins = math.ceil(int(call[2])/60)
# Store todays date so we can check with later days
if call[0] == started:
# We need to check to things:
# have we talked more than 100 mins today, or not?
if (history + mins) > 100:
if history >= 100:
bill += mins*2
if history < 100:
bill += (100-history) + (mins-(100-history))*2
else:
bill += mins
history += mins
# Only check when day is different than previous call
else:
if mins > 100:
bill += 100 + (mins-100)*2
else:
bill += mins
history = mins
started = call[0]
return bill
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert total_cost(("2014-01-01 01:12:13 181",
"2014-01-02 20:11:10 600",
"2014-01-03 01:12:13 6009",
"2014-01-03 12:13:55 200")) == 124, "Base example"
assert total_cost(("2014-02-05 01:00:00 1",
"2014-02-05 02:00:00 1",
"2014-02-05 03:00:00 1",
"2014-02-05 04:00:00 1")) == 4, "Short calls but money..."
assert total_cost(("2014-02-05 01:00:00 60",
"2014-02-05 02:00:00 60",
"2014-02-05 03:00:00 60",
"2014-02-05 04:00:00 6000")) == 106, "Precise calls"
| true |
a8fba46f6e31961084f2e7930740eb99b1384146 | akaase/hw-06-tuples-dicts | /exercise3.py | 395 | 4.21875 | 4 | # Write your reverse_lookup function here
# def ...
phonebook = {
'Joe': '702-555-6495',
'Silvio': '504-555-3234',
'Greta': '213-555-4364',
'Jill': '415-555-5864'
}
print(reverse_lookup(phonebook, '504-555-3234')) #--> Silvio's number
print(reverse_lookup(phonebook, '213-555-4364')) #--> Greta's number
print(reverse_lookup(phonebook, '111-222-3333')) #--> Nobody's number
| false |
2c9a944c327d2d2100124d20b37fd78b6b85a801 | harshitbansal373/hackerrank-solutions | /python/the-birthday-bar.py | 2,695 | 4.28125 | 4 | '''
problem--
Lily has a chocolate bar that she wants to share it with Ron for his birthday. Each of the squares has an integer on it. She decides to share a contiguous segment of the bar selected such that the length of the segment matches Ron's birth month and the sum of the integers on the squares is equal to his birth day. You must determine how many ways she can divide the chocolate.
Consider the chocolate bar as an array of squares, s=[2,2,1,3,2]. She wants to find segments summing to Ron's birth day, d=4 with a length equalling his birth month, m=2. In this case, there are two segments meeting her criteria:[2,2] and [1,3].
Function Description--
Complete the birthday function in the editor below. It should return an integer denoting the number of ways Lily can divide the chocolate bar.
birthday has the following parameter(s):
s: an array of integers, the numbers on each of the squares of chocolate
d: an integer, Ron's birth day
m: an integer, Ron's birth month
Input Format--
The first line contains an integer n, the number of squares in the chocolate bar.
The second line contains n space-separated integers s[i], the numbers on the chocolate squares where 0<=i<=n.
The third line contains two space-separated integers, d and m, Ron's birth day and his birth month.
Output Format--
Print an integer denoting the total number of ways that Lily can portion her chocolate bar to share with Ron.
Sample Input 0--
5
1 2 1 3 2
3 2
Sample Output 0--
2
Explanation 0--
Lily wants to give Ron m=2 squares summing to d=3. The following two segments meet the criteria:
Sample Input 1--
6
1 1 1 1 1 1
3 2
Sample Output 1--
0
Explanation 1--
Lily only wants to give Ron m=2 consecutive squares of chocolate whose integers sum to d=3. There are no possible pieces satisfying these constraints:
Thus, we print 0 as our answer.
Sample Input 2--
1
4
4 1
Sample Output 2--
1
Explanation 2--
Lily only wants to give Ron m=1 square of chocolate with an integer value of d=4. Because the only square of chocolate in the bar satisfies this constraint, we print 1 as our answer.
'''
#code here
#!/bin/python3
import math
import os
import random
import re
import sys
def birthday(s, d, m):
count=0
for i in range(len(s)-m+1):
sum=0
for j in range(m):
sum+=s[i+j]
if sum==d:
count+=1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
s = list(map(int, input().rstrip().split()))
dm = input().rstrip().split()
d = int(dm[0])
m = int(dm[1])
result = birthday(s, d, m)
fptr.write(str(result) + '\n')
fptr.close()
| true |
e5ca72d51341dfafdd5a477af95dad664a4be5ee | harshitbansal373/hackerrank-solutions | /problem solving/digonal-difference.py | 1,807 | 4.5 | 4 | '''
problem--
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = 1+5+9=15. The right to left diagonal = 3+5+9=17. Their absolute difference is |15-17|=2.
Function description
Complete the digonal difference function in the editor below. It must return an integer representing the absolute diagonal difference.
diagonalDifference takes the following parameter:
arr: an array of integers .
Input Format
The first line contains a single integer, n, the number of rows and columns in the matrix arr.
Each of the next n lines describes a row, arr[i], and consists of space-separated integers arr[i][j].
Constraints--
-100<=a[i][j]<=100
Output Format--
Print the absolute difference between the sums of the matrix's two diagonals as a single integer.
Sample Input--
3
11 2 4
4 5 6
10 8 -12
Sample Output--
15
Explanation--
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
Note: |x| is the absolute value of x
'''
#code here
#!/bin/python3
import math
import os
import random
import re
import sys
def diagonalDifference(arr):
d1=0
d2=0
for i in range(len(arr)):
d1+=arr[i][i]
d2+=arr[i][len(arr)-i-1]
diff=d1-d2
if diff<0:
diff=-diff
return diff
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
| true |
fe4823dc892ad5572de3e7d942154de3d356824d | harshitbansal373/hackerrank-solutions | /problem solving/circular-array-rotation.py | 2,497 | 4.5625 | 5 | '''
problem:-
John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and shifts all remaining elements right one. To test Sherlock's abilities, Watson provides Sherlock with an array of integers. Sherlock is to perform the rotation operation a number of times then determine the value of the element at a given position.
For each array, perform a number of right circular rotations and return the value of the element at a given index.
For example, array a=[3,4,5], number of rotations, k=2 and indices to check, m=[1,2].
First we perform the two rotations:
[3,4,5] -> [5,3,4] -> [4,5,3]
Now return the values from the zero-based indices 1 and 2 as indicated in the m array.
a[1]=5
a[2]=3
Function Description:-
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices to report
Input Format:-
The first line contains 3 space-separated integers, n, k, and q, the number of elements in the integer array, the rotation count and the number of queries.
The second line contains n space-separated integers, where each integer i describes array element a[i].
Each of the q subsequent lines contains a single integer denoting m, the index of the element to return from a.
Output Format:-
For each query, print the value of the element at index m of the rotated array on a new line.
Sample Input 0:-
3 2 3
1 2 3
0
1
2
Sample Output 0:-
2
3
1
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the circularArrayRotation function below.
def circularArrayRotation(a, k, queries):
for i in range(k) :
a.insert(0,a.pop())
result=[]
for i in queries:
result.append(a[i])
return result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nkq = input().split()
n = int(nkq[0])
k = int(nkq[1])
q = int(nkq[2])
a = list(map(int, input().rstrip().split()))
queries = []
for _ in range(q):
queries_item = int(input())
queries.append(queries_item)
result = circularArrayRotation(a, k, queries)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
6d7ea971945a9f8b7d072c77e5eadd5f209d192c | harshitbansal373/hackerrank-solutions | /problem solving/picking-numbers.py | 1,686 | 4.3125 | 4 | '''
problem:-
Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1. For example, if your array is a=[1,1,2,2,4,4,5,5,5], you can create two subarrays meeting the criterion: [1,1,2,2] and [4,4,5,5,5]. The maximum length subarray has 5 elements.
Function Description:-
Complete the pickingNumbers function in the editor below. It should return an integer that represents the length of the longest array that can be created.
pickingNumbers has the following parameter(s):
a: an array of integers
Input Format:-
The first line contains a single integer , the size of the array .
The second line contains space-separated integers .
Output Format:-
A single integer denoting the maximum number of integers you can choose from the array such that the absolute difference between any two of the chosen integers is <=1.
Sample Input 0:-
6
4 6 5 3 3 1
Sample Output 0:-
3
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def pickingNumbers(a):
l=a
max=0
for i in a:
c=b=0
for j in range(len(l)):
if i-l[j]==1 or i-l[j]==0:
c+=1
for j in range(len(l)):
if i-l[j]==1 or i-l[j]==0:
b+=1
if max<c:
max=c
if max<b:
max=b
return max
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
result = pickingNumbers(a)
fptr.write(str(result) + '\n')
fptr.close()
| true |
08a28c58c4ea601b925c51d93a1617c7b33a63ec | SaiHoYip/Learning | /Python/LearningProjects/Calculator1.py | 353 | 4.375 | 4 | print("Hello and Welcome! This is a calculator that will do addition ")
# Note + = Addition - = Subtraction % = remainder * = multiplication / = division // = floor division ** exponent
# Note this calculator will only take whole numbers!
Num1 = int(input("Enter a Number: "))
Num2 = int(input("Enter a 2nd Number: "))
Result = Num1 + Num2
print(Result) | true |
1b08f7ba05ef912e38151b0502bf9e1ead2b33b0 | jadhavjay0253/python_playground | /Learning/ADV OOP/pr_02.py | 381 | 4.3125 | 4 | # CREATE A CLASS PETS FROM CLASS ANIMALS AND FURTHER CREATE ANIMALS
# AND FURTHER CREATE A CLASS DOG FROM PETS, ADD BARK METHOD TO CLASS DOG
class Animals:
am1 = "dog"
am2 = "horse"
class Pets(Animals):
r1 = "rainer"
class Dog(Pets):
@staticmethod
def bark():
print("Dog is barking from dog class.")
d = Dog()
print(d.am1)
d.bark() | true |
5494335b5bc31601a8af247aac71bd710b13a11e | jmaldon1/Python-Course | /classes.py | 1,082 | 4.21875 | 4 | import random
#Creates an object named Thief
class Thief:
#Has an Attribute of 'sneaky'
sneaky = True
#Python will run __init__ method automatically when class is called
#Lets us control how the Class is initialized(created)
#Kwargs are Key Word Arguments
def __init__(self, name, sneaky=True, **kwargs):
self.name = name
self.sneaky = sneaky
#Allows the user to input any key-value pairs they want
#Example: Thief("Josh", sneaky = False, scar = None, favorite_weapon = "wit")
for key, value in kwargs.items():
#Turns the each key-value pair into an attribute
setattr(self, key, value)
#Has a method(function inside a class) named pickpocket with the argument 'self'
#'self' is required as an argument in a method
def pickpocket(self):
#If sneaky is set to True, pickpocket method will choose a random number between 1 and 0
return self.sneaky and bool(random.randint(0,1))
#A method with an argument besides 'self'
def hide(self, light_level):
#will return True if sneaky = true AND light_level < 10
return self.sneaky and light_level < 10 | true |
13eb5ce49c41979a67cd543e7601d33c2b62236a | marinasugita/Practicals | /prac_10/2d_pyramid.py | 234 | 4.15625 | 4 | def count_number_of_blocks(n):
"""Calculate number of blocks needed, given the number of rows to make a 2D pyramid."""
if n <= 1:
return 1
return n + count_number_of_blocks(n - 1)
print(count_number_of_blocks(6)) | true |
7f2f36b8665f3c9800e51cc2a161f6afdede08e3 | benchng/python_onsite | /week_01/04_strings/05_mixcase.py | 440 | 4.40625 | 4 | '''
Write a script that takes a user inputted string
and prints it out in the following three formats.
- All letters capitalized.
- All letters lower case.
- All vowels lower case and all consonants upper case.
'''
first = "starbucks"
second = ""
#vowels = 'aeiou'
vowels = ['a','e','i','o','u']
for i in first:
if i in vowels:
second = second+i.lower()
else :
second = second+i.upper()
print (second) | true |
5069ddfc6934ec621f100d4360622ef1e599d7b2 | telnettech/Python | /WhileLoops.py | 1,408 | 4.28125 | 4 | # Problem 1: Warm the oven
# Write a while loop that checks to see if the oven
# is 350 degrees. If it is, print "The oven is ready!"
# If it's not, increase current_oven_temp by 25 and print
# out the current temperature.
current_oven_temp = 75
# Solution 1 here
while current_oven_temp < 350:
current_oven_temp += 25
print(current_oven_temp)
else:
print("The oven is ready")
# Problem 2: Total and average
# Complete the following function so that it asks for
# numbers from the user until they enter 'q' to quit.
# When they quit, print out the list of numbers,
# the sum and the average of all of the numbers.
def total_and_average():
numbers = []
# Solution 2 here
while True:
num = input("Give me a number, or 'q' to quit: ").lower()
if num == 'q':
break
try:
numbers.append(float(num))
except ValueError:
continue
print("You entered: ", numbers)
print("The total is:", sum(numbers))
print("The average is:", sum(numbers)/len(numbers))
total_and_average()
# Problem 3: Missbuzz
# Write a while loop that increments current by 1
# If the new number is divisible by 3, 5, or both,
# print out the number. Otherwise, skip it.
# Break out of the loop when current is equal to 101.
current = 1
# Solution 3 here
while current < 101:
if not current % 3 or current % 5 == 0:
print(current)
current += 1
| true |
5df5e1d4984f428280d63318ee5c52d90c51a3c4 | telnettech/Python | /ForLoops.py | 1,942 | 4.34375 | 4 |
# Columns: Name, Day/Month, Celebrates, Age
BIRTHDAYS = (
("James", "9/8", True, 9),
("Shawna", "12/6", True, 22),
("Amaya", "28/2", False, 8),
("Kamal", "29/4", True, 19),
("Sam", "16/7", False, 22),
("Xan", "14/3", False, 34),
)
# Problem 1: Celebrations
# Loop through all of the people in BIRTHDAYS
# If they celebrate their birthday, print out
# "Happy Birthday" and their name
print("Celebrations:")
# Solution 1 here
for person in BIRTHDAYS:
if person[2]:
print("Happy Birthday, {}".format(person[0]))
print("-"*20)
# Problem 2: Half birthdays
# Loop through all of the people in BIRTHDAYS
# Calculate their half birthday (six months later)
# Print out their name and half birthday
print("Half birthdays:")
# Solution 2 here
for person in BIRTHDAYS:
name = person[0]
birthdate = person[1].split('/')
birthdate[1] = int(birthdate[1]) + 6
if birthdate[1] > 12:
birthdate[1] = birthdate[1] - 12
birthdate[1] = str(birthdate[1])
print(name, "/".join(birthdate))
print("-"*20)
# Problem 3: Only school year birthdays
# Loop through the people in BIRTHDAYS
# If their birthday is between September (9)
# And June (6), print their name
print("School birthdays:")
# Solution 3 here
for person in BIRTHDAYS:
name = person[0]
birthdate = person[1].split('/')
birthdate[1] = int(birthdate[1])
if birthdate[1] in range(1, 7) or birthdate[1] in range(9, 13):
print(name)
print("-"*20)
# Problem 4: Wishing stars
# Loop through BIRTHDAYS
# If the person celebrates their birthday,
# AND their age is 10 or less,
# Print out their name and as many stars as their age
print("Stars:")
# Solution 4 here
for person in BIRTHDAYS:
name = person[0]
age = person[-1]
celebrates = person[-2]
if celebrates and age <= 10:
stars = ''
for star in range(age):
stars += '*'
print(name, stars)
print("-"*20)
| true |
f03ee8e4cd4e8adc0cf99273a95edb03809ec169 | IlungaNtita/codes | /Codes/Simple Calculator.py | 841 | 4.15625 | 4 | #A simple calculator
import math
def mul(x,y):
return x * y
def add(x,y):
return x + y
def sub(x,y):
return x - y
def dev(x,y):
return x / y
while True:
i=input("To calculate, type: \n+ for addition \n- for subbtraction \n* for multiplication \n/ for devision \nx to close: ")
try:
if i == "+":
print(int(add(int(input("Insert number:" )),int(input("Insert another number:" )))))
elif i == "-":
print(int(sub(int(input("Insert number:" )),int(input("Insert another number:" )))))
elif i == "*":
print(int(mul(int(input("Insert number:" )),int(input("Insert another number:" )))))
elif i == "/":
print(float(dev(float(input("Insert number:" )),float(input("Insert another number:" )))))
elif i == "x":
break
else:
print("Input error")
except :
print("Division by zero")
| false |
6bf4ab6b47d9befb9f5bb1c1bcbe1cac0a110d1c | PmXa/platzi_python | /comprehension_dictionaries.py | 507 | 4.25 | 4 | def run():
# Create a dictionary whose:
# - keys are of the first 100 natural numbers not divisible by 3
# - values are those same numbers cubed
my_dict = {}
for i in range (1, 101):
if i%3 != 0:
my_dict[i] = i**3
print("Classic method:")
print(my_dict, "\n")
# Do the same but using comprehension
comp_dict = {i: i**3 for i in range(1, 101) if i%3 != 0}
print("Comprehension method:")
print(comp_dict)
if __name__ == '__main__':
run() | true |
1488797d6a058ba83dd1e0949f9e6f6e915bb409 | aivan2798/Data-Structures-and-Algorithms | /02. Algorithms/02. Sorting/02. InsertionSort/insertionSort.py | 701 | 4.40625 | 4 | # creating a function for insertion
def insertion_sort(list1):
# Outer loop to traverse through 1 to len(list1)
for i in range(1, len(list1)):
value = list1[i]
# Move elements of list1[0..i-1], that are greater than value, to one position ahead of their current position
j = i - 1
while j >= 0 and value < list1[j]:
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
# Driver code to test above
list1 = [25,6,3,9,1,17]
print("The unsorted list is:", list1)
print("The sorted list1 is:", insertion_sort(list1))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.