blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a9f772545af1ba2fb1e4ca48c4b8ad390d600794 | laurieskelly/lrs-bin | /euler/euler_4.py | 1,078 | 4.25 | 4 | # A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 x 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
digits = 3
def largest_palindromic_product(ndigits):
largest = 10**ndigits - 1
if is_palindrome(largest**2):
return largest**2
f1 = largest - 1
largest_palindrome = 0
while f1 > 10**(ndigits-1):
# print 'New f1: ',f1
# for each integer (f2) from largest down to f1
for f2 in xrange(largest,f1,-1):
# print f1, f2, f1*f2
# check if f1 * f2 is a palindrome
if is_palindrome(f1*f2):
if f1 * f2 > largest_palindrome:
largest_palindrome = f1*f2
f1 -= 1
return largest_palindrome
def is_palindrome(n):
strn = str(n)
i = 0
while i <= len(strn)/2:
if strn[i] != strn[-(i+1)]:
return False
i += 1
return True
largest = largest_palindromic_product(digits)
print 'answer:', largest | true |
d3f0a250349a42802aa835e9683dd7fe51d3ac6e | trent-hodgins-01/ICS3U-Unit6-04-Python | /2d_average.py | 1,351 | 4.53125 | 5 | # !/user/bin/env python3
# Created by Trent Hodgins
# Created on 10/26/2021
# This is the 2D Average program
# The program asks the user how many rows and cloumns they want
# The program generates random numbers between 1-50 to fill the rows/columns
# The program then figures out and displays the average of all the numbers
import random
def sum_of_numbers(passed_in_2D_list):
# this function adds up all the elements in a 2D array
total = 0
for row_value in passed_in_2D_list:
for single_element in row_value:
total += single_element
return total
def main():
# this function uses a 2D array
a_2d_list = []
# input
rows = int(input("How many rows would you like: "))
columns = int(input("How many columns would you like: "))
print("")
for loop_counter_rows in range(0, rows):
temp_column = []
for loop_counter_columns in range(0, columns):
a_random_number = random.randint(0, 50)
temp_column.append(a_random_number)
print("{0} ".format(a_random_number), end="")
a_2d_list.append(temp_column)
print("")
divide = rows * columns
average = sum_of_numbers(a_2d_list) / divide
print("\nThe average of all the numbers is: {0} ".format(average))
print("\nDone")
if __name__ == "__main__":
main()
| true |
ea3b4a01637841a101b969124cfeb8dd08122ab4 | vallocke/zug-zug | /py_exercises/zellers_func.py | 1,340 | 4.3125 | 4 | # Name: Peter Kelt
# Date: 02-18-2013
def zellers(month, day, year):
'''zellers_func.py - Zeller's algorithm computes the day of the week on
which a given date will fall (or fell).
'''
days = {0 : 'Sunday',
1 : 'Monday',
2 : 'Tuesday',
3 : 'Wedsday',
4 : 'Thurdsay',
5 : 'Friday',
6 : 'Saturday',
}
months = {'Jan' : 1,
'Feb' : 2,
'Mar' : 3,
'Apr' : 4,
'May' : 5,
'Jun' : 6,
'Jul' : 7,
'Aug' : 8,
'Sep' : 9,
'Oct' : 10,
'Nov' : 11,
'Dec' : 12,
}
# Assign variables to standard Zeller's algorithm terms.
A = months[month]
B = day
# Format month so March = 1...February = 12, decriment year if Jan or Feb.
if A == 1 or A == 2:
A += 10
year -= 1
else:
A -= 2
C = year % 100
D = (year - C) / 100
W = (13 * A - 1) / 5
X = C / 4
Y = D / 4
Z = W + X + Y + B + C - 2*D
R = Z % 7
# Fix 'R' if negative.
if R < 0:
R += 7
print days[R]
zellers("Mar", 10, 1940)
zellers("Mar", 27, 1976)
zellers("Aug", 31, 1979)
| false |
c838693c51ae2847566c0e635f80f05db7a215c1 | Romny468/FHICT | /Course/3.2.1.9.py | 282 | 4.21875 | 4 |
word = input("enter a word: ")
while word != 0:
if word == "chupacabra":
print("You've successfully left the loop.")
break
else:
print("Ha! You're in a loop till you find the secret word")
word = input("\ntry again, enter another word: ") | true |
02d6002df846e2f11ee5a5e7345f9df1343db18e | Romny468/FHICT | /Course/3.2.1.6.py | 394 | 4.15625 | 4 | import time
# Write a for loop that counts to five.
# Body of the loop - print the loop iteration number and the word "Mississippi".
# Body of the loop - use: time.sleep(1)
# Write a print function with the final message.
for i in range(6):
print(i, "Mississippi")
time.sleep(1)
if i == 5:
print("Ready or not, here I come!")
i = 0
| true |
cf86dabe4955604b47ccc0b7e3881978291827f1 | JonathanGamaS/hackerrank-questions | /python/find_angle_mbc.py | 372 | 4.21875 | 4 | """
Point M is the midpoint of hypotenuse AC.
You are given the lengths AB and BC.
Your task is to find <MBC (angle 0°, as shown in the figure) in degrees.
"""
import math
def angle_finder():
AB = int(input())
BC = int(input())
MBC = math.degrees(math.atan(AB/BC))
answer = str(int(round(MBC)))+'°'
print(answer)
return answer
angle_finder() | true |
d0fb9d8752231bc0728a0572e1045eb7694af8c1 | JonathanGamaS/hackerrank-questions | /python/string_formatting.py | 462 | 4.15625 | 4 | """
Given an integer, N, print the following values for each integer I from 1 to N:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
"""
def print_formatted(number):
b = len(str(bin(number)[2:]))
for i in range(1,number+1):
print("{0}{1}{2}{3}".format(str(i).rjust(b),str(oct(i)[2:]).rjust(b+1),str(hex(i)[2:].upper()).rjust(b+1),str(bin(i)[2:]).rjust(b+1)))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
| true |
ec7ba04208c18b82e5f1b1924183b5a0c5ab2166 | ekeydar/python_kids | /lists/rand_list_ex.py | 637 | 4.125 | 4 | import random
def rand_list3():
"""
return list of 3 random items between 1 to 10 (include 1 and include 10)
"""
# write your code here
# verify that your function returns
# 3 numbers
# not all items of the list are the same always
# numbers are in 1,2,3,4,5,6,7,8,9,10
def main():
assert len(rand_list3()) == 3, 'list should be in size 3'
items = set()
for x in range(1000):
items |= set(rand_list3())
assert items == set(range(1, 11)), 'Probably something wrong with your call to random.randint'
print('Everything OK, well done!')
if __name__ == '__main__':
main()
| true |
69edca7bcdea35c28a3917d545dcbcab80e18661 | MugenZeta/PythonCoding | /BirthdayApp/Program.py | 1,260 | 4.4375 | 4 | #Birthday Program
import datetime
def printH():
User_Name = input("Hello. Welcome to the Birthday Tracker Application. Please enter your name: ")
def GetBirthDay():
#User Inputes Birthday
print()
DateY = input("Please put the year you where born [YYYY]: ")
DateM = input("Please put the year you where born [MM]: ")
DateD = input("Please put the year you where born [DD]: ")
#tranform string to int.
year = int(DateY)
month = int(DateM)
day = int(DateD)
bday = datetime.date(year,month,day)
return bday
#calculate days till birthday from today pass in 2 days
def CalDaysinDates(Original_Year,Target_Year):
This_Year = datetime.date(Target_Year.year,Original_Year.month, Original_Year.day)
dt = This_Year - Target_Year
return dt.days
def printBday(days):
if days > 0:
print("You have {} days until your birthday!".format(-days))
elif days < 0:
print("Your Birthday passed {} days ago!".format(days))
else:
print("Happy Birthday")
#Ties all functions together in execution oder
def main():
printH()
bday = GetBirthDay()
today = datetime.date.today()
Number_of_days = CalDaysinDates(bday, today)
printBday(Number_of_days)
main()
| true |
40a210b5eba4a886a5056ce573276175196e98b1 | anatulea/PythonDataStructures | /src/Stacks and Queues/01_balanced_check.py | 1,475 | 4.3125 | 4 | '''
Problem Statement
Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these, no spaces words or numbers. As a reminder, balanced parentheses require every opening parenthesis to be closed in the reverse order opened. For example ‘([])’ is balanced but ‘([)]’ is not.
You can assume the input string has no spaces.
'''
def balance_check(s):
if len(s)%2 != 0:
return False
opening = set('({[')
matches = ([ ('(',')'), ('[',']'), ('{','}')])
stack = []
for paren in s:
if paren in opening:
stack.append(paren)
else:
if len(stack) == 0:
return False
last_open = stack.pop()
if (last_open, paren) not in matches:
return False
return len(stack) == 0 # returns true if all mached
print(balance_check('[]'))
print(balance_check('[](){([[[]]])}'))
print(balance_check('()(){]}'))
def balance_check2(s):
chars = []
matches = {')':'(',']':'[','}':'{'}
for c in s:
if c in matches:
if chars.pop() != matches[c]:
return False
else:
chars.append(c)
return chars == []
print(balance_check2('[]'))
print(balance_check2('[](){([[[]]])}'))
print(balance_check2('()(){]}')) | true |
c07bef00e1f0ea19ca1f09e5de220f5e6ff2e3df | kuba777/sql | /cars7.py | 1,688 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Using the COUNT() function, calculate the total number of orders for each make and
# model.
# Output the car’s make and model on one line, the quantity on another line, and then
# the order count on the next line.
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("SELECT make, model FROM orders")
rows1 = c.fetchall()
#print type(rows)
make = []
model = []
for r in rows1:
make.append(r[0])
model.append(r[1])
a = list(set(model))
a.sort()
c.execute("SELECT DISTINCT orders.make, inventory.quantity, inventory.molde from orders, inventory WHERE inventory.molde = orders.model ORDER BY inventory.molde ASC")
row = c.fetchall()
#print row[1]
count = 0
#print a
for r in a:
c.execute("SELECT DISTINCT count(order_date) FROM orders WHERE model =" + "'" + r + "'" + "")
row2 = c.fetchone()
print "Make and model: ", row[count][0], row[count][2]
print "Qty: ", row[count][1]
print "# of orders: ", row2[0]
print
count = count + 1
# for r in list(set(model)):
# c.execute("SELECT count(order_date) FROM orders WHERE model = " + "'" + r + "'")
# row2 = c.fetchone()
# print "make and model: ", row[0], row[2]
# print "qty: ", row[1]
# print "order count: ", row2[0]
# print
# for r in list(set(make)):
# c.execute("SELECT count(order_date) FROM orders WHERE make = " + "'" + r + "'")
# results = c.fetchone()
# print r, results[0]
| true |
45f06e4bc2eb22ca904017fd6195d266643a0b21 | rprustagi/GALA-Fibonacci-Number-Programs | /chkprime.py | 395 | 4.15625 | 4 | #!/usr/bin/env python
# The programs to check if a given number is prime number.
import sys
def chkprime(param):
try:
num = int(param)
except:
return False
if num == 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
k = 3
while k * k <= num:
if num % k == 0:
return False
k = k + 2
return True
print(chkprime(sys.argv[1])) | false |
6839b8efe40a3a06f54ee81fc9a95a9ab18f189c | code613/functionalPHomework | /targilv3/t3q9.py | 1,521 | 4.15625 | 4 | #import targil3.t3q1
#from targil3 import t3q1
import targilv3.t3q1
import targilv3.t3q2 as q2
import targilv3.t3q3 as q3
import targilv3.t3q4 as q4
import targilv3.t3q5 as q5
import targilv3.t3q6 as q6
import targilv3.t3q7 as q7
import targilv3.t3q8 as q8
#dictionary menu and 1 whould be do targil3 question1
def main():
#hum maybe should put a while here while key or number is!= 0
num = 1
while num != 0:
print('''
enter a number to go to a specific question number in targil 3
0 to exit
targil 1 penta number function
targil 2 sum digits
targil 3 reverse num
targil 4 chech to see if a number is a Palindrome
targil 5 return sigma of i/(i+1) of the number given
targil 6 return approximation of pi through function to Nth correctness
targil 7 returns a dictionary prime numbers that are different only by 2
targil 8 returns a dictionary that is the merge of 3 dictionary's
and btw dear user this was your menu (in case you were wondering)
((you know i love you))
''')
#ok so need to se if there is a wy tpo just run the main there
#ok now need a dictionarry
targilDictionary = {1:targilv3.t3q1,
2:q3,3:q3,4:q4,5:q5,6:q6,7:q7,8:q8}
num = input("please enter yor number here: ")
if num != 0:
targilDictionary[int(num)].main()
'''
n = 10
print( reverseNum(n))
'''
if __name__ == "__main__":
main()
| false |
32b1cd767e5e882c04f93c41dd90af8830e3adb1 | Artexxx/Artem-python | /algorithms/Project_Euler/046 - Goldbachs other conjecture/sol1.py | 2,386 | 4.1875 | 4 | """
Кристиан Гольдбах показал, что любое нечетное составное число можно записать в виде суммы простого числа и удвоенного квадрата.
Оказалось, что данная гипотеза неверна.
9 = 7 + 2×(1)^2
15 = 7 + 2×(2)^2
21 = 3 + 2×(3)^2
25 = 7 + 2×(3)^2
27 = 19 + 2×(2)^2
33 = 31 + 2×(1)^2
Каково наименьшее нечетное составное число, которое нельзя записать в виде суммы простого числа и удвоенного квадрата?
[#] Можно смотреть только нечётные числа.
Время Замедление Число Результат
--------- ------------ ------- -----------
0.0052454 0.525% 1 5777 (Ответ)
0.0001999 -0.505% 5777 5993
"""
import itertools
import math
from functools import lru_cache
@lru_cache(maxsize=None)
def is_prime(n: int) -> bool:
"""
Determines if the natural number n is prime.
>>> is_prime(10)
False
>>> is_prime(11)
True
"""
# simple test for small n: 2 and 3 are prime, but 1 is not
if n <= 3:
return n > 1
# check if multiple of 2 or 3
if n % 2 == 0 or n % 3 == 0:
return False
# search for subsequent prime factors around multiples of 6
max_factor = int(math.sqrt(n))
for i in range(5, max_factor + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
def is_goldbach(n):
if n % 2 == 0 or is_prime(n):
return True
for i in itertools.count(1):
k = n - 2 * i * i
if k <= 0:
return False
elif is_prime(k):
return True
def solution(start=1):
"""
Находит следующее нечетное составное число, которое нельзя записать в виде суммы простого числа и удвоенного квадрата
"""
for n in itertools.count(start=start, step=2):
if not is_goldbach(n):
return n
if __name__ == '__main__':
### Run Time-Profile Table ###
import sys; sys.path.append('..')
from time_profile import TimeProfile
TimeProfile(solution, [3, 5779], DynamicTimer=True)
| false |
b3b0b107f3cf64ee98def0a5e6d02614eedd0dcd | Artexxx/Artem-python | /algorithms/Project_Euler/015 - Lattice Path/sol-best.py | 1,045 | 4.4375 | 4 | """
Начиная в левом верхнем углу сетки 2×2 и имея возможность двигаться только вниз или вправо,
существует ровно 6 маршрутов до правого нижнего угла сетки.
Сколько существует таких маршрутов в сетке размером gridSize?
"""
import math
def binomial(n, k):
assert 0 <= k <= n
return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))
def solution(gridSize):
"""
Возвращает количество путей, возможных в сетке n x n, начиная с верхнего левого угла,
переходя в нижний правый угол и имея возможность двигаться только вправо и вниз.
>>> solution(20)
137846528820
>>> solution(1)
2
"""
return binomial(gridSize*2, gridSize)
if __name__ == "__main__":
print(solution(int(input()))) | false |
951a0efb9e825ea81dd0ca7c7cb275a01494a422 | Artexxx/Artem-python | /algorithms/Project_Euler/018 - Maximum Path Sum I/sol1.py | 2,866 | 4.3125 | 4 | """
Начиная в вершине треугольника (см. пример ниже) и перемещаясь вниз на смежные числа, максимальная сумма до основания составляет 23.
3
7 4
2 4 6
8 5 9 3
То есть, 3 + 7 + 4 + 9 = 23
Найдите максимальную сумму пути от вершины до основания следующего треугольника:
"""
def num_to_array(triangle):
"""
Идея:
3 становится [3], 7 становится [7]. Это немного облегчает суммирование чисел через строки треугольника,
так как больше нет необходимости проверять, описывает ли предыдущая строка массив или целое число.
"""
res = triangle.copy()
for i in range(len(triangle)):
for j, num in enumerate(triangle[i]):
if num: res[i][j] = [num]
return res
# Для каждого числа в `array` прибавляет `current_value`
current_sum = lambda array, current_value: [num + current_value for num in array]
def solution(triangle):
"""Находит максимальную сумму в треугольнике, как описано в постановке задачи выше.
>>> solution(triangle)
1074
"""
result_sum = num_to_array(triangle)
for i in range(1, len(triangle)):
for j in range(len(triangle[i])):
current = result_sum[i][j]
if (current):
north_west = result_sum[i - 1][j - 1]
north_east = result_sum[i - 1][j]
result_sum[i][j] = []
current_value = current[0]
if (north_west):
result_sum[i][j] = [*result_sum[i][j], *current_sum(north_west, current_value)]
if (north_east):
result_sum[i][j] = [*result_sum[i][j], *current_sum(north_east, current_value)]
flatten_result_sum = []
for arr in result_sum[-1]:
flatten_result_sum.extend(arr)
return max(flatten_result_sum)
if __name__ == '__main__':
# testTriangle = \
# [[3, 0, 0, 0],
# [7, 4, 0, 0],
# [2, 4, 6, 0],
# [8, 5, 9, 3]]
# assert maximumPathSumI(testTriangle) == 23
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle, "r") as f: triangle = f.readlines()
raw_triangle = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle] # read row triangle
triangle_with_zeros = [x + [0] * (len(raw_triangle[-1]) - len(x)) for x in raw_triangle] # add zeros
print(solution(triangle_with_zeros))
| false |
16e12a8c252bc7e83eebe5e13864b871cc9451d7 | taylorhcarroll/PythonIntro | /debug.py | 901 | 4.15625 | 4 | import random
msg = "Hello Worldf"
# practice writing if else
# if msg == "Hello World":
# print(msg)
# else:
# print("I don't know the message")
# # I made a function
# def friendlyMsg(name):
# return f'Hello, {name}! Have a great day!'
# print(friendlyMsg("james").upper())
# print(friendlyMsg("clayton"))
# accepting user input
print("What's your name")
name = str(input())
# Random Number Guessing Game
rand = random.randint(1, 10)
print(f"Alright {name}, Guess a number between 1 and 10")
x = 0
while x < 3:
numberGuessed = int(input())
if numberGuessed == rand:
print(f"YOU GOT IT. THE NUMBAH WAS {rand}")
break
elif numberGuessed < rand:
print(f"Guess a higher number than {numberGuessed}")
x += 1
elif numberGuessed > rand:
print(f"guess a lower number {numberGuessed}")
x += 1
if x == 3:
print("You've lost!")
| true |
df249f359269c4357e81b95506316c4481928da6 | mani67484/FunWithPython | /calculate_taxi_fare_2.py | 2,437 | 4.40625 | 4 | """
After a lengthy meeting, the company's director decided to order a taxi to take the staff home. He ordered N cars
exactly as many employees as he had. However, when taxi drivers arrived,
it turned out that each taxi driver has a different fare for
1 kilometer.The director knows the distance from work to home for each employee (unfortunately,
all employees live in different directions, so it is impossible to send two employees in one car).
Now the director wants to select a taxi for each employee.
Obviously, the director wants to pay as little as possible.
Input format: The first line contains N numbers through a space
specifying distances in kilometers from work to the homes of employees.
The second line contains N fares for one kilometer in a taxi.
All distances are unique and all rates are unique too.
Output format: Give taxi cars integer indexes starting from zero.
For each employee print the index of the taxi they should choose.
Note: Loops, iterations, and list comprehensions are forbidden in this task.
------------------------
Input data:
10 20 30
50 20 30
Program output:
0 2 1
------------------------
Input data:
10 20 1 30 35
1 3 5 2 4
Program output:
4 1 2 3 0
"""
def calculate_original_index_of_taxi_fare():
result_index_list = list(map(get_original_index, list_of_employees_total_home_distance_in_km))
print(*result_index_list, sep=" ")
def get_original_index(employees_total_home_distance_in_km):
return list_of_tax_fare_per_km.index(zipped_dictionary[employees_total_home_distance_in_km])
def collect_data():
global sorted_list_of_employees_total_home_distance_in_km, \
sorted_list_of_taxi_fares_per_km, \
list_of_tax_fare_per_km,\
list_of_employees_total_home_distance_in_km,\
zipped_dictionary
user_input1 = input()
user_input2 = input()
list_of_employees_total_home_distance_in_km = list(map(int, user_input1.split()))
sorted_list_of_employees_total_home_distance_in_km = sorted(list_of_employees_total_home_distance_in_km,
reverse=True)
list_of_tax_fare_per_km = list(map(int, user_input2.split()))
sorted_list_of_taxi_fares_per_km = sorted(list_of_tax_fare_per_km)
zipped_dictionary = dict(zip(sorted_list_of_employees_total_home_distance_in_km, sorted_list_of_taxi_fares_per_km))
calculate_original_index_of_taxi_fare()
collect_data()
| true |
d8445e9f19318af7b9afc98acde565443f2e7713 | SindriTh/DataStructures | /PA2/my_linked_list.py | 2,601 | 4.21875 | 4 | class Node():
def __init__(self,data = None,next = None):
self.data = data
self.next = next # Would it not be better to call it something other than next, which is an inbuilt function?
class LinkedList:
def __init__(self):
self._head = None
self._tail = None
self._size = 0
# O(1)
def push_back(self, data):
''' Appends the data to the linked list '''
new_node = Node(data)
if self._size == 0:
self._head = new_node
self._tail = new_node
else:
self._tail.next = new_node
self._tail = self._tail.next
self._size +=1
return
# O(1)
def push_front(self,data):
''' Prepends the data to the linked list '''
new_node = Node(data,self._head)
self._head = new_node
if self._size == 0:
self._tail = self._head
self._size += 1
# O(1)
def get_size(self):
''' Returns the size of the linked list '''
return self._size
# O(1)
def pop_front(self):
''' Removes the first node of the linked list and returns it '''
if self._head == None:
return
node = self._head
self._head = self._head.next
self._size -= 1
return node.data
# O(n)
def pop_back(self):
''' Removes the last node of the linked list and returns it '''
returnnode = self._tail
if self._tail == self._head:
self._head, self._tail = None,None
else:
node = self._head
while node.next != self._tail:
node = node.next
node.next = None
self._tail = node
self._size -=1
return returnnode.data
# O(n)
def __str__(self):
''' Handles printing of the linked list '''
node = self._head
returnstring = ""
while node != None:
returnstring += str(node.data) + " "
node = node.next
return returnstring[:-1]
if __name__ == "__main__":
listi = LinkedList()
listi.push_back("1")
listi.push_back("2")
listi.push_front("0")
listi.push_back("3")
listi.push_back("4")
print(listi)
print(f"oh boi I popped one! {listi.pop_front()}")
print(listi)
print(f"Popped one from the back {listi.pop_back()}")
print(listi)
print(f"Popped one from the back {listi.pop_back()}")
print(f"Popped one from the back {listi.pop_back()}")
print(f"Popped one from the back {listi.pop_back()}")
print(listi) | true |
c3b0de9516118a12593fdb1c33288105f5720caf | Heena3093/Python-Assignment | /Assignment 1/Assignment1_7.py | 558 | 4.25 | 4 | #7.Write a program which contains one function that accept one number from user and returns true if number is divisible by 5 otherwise return false.
#Input : 8 Output : False
#Input : 25 Output : True
def DivBy5(value):
if value % 5 == 0:
return True
else:
return False
def main():
print ("Enter number ")
no=int(input())
ret=DivBy5(no)
if no % 5 == 0:
print("Number is divisible by 5")
else:
print("Number is not divisible by 5 ")
if __name__=="__main__":
main() | true |
f7cbd0159a129526f623685f9edb077d805eefd3 | Heena3093/Python-Assignment | /Assignment 3/Assignment3_4.py | 836 | 4.125 | 4 | #4.Write a program which accept N numbers from user and store it into List. Accept one another number from user and return frequency of that number from List.
#Input : Number of elements : 11
#Input Elements : 13 5 45 7 4 56 5 34 2 5 65
#Element to search : 5
#Output : 3
def DisplayCount(LIST,x):
cnt = 0
for i in range(len(LIST)):
if LIST[i]==x:
cnt=cnt+1
return cnt
def main():
arr=[]
print("Enter the number of elements:")
size=int(input())
for i in range(size):
print("The elemnts are :",i+1)
no=int(input())
arr.append(no)
print("Display the Elements are:",arr)
print("Elemnt to the search")
no=int(input())
ret=DisplayCount(arr,no)
print("Number of count is :",ret)
if __name__=="__main__":
main() | true |
4169416e5ec1e1bb647482465fd55ab7119a88b0 | Heena3093/Python-Assignment | /Assignment 1/Assignment1_9.py | 308 | 4.34375 | 4 | #9. Write a program which display first 10 even numbers on screen.
#Output : 2 4 6 8 10 12 14 16 18 20
def DisplayW():
print("Display First 10 even number")
i=0
while(i<20):
i=i+2
print(i)
def main():
DisplayW()
if __name__=="__main__":
main() | false |
e11d7e50b4adf445696bea2e2bbd2623c89e3af9 | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Digits of a number.py | 1,664 | 4.25 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To analyze positive integers and present their characteristics.
#------------------------------------------------------------------------------#
again = "Y"
while again == "y" or again == "Y":
number = int(input("Please enter a positive integer: "))
while number <= 0:
number = int(input("Please re-enter a positive, non-zero, number: "))
count = 0
breakdown = number
leftover = 0
reverse = 0
Sum = 0
digitalroot = 0
maximum = 0
while breakdown != 0:
leftover = breakdown % 10
reverse = reverse * 10 + leftover
Sum = Sum + leftover
breakdown = breakdown // 10
count = count + 1
digitalroot = Sum
leftover = 0
for maximum in range(1, 21):
while digitalroot != 0:
leftover = leftover + (digitalroot % 10)
digitalroot = digitalroot // 10
digitalroot = leftover
leftover = 0
if digitalroot >= 0 and digitalroot <= 9:
maximum = 21
print("Your number has",count,"digits.")
print("The sum of these digits is",Sum,".")
print("The reverse of this number is",reverse,".")
print("The digital root of this number is",digitalroot,".")
if reverse == number:
print("This number also happens to be a palindrome!")
again = input("Would you like to analyse another number? (Y/N) ")
while not(again == "Y" or again == "N" or again == "y" or again == "n"):
again = input("Please enter if you would like to analyse another number. (Y/N) ")
print()
print()
print("Have a nice day!")
| true |
bdb7d0ff8b7c439147fc677ac68a71ec851d2f2c | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Parking Garage.py | 2,142 | 4.15625 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To create a program that will calculate the cost of parking
# at a parking garage.
#------------------------------------------------------------------------------#
again = "Y"
while again == "Y" or again == "y":
minutes = int(input("Please enter the amount of minutes you have parked for: "))
while minutes <= 0:
minutes = int(input("Please re-enter the amount of minutes you have parked for: "))
timeEntered = int(input("Now, please enter the time you have entered , in 24 hour format. (HHMM): "))
while timeEntered <= 0 or timeEntered > 2359 or timeEntered % 100 > 59:
timeEntered = int(input("Please enter a valid time you have entered at, in 24 hour format. (HHMM): "))
parkingPass = str(input("Finally, do you have a staff parking pass? (Y/N) "))
while not(parkingPass == "Y" or parkingPass == "N" or parkingPass == "y" or parkingPass == "n"):
parkingPass = str(input("Please re-enter if you have a parking pass or not. (Y/N) "))\
minutesEntered = (timeEntered // 100) * 60 + (timeEntered % 100)
price = 0
finalTime = minutesEntered + minutes
if finalTime >= 1080:
if minutesEntered > 1080:
price = 5
elif (1080 - minutesEntered) % 20 > 0:
price = ((((1080 - minutesEntered) // 20) + 1) * 3) + 5
else:
price = (((1080 - minutesEntered) // 20) * 3) + 5
elif minutes % 20 > 0:
price = ((minutes // 20) + 1) * 3
else:
price = (minutes // 20) * 3
if price > 28:
price = 28
if parkingPass == "Y" or parkingPass == "y":
if price > 8.5:
price = 8.5
print(" ")
print(" ")
print("The total cost of your parking visit is $%.2f" %price)
print(" ")
print(" ")
again = input("Would you like to calculate another time? (Y/N): ")
while not(again == "Y" or again == "N" or again == "y" or again == "n"):
again = input("Please re-enter if you want to calculate again. (Y/N): ")
print(" ")
print(" ")
print("Have a nice day!")
| true |
3fd8156ce49e6066d7a5ee72e892bb2f3b15ef33 | alejandroruizgtz/progAvanzada | /ejercicio34.py | 352 | 4.1875 | 4 | # Escriba un programa que lea un numero entero introduciendo pot el usuario.Su programa debe desplegar un mensaje indicando si su numero entero es par o inpar.
entero = float(int(input('Inserte un numero entero:')))
a = (entero / 2)
b = (entero % 2)
if b <= 0.0:
print('Es un numero par')
elif b >= 1:
print('Es un numero impar')
| false |
46e385c7eaf8fbf47187f5aca31e877c366907d7 | alejandroruizgtz/progAvanzada | /ejemplo3.py | 747 | 4.28125 | 4 | #ciclo while
#La ejcucion de esta estructura de control while es la siguiente:
#Python evalua la condicion:
#si el resultado es true, falso, se ejecuta el cuerpo del bucle
#o del ciclo. Una vez ejecutado el cuerpo del bucle, se repite
#elproceso (se evalua de nuevo la condicion y si es cierta se
#ejecuta de nuevo el cuerpo del bucle) una y otra vez mientras
#la condicion sea cierta.
#si el resultado es false el cuerpo del bucle no se ejecuta y
#continua la ejecucion del resto del programa.
### con ctrol+c se rompe el programa
# while es mientras
#ejercicio: Hacer un programa que escriba los numeros del 1 al
#10
i = 1
while i <= 10:
print(i)
i = i + 1
print('fin del programa')
| false |
6dbd416dfcc76c593dadb4da44e5c0b4f8606061 | alejandroruizgtz/progAvanzada | /ejemplo.py | 694 | 4.125 | 4 | # El comando printp imprime un mensaje en la pantalla o en otro dispocitivo de salida. El mensaje puede ser una cadena de caracteres o cualquier objeto que sea convertible a cadena de caracteres
# El comando input permite al usuario introducir informacion utilizando el teclado. La variable donde se guarda dicha informacion es de tipo string o cadena de caracteres.
# El comando int convierte cualquier dato al tipo entero.
# El comando float convierte cualquier dayto al tipo decimal.
Nombre= input('Inserta tu nombre:')
edad= int(input('Inserta tu eded:'))
estatura= float(input('Inserta tu estarura'))
print('Mi nombre es', Nombre,'y naci en',2019-edad, 'y mido', estatura)
| false |
cc5f99671f9f2101ff298e05a41af8c0568aefeb | alejandroruizgtz/progAvanzada | /ejercicio46.py | 519 | 4.125 | 4 | mes = input('Introduzca mes:')
dia = float(int(input('Introduzca dia:')))
if mes == 'enero' or mes =='febrero' or mes == 'marzo' or dia >= 20 or dia <=21:
print('Primavera')
elif mes == 'abril' or mes == 'mayo' or mes == 'junio' and dia >= 21 or dia <=20:
print('verano')
elif mes == 'julio' or mes =='agosto' or mes == 'septiembre' and dia >= 22 or dia <=21:
print('otolo')
elif mes == 'octubre' or mes =='noviembre' or mes == 'diciembre' and dia >= 21 or dia <=20:
print('invierno')
| false |
3a9bfeb8bf331298b613dc10f85cadd41199e5fb | 1sdc0d3r/code_practice | /leetcode/Python/backspace_compare.py | 968 | 4.15625 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# Note that after backspacing an empty text, the text will continue empty.
def backSpaceCompare(S, T):
def back(x):
newString = list()
for l in x:
if l is not "#":
newString.append(l)
elif l is "#" and len(newString) > 0:
newString.pop()
return "".join(newString)
if back(S) == back(T):
return True
return False
s1 = "ab#c"
t1 = "ad#c"
s2 = "ab##"
t2 = "c#d#"
s3 = "a##c"
t3 = "#a#c"
s4 = "a#c"
t4 = "b"
s5 = "y#fo##f"
t5 = "y#f#o##f"
s6 = "hd#dp#czsp#####"
t6 = "hd#dp#czsp#######"
print(backSpaceCompare(s1, t1)) # True
# print(backSpaceCompare(s2, t2)) # True
# print(backSpaceCompare(s3, t3)) # True
# print(backSpaceCompare(s4, t4)) # False
# print(backSpaceCompare(s5, t5)) # True
# print(backSpaceCompare(s6, t6)) # True
| true |
889195f0a205ab24f651a68ae067d356518c4eef | wellesleygwc/2016 | /mf/Sign-in-and-Add-user/app/db.py | 1,406 | 4.15625 | 4 | import sqlite3
database_file = "static/example.db"
def create_db():
# All your initialization code
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Create a table and add a record to it
cursor.execute("create table if not exists users(username text primary key not null, password text not null)")
cursor.execute("insert or ignore into users values ('Meghan', 'Flack')")
# Save (commit) the changes
connection.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
connection.close()
def check_password(username, password):
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Try to retrieve a record from the users table that matches the usename and password
cursor.execute("select * from users where username='%s' and password='%s'" % (username, password))
rows = cursor.fetchall()
connection.close()
return len(rows) > 0
def create_user(username, password):
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Try to retrieve a record from the users table that matches the usename and password
cursor.execute("insert or ignore into users values ('%s', '%s')" % (username, password))
connection.commit()
connection.close()
| true |
b9b89f34dc087eb641cda31afde4da5022d41968 | RakeshNain/TF-IDF | /TF-IDF/task4_30750008.py | 591 | 4.1875 | 4 | """
This function is finding most suitable document for a given term(word)
"""
import pandas as pd
def choice(term, documents):
# finding IDF of given term(word)
idf = documents.get_IDF(term)
# creating a new DataFrame of the term which contain TF-IDF instead of frequencies
tf_idf_df = documents.data[term]*idf
# finding the maximum value is the new Data Frame
max_v = tf_idf_df.max()
# finding the row name(book name) corresponding to the highest value
book_choice = tf_idf_df[tf_idf_df == max_v].index[0]
return book_choice
| true |
669d633b331c32363512ee50b23e414edece7277 | ElliottKasoar/algorithms | /bubblesort.py | 1,259 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 17:48:06 2020
@author: Elliott
"""
# Bubble sort algorithm
import numpy as np
import time
# Bubble sort function.
# Compares adjacent pairs of elements and swaps if first element is larger
# Repeats this (length of array - 1) times, each time one fewer element must be
# considered.
def bubble_sort(arr):
length = len(arr)
for i in range(length - 1):
for j in range(length - i - 1):
if (arr[j] > arr[j+1]):
temp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = temp
# print(arr)
# Main
def main():
ol = np.linspace(1,1000,1000) #Ordered list to compare with at end.
ul = ol.copy() #Copy else just renames ol as ul and will still be shuffled
np.random.shuffle(ul) #Shuffle to create unodered list
# print("ol: ", ol)
# print("ul: ", ul)
#Run main code
t1= time.time()
bubble_sort(ul)
t2= time.time()
dt = t2 - t1
# print("Final list: ", ul)
if (np.array_equal(ol, ul)):
print("Sorted!")
print("Time taken = ", dt)
else:
print("Not sorted.")
#Run code
main() | true |
34fbf47b698571fbe50d3fa41a948662bb64cf86 | Juliakm1997/Juliakm | /17-02_Classes/15-3-Classes2.py | 831 | 4.25 | 4 | # ----- Classes -----
# Metodo construtor
class Calculadora:
n1 = 0
n2 = 0
resultado = 0
# Criação de um método construtor, com parêmetros
def __init__(self, numero1, numero2):
self.n1 = numero1
self.n2 = numero2
# método soma utiliza as variáveis da classe n1 e n2 para realizar a soma
# o resultado da soma é armazenado na variável da classe 'resultado'
def soma(self):
self.resultado = self.n1 + self.n2
# Instanciando um objeto da classe Calculadora passando dois argumentos
# Os dois argumentos passados durante o instancimendo, são passados para o metodo init(Construtor)
calc = Calculadora(10, 20)
# Chamada do método 'soma' da classe 'Calculadora'
calc.soma()
# impressao do valor da variável 'resultado' da classe 'Calculadora'
print(calc.resultado)
| false |
ed5d38d2198adbf41ddf168c1137de333503f7ea | bwprescott/2015-Assignments-and-Projects | /c124multiplication_blakeprescott.py | 885 | 4.1875 | 4 | #!/usr/bin/python3
""" Args: 2 arrays of n bits """
def binary_multiplication(a_arr, b_arr):
print('a_arr={} b_arr={}'.format(a_arr, b_arr))
a = binary2decimal(a_arr)
print(a)
b_arr = list(reversed(b_arr))
c = [0]*len(b_arr)
product = 0
for j in range(0, len(b_arr)):
if b_arr[j] == 1:
c[j] = a * (2 ** j)
else:
c[j] = 0
product += c[j]
return product
"""return decimal value of an array of n bits"""
def binary2decimal(a):
s = 0
for j in range(0,len(a)):
s = (s*2) + a[j]
return s
print(binary_multiplication([0,1,0,1],[1,1,1,0]))
| false |
1d2ace87d805ecaa811e860f29f163a26c85c429 | padmacho/pythontutorial | /collections/dict/dict_demo.py | 1,585 | 4.6875 | 5 | capitals = {"india":"delhi", "america":"washington"}
print("Access values using key: ", capitals["india"])
name_age = [('dora', 5), ('mario', 10)]
d = dict(name_age)
print("Dict", d)
d = dict(a=1, b=2, c=3)
print("Dict", d)
# copying method 1
e = d.copy()
print("Copied dictionary e: ", e)
# copying method 2
f = dict(d)
print("Copied dictionary f: ", f)
# updating dict
g = dict(a=-1, b=-2)
print("d", d)
print("g", g)
d.update(g)
print("Updated dictionary d with g", d)
# Iterating through dictionary
d = dict(a=1, b=2, c=3)
# Note key are retrieved in arbitrary order
for key in d:
print(d[key])
# iterate through values
# There is no efficient way to get keys from values
print("Get values for dictionary with out keys")
for value in d.values():
print(value)
print("Get items for dictionary")
# Each key-value pair in a dictionary is called an item, and we can get ahold of an iterable view of the items using the items() dictionary method.
for key, value in d.items():
print(key, value)
# member ship operator works only on keys
d = dict(a=1, b=2, c=3)
print("a" in d)
print("e" in d)
# Remove an item from the dictionary
d = dict(a=1, b=2, c=3)
print("d", d)
print("Removing item c from dictionary")
del d['c']
print(d)
# Keys are immutable and values can be modified
d = dict(a=1, b=2, c=3)
print("d", d)
print("Modify element value of item a")
d["a"] = -1
print("d", d)
# Pretty printing
print("Pretty printing")
from pprint import pprint as pp
d = dict(a=1, b=2, c=3)
pp(d)
| true |
679d78cde339c2ab96b05a34b983f9530404d4fa | padmacho/pythontutorial | /scopes/assignment_operator.py | 311 | 4.15625 | 4 | a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
| true |
25b4cc8f5f2f989e126dc684386245f8ab25e16a | qilaidi/leetcode_problems | /leetcode/155MinStack.py | 1,488 | 4.21875 | 4 | class MinStack1:
"""
1。 直接用列表 (leetcode已提交, 这种耗时较高主要是因为没有存最小值)
2。 用链表 (leetcode已提交)
3。 用tuple列表
"""
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
if self.stack == []:
self.stack.append((x, x))
else:
self.stack.append((x, min(x, self.stack[-1][1])))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
return self.stack[-1][1]
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = []
def push(self, x: int) -> None:
if not self.min:
self.min.append(x)
elif self.min[-1] >= x:
self.min.append(x)
self.stack.append(x)
def pop(self) -> None:
x = self.stack.pop()
if x == self.min[-1]:
self.min.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min[-1]
# Your MinStack object will be instantiated and called as such:
if __name__ == '__main__':
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())
| false |
e14df3b6a6de916386a171b5095f282f2a2885be | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /23. Python File IO Basics.py | 755 | 4.28125 | 4 | ########### Python File IO Basics #########
# Two types of memory
# 1. Volatile Memory : Data cleared as System Shut Down
# Example : RAM
# 2. Non-Volatile Memory : Data remains saved always.
# Example : Hard Disk
# File : In Non-Volatile Memory we store Data as File
# File may be text file,binary file(Ex - Image,mp3),etc.
# Different Modes of Opening files in Python
"""
"r" - Open file for reading - Default mode
"w" - Open a file for writing
"x" - Create file if not exists
"a" - Add more content to a file/ append at end in file
"t" - open file in text mode - Default mode
"b" - open file in binary mode
"+" - for update (read and write both)
"""
# Question of the tutorial:
# How to print docstring of func1()
# Answer : print(func1.__doc__) | true |
9892c365ccbe67416408836343251224372f854f | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /15. While Loops In Python.py | 506 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# Assuming code inside for and while loop is same
# Both While and for loop takes almost equal time
# As both converted into same machine code
# So you can use any thing which is convenient | true |
658bf19caa15b39086e4166c6bd43b8f026939e4 | evlevel/lab_6_starting_repo | /lab_6_starting/wordstats.py | 794 | 4.28125 | 4 | #
# wordstats.py:
#
# Starting code for Lab 6-4
#
# we'll learn more about reading from text files in HTT11...
FILENAME = 'words.txt'
fvar = open(FILENAME, 'r') # open file for reading
bigline = fvar.read() # read ENTIRE file into single string
# what happens when you print such a big line?
# try it, by uncommenting next line
# print (bigline)
# the following print illustrates the printf-formatting approach in Python
# # this is the "old way", and not discussed in our book...
# [L6-4a] total number of characters, including newlines
print("Number of characters is: %d" % len(bigline))
# [L6-4b] total number of words in the file
# hint: each word ends with a newline
# [L6-4c] average length of a word
# [L6-4d] count of 'e' in all words
# [L6-4e]
fvar.close()
| true |
015b5f6887cc692ae30fdef44d1fa87e8b74ae6b | toma-ungureanu/FII-Python | /lab1/ex1.py | 1,142 | 4.3125 | 4 | class Error(Exception):
"""Exception"""
pass
class NegativeValueError(Error):
"""Raised when the input value is negative"""
pass
class FloatError(Error):
"""Raised when the input value is negative"""
pass
def find_gcd_2numbers(num1, num2):
try:
if num1 < 0 or num2 < 0:
raise NegativeValueError
if isinstance(num1, float) or isinstance(num2, float):
raise FloatError
while num2:
num1, num2 = num2, num1 % num2
return num1
except (NegativeValueError, FloatError):
print("You didn't enter a positive integer")
def main():
numbers = []
while True:
try:
num = int(input("Enter an integer: "))
numbers.append(num)
except ValueError:
break
if len(numbers) < 2:
print("Please enter more values")
return 1
print(numbers)
main_num1 = numbers[0]
main_num2 = numbers[1]
gcd = find_gcd_2numbers(main_num1, main_num2)
for i in range(2, len(numbers)):
gcd = find_gcd_2numbers(gcd, numbers[i])
print(gcd)
return 0
main()
| true |
dc276b879b3045f27a3ae01b0984e82cf831f970 | toma-ungureanu/FII-Python | /lab5/ex5.py | 816 | 4.1875 | 4 | import os
def writePaths(dirname,filename):
file_to_write = open(filename, "w+", encoding='utf-8')
for root, dirs, files in os.walk(dirname):
path = root.split(os.sep)
file_to_write.write((len(path) - 1) * '---')
file_to_write.write(os.path.basename(root))
file_to_write.write("\n")
for file in files:
file_to_write.write(len(path) * '---')
file_to_write.write(os.path.basename(file))
file_to_write.write("\n")
def main():
try:
path = input(" Enter the desired path: ")
file_to_write_in = input(" Enter the file you want to write in: ")
if not os.path.isdir(path):
raise OSError
writePaths(path, file_to_write_in)
except OSError:
print(" Enter a directory!")
main()
| true |
f7fba7853ba6cd086384d43014fae831e5597215 | Dhruvish09/PYTHON_TUT | /Loops/function with argument.py | 1,111 | 4.5 | 4 | #Information can be passed into functions as arguments.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
#You can also send arguments with the key = value syntax.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
#If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
#You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
#To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
| true |
8af2a7bee92cdbddf41e63bc1cc143b3da929b93 | Dhruvish09/PYTHON_TUT | /Operators/Comparison Operator/ALL IN ONE.py | 273 | 4.28125 | 4 | # Examples of Comparion Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
| false |
bde78bbe09e2ba11f43555b4fce453392628e4f7 | RavikrianGoru/py_durga | /telsuko_one/py_samples/poly_method_overloading_37.py | 1,319 | 4.21875 | 4 | class Nums:
def __init__(self,m=0):
self.m=m
#def sum(self, m1,m2):
# return m1+m2
#def sum(self,m1,m2, m3):
# return m1+m2+m3
#method overloading trick
def sum(self, m1=None, m2=None, m3=None):
if m1!=None and m2!=None and m3!=None:
return m1+m2+m3
elif m1!=None and m2!=None:
return m1+m2
elif m1!=None:
return m1
else:
return 0
# method overloading trick
def add(self,*a):
s =0
for i in a:
s+=i
return s
print('--------------------------- \nMethod overloading by defining \n m1(a,b) \n m1(a,b,c) method \ndeclaration does not support in python')
n1 = Nums()
#print(n1.sum(5,10))
#print(n1.sum(5,10,15))
print('n1.sum(5)=', n1.sum(5))
print('n1.sum(5,10)=', n1.sum(5,10))
print('n1.sum(5,10,15)=', n1.sum(5,10,15))
print('n1.add(50)=', n1.add(50))
print('n1.add(50,100)=', n1.add(50,100))
print('n1.add(50,100,150)=', n1.add(50,100,150))
print('--------------------------- \nMethod overriding, same class is available in Parent and child classes')
class A:
def show(self):
print(type(self), "show() in A")
class B(A):
def show(self):
print(type(self), "show() in B")
obj1 = A()
obj1.show()
obj2 =B()
obj2.show() | false |
6d260adeec1de35945ff49f6cf3507881b93e724 | RavikrianGoru/py_durga | /byte_of_python/py_flowcontrol_func_modules/10_while_else.py | 674 | 4.125 | 4 | # while-else
# input() is builtin function. we supply input as string. Once we enter something and press kbd[enter] key.
# input() function returns what we entered as string.
# then we can convert into any format what we required.
pass_mark = 45
running = True
print('Process is started')
while running:
marks = int(input("Enter marks:"))
if marks == pass_mark:
print('you just passed')
elif marks < pass_mark:
print('you failed')
running = bool(int(input("Enter your option(1/0)")))
print(type(running), running)
else:
print("you passed")
else:
print("While is is completed")
print('Process is completed')
| true |
565570d8c4eb0e04658e96ff362e08957f516f33 | RavikrianGoru/py_durga | /byte_of_python/ds/ds_using_set.py | 907 | 4.1875 | 4 | # Sets are unordered collections of simple objects. These are used when the existence of an
# object in a collection is more important than the order or how many times it occurs.
cities = {'gnt','mas','vij'}
print('all cities set:', cities)
names = ['gnt', 'mas', 'vij', 'gnt']
print('all names list:', names)
s = set(names)
print('all names set:', s)
print(f'ravi in s : {"gnt" in s}')
print(f'ravi not in s : {"gnt" not in s}')
s.add('hyd')
print(s)
print(f's.issubset(cities) = {s.issubset(cities)}')
print(f's.issuperset(cities) = {s.issuperset(cities)}')
print(f's.issuperset(names) = {s.issuperset(names)}')
print(f'cities | s = {cities | s}')
print(f'cities.union(s) = {cities.union(s)}')
print(f'cities & s = {cities & s}')
print(f'cities.intersection(s) = {cities.intersection(s)}')
# print(f'cities & names = {cities & names}') # TypeError: unsupported operand type(s) for &: 'set' and 'list'
| false |
3f26b2ccfc2e70402b275e09a4aa6b9a7a4a7b8a | emma-ola/calc | /codechallenge.py | 1,015 | 4.40625 | 4 | # Days in Month
# convert this function is_leap(), so that instead of printing "Leap year." or "Not leap year." it
# should return True if it is a leap year and return False if it is not a leap year.
# create a function called days_in_month() which will take a year and a month as inputs
def is_leap(year):
""" The function takes a year and returns True if it is a leap year or False if it is not"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year, month):
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month > 12 or month < 1:
return "Invalid month entered."
if month == 2 and is_leap(year):
return 29
return month_days[month - 1]
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
| true |
545f2e6bbc59b938c2e23b1c0a4ffbda28b5f2a9 | viveksyngh/Algorithms-and-Data-Structure | /Data Structure/Queue.py | 792 | 4.21875 | 4 | class Queue :
def __init__(self) :
"""
Initialises an empty Queue
"""
self.items = []
def is_empty(self) :
"""
Returns 'True' if Queue is empty otherwise 'False'
"""
return self.items == []
def enqueue(self, item) :
"""
Insert an item to the end of the Queue and Returns None
"""
self.items.append(0, item)
def dequeue(self) :
"""
Removes an item from the front end of Queue and Returns it
"""
return self.items.pop()
def size(self) :
"""
Returns the size (number of items) of the Queue
"""
return len(self.items)
#Tester Code
q = Queue()
q.enqueue('hello')
q.enqueue('dog')
q.enqueue(3)
q.dequeue()
| true |
40cc7c6d18482056565687650ad8f77cf15208fd | AmitKulkarni23/OpenCV | /Official_OpenCV_Docs/Core_Operations/place_image_over_another_using_roi.py | 1,942 | 4.15625 | 4 | # Placing image over another image using ROI
# Use of bitwise operations and image thresholding
# API used
# cv2.threshold
# 1st arg -> gray scale image
# 2nd arg -> threshold value used to classify the images
# 3rd arg -> Value to be given if pixel value is more than threshold value
# 4th arg -> different styles of thresholding
###################################
import cv2
# File names for images
messi_file_name = "messi_barca.jpg"
opencv_logo_file_name = "opencv-logo.png"
# Read the images
messi_image = cv2.imread(messi_file_name)
opencv_image = cv2.imread(opencv_logo_file_name)
# Get the rows, columns and channels for opencv image
rows, columns, channels = opencv_image.shape
# Now create a region of interest in teh first image
# Top left corner
roi = messi_image[0:rows, 0:columns]
# Now perform image thresholding
# Image thresholding requires a gray scale image
opencv_image_gray = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2GRAY)
# Show opencv_image_gray
# cv2.imshow("OpenCV Gray Wimdow", opencv_image_gray)
# Actual image thresholding
ret, mask = cv2.threshold(opencv_image_gray, 10, 255, cv2.THRESH_BINARY)
# Calculate the inverse of mask as well
mask_inv = cv2.bitwise_not(mask)
# Lets display the thresholded image
# cv2.imshow("Thresholded Image", mask)
# print(roi)
# lets show teh region of interest
# cv2.imshow("ROI Window", roi)
# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
# cv2.imshow("img1_bg Window", img1_bg)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(opencv_image,opencv_image,mask = mask)
# cv2.imshow("img2_fg Window", img2_fg)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
messi_image[0:rows, 0:columns] = dst
# Final Dipslay
cv2.imshow("Mesi Image After Operation", messi_image)
# Wait for user input from keyboard
cv2.waitKey(0)
# Destroy all windows
cv2.destroyAllWindows()
| true |
992c7145f29120ebfdaf21b2b503a9ebe5f05a60 | rossirm/Python | /Programming-Basics/Complex-Conditional-Statements/fruit_or_vegetable.py | 350 | 4.375 | 4 | plant = input()
result = ''
if plant == 'banana' or plant == 'apple' or plant == 'kiwi' \
or plant == 'cherry' or plant == 'lemon' or plant == 'grapes':
result = 'fruit'
elif plant == plant == 'tomato' or plant == 'cucumber' or plant == 'pepper' or plant == 'carrot':
result = 'vegetable'
else:
result = 'unknown'
print(result)
| false |
9a7f222209e105a33d45217efb1e1f26656a4a87 | AndreasArne/python-examination | /test/python/me/kmom01/plane/plane.py | 877 | 4.5 | 4 | #!/usr/bin/evn python3
"""
Program som tar emot värden av en enhetstyp och omvandlar till motsvarande
värde av en annan.
"""
# raise ValueError("hejhejhej")
# raise StopIteration("hejhejhej")
print("Hello and welcome to the unit converter!")
hight = float(input("Enter current hight in meters over sea, and press enter: "))
speed = float(input("Enter current velocity in km/h, and press enter: "))
temp = float(input("Enter current outside temperature in °C, and press enter: "))
# temp = float(input("Enter current outside temperature in °C, and press enter: "))
h = str(round(hight * 3.28084, 2))
s = str(round(speed * 0.62137, 2))
t = str(round(temp * 9 / 5 + 32, 2))
print(str(hight) + " meters over sea is equivalent to " + h + " feet over sea.")
print(str(speed) + " km/h is equivalent to " + s + " mph")
print(str(temp) + " °C is equivalent to " + t + " °F")
| true |
42e2363e23f1bb3ab1a1d905b7165e4c1371e456 | raymonshansen/dungeon | /python/utils.py | 1,832 | 4.1875 | 4 | """Utility functions."""
def plot_line(x1, y1, x2, y2):
"""Brensenham line drawing algorithm.
Return a list of points(tuples) along the line.
"""
dx = x2 - x1
dy = y2 - y1
if dy < 0:
dy = -dy
stepy = -1
else:
stepy = 1
if dx < 0:
dx = -dx
stepx = -1
else:
stepx = 1
dy = dy*2
dx = dx*2
x = x1
y = y1
pixelpoints = [(x, y)]
if dx > dy:
fraction = dy - (dx/2)
while x is not x2:
if fraction >= 0:
y = y + stepy
fraction = fraction - dx
x = x + stepx
fraction = fraction + dy
pixelpoints.append((x, y))
else:
fraction = dx - (dy/2)
while y is not y2:
if fraction >= 0:
x = x + stepx
fraction = fraction - dy
y = y + stepy
fraction = fraction + dx
pixelpoints.append((x, y))
return pixelpoints
def plot_circle(x0, y0, radius):
"""Return a list of the points around a circle."""
result = []
f = 1 - radius
ddf_x = 1
ddf_y = -2 * radius
x = 0
y = radius
result.append((x0, y0 + radius))
result.append((x0, y0 - radius))
result.append((x0 + radius, y0))
result.append((x0 - radius, y0))
while x < y:
if f >= 0:
y -= 1
ddf_y += 2
f += ddf_y
x += 1
ddf_x += 2
f += ddf_x
result.append((x0 + x, y0 + y))
result.append((x0 - x, y0 + y))
result.append((x0 + x, y0 - y))
result.append((x0 - x, y0 - y))
result.append((x0 + y, y0 + x))
result.append((x0 - y, y0 + x))
result.append((x0 + y, y0 - x))
result.append((x0 - y, y0 - x))
return result
| false |
ab77e72fabb93382bb3f009069465def1d6c3368 | suraj-thadarai/Learning-python-from-Scracth | /findingFactorial.py | 263 | 4.375 | 4 | #finding the factorial of a given number
def findingFactorial(num):
for i in range(1,num):
num = num*i
return num
number = int(input("Enter an Integer: "))
factorial = findingFactorial(number)
print("Factorial of a number is:",factorial)
| true |
6b1883815e71b89b42642fb84a893a599e69496e | cseshahriar/The-python-mega-course-practice-repo | /advance_python/map.py | 407 | 4.28125 | 4 | """
The map() function executes a specified function for
each item in an iterable. The item is sent to the function as a parameter.
"""
def square(n):
return n * n
my_list = [2, 3, 4, 5, 6, 7, 8, 9]
map_list = map(square, my_list)
print(map_list)
print(list(map_list))
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'),
('orange', 'lemon', 'pineapple'))
| true |
ae867fa7bd813de8cc06c1d30a7390eb8201e7fd | cseshahriar/The-python-mega-course-practice-repo | /random/random_example.py | 939 | 4.625 | 5 | # Program to generate a random number between 0 and 9
# importing the random module
import random
""" return random int in range """
print(random.randint(0, 9))
""" return random int in range"""
print(random.randrange(1, 10))
""" return random float in range """
print(random.uniform(20, 30))
"""
To pick a random element from a non-empty sequence (like a list or a tuple),
you can use random.choice(). There is also random.choices() for choosing
multiple elements from a sequence with replacement (duplicates are possible):
"""
items = ['one', 'two', 'three', 'four', 'five']
print(random.choice(items))
print(random.choices(items, k=2)) # two val return
print(random.choices(items, k=3)) # three val return
"""
You can randomize a sequence in-place using random.shuffle().
This will modify the sequence object and randomize the order of elements:
"""
print(items) # before
random.shuffle(items)
print(items) # after shuffle
| true |
4e75f9a6e15452f67f38d7eb43b17bc8cd8aacf9 | nikhiilll/Algorithms-using-Python | /Easy-AE/BubbleSort.py | 648 | 4.125 | 4 | def bubbleSort(array):
n = len(array)
for i in range(n):
for j in range(n - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
"""
TC: O(n^2) | SC: O(1)
"""
def bubbleSort2(array):
isSorted = False
counter = 0
while not isSorted:
isSorted = True
for i in range(len(array) - 1 - counter):
if array[i] > array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
isSorted = False
counter += 1
return array
print(bubbleSort2([8, 5, 2, 9, 5, 6, 3])) | false |
414024ec189b3b448632b6743408ca1235df3b7c | Darja-p/python-fundamentals-master | /Labs/06_functions/06_02_stats.py | 455 | 4.125 | 4 | '''
Write a script that takes in a list and finds the max, min, average and sum.
'''
inp1 = input("Enter a list of numbers: ")
def MinMax(a):
listN = a.split()
listN = [float(i) for i in listN]
max_value = max(listN)
min_Value = min(listN)
avg_Value = sum(listN) / len(listN)
sum_Value = sum(listN)
print(f"Maximum value is {max_value}, minimum value is {min_Value}, average is {avg_Value}, sum is {sum_Value}")
MinMax(inp1) | true |
700b4701729713ce93c836709beef9b393dd6327 | Darja-p/python-fundamentals-master | /Labs/08_file_io/08_01_words_analysis.py | 646 | 4.3125 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
from itertools import count
list1 = []
with open("words.txt",'r') as fin:
for w in fin.readlines():
w = w.rstrip()
list1.append(w)
print(list1)
print(f"shortest word is: {min((word for word in list1), key=len)}")
print(f"longest word is: {max((word for word in list1), key=len)}")
print(len(list1))
"""count1 = 0
for i in list1:
count1 += 1
print(count1)"""
| true |
6a8ba495dd00b7a9bd3d40098780799e4bb5d03d | Darja-p/python-fundamentals-master | /Labs/07_classes_objects_methods/07_05_freeform_inheritance.py | 2,115 | 4.21875 | 4 | '''
Build on your previous freeform exercise.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in the previous exercises.
If you cannot think of a way to build on your freeform exercise,
you can start from scratch here.
We encourage you to be creative and try to think of an example of
your own for this exercise but if you are stuck, some ideas include:
- A Vehicle superclass, with Truck and Motorcycle subclasses.
- A Restaurant superclass, with Gourmet and FastFood subclasses.
'''
class Movie():
list_to_see = []
def __init__(self, title, year, seen='have not seen'):
"""title should be a string"""
self.title = title
self.year = year
assert (type(self.year) == int), "year must be an integer"
self.seen = seen
def __str__(self):
return f"this is a movie called {self.title}, from {self.year}, which you {self.seen}"
def watch(self):
self.seen = "watched already"
return f" you watched {self.title}"
def watch_list(self):
if self.seen == "watched already":
print(f"you have seen this movie already")
else:
Movie.list_to_see.append(self.title)
return Movie.list_to_see
class RomCom(Movie):
pass
class newRomCom(RomCom):
"""class for Rom Com movies from the last two years"""
pass
class ActionMovie(Movie):
def __init__(self, title, year, seen, pg =13):
print(f"this is a pg {pg}")
self.pg = pg
super().__init__(title,year,seen)
def __str__(self):
return f"{self.title} from the year {self.year} with the rating {self.pg} which you {self.seen}"
pretty = Movie("Pretty woman", 1990)
print(pretty)
pretty.watch_list()
print(Movie.list_to_see)
la = RomCom("Love Actually", 1995)
print(la)
la.watch()
print(la)
ist = newRomCom("Isn't it romantic", 2019)
print(ist)
ist.watch()
ist.watch_list()
mm = ActionMovie("Mad Max", 2015,"not seen")
print(mm)
mm.watch_list()
print(Movie.list_to_see) | true |
8b84cae134528d332b0cf3e998c873697381a45e | Darja-p/python-fundamentals-master | /Labs/03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 485 | 4.1875 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list1 = list(input_dict.items())
print(list1)
def takeSecond(elem):
return elem[1]
sortedList = sorted(list1, key=takeSecond)
sortedList1 = sorted(list1, key=lambda elem: elem[-1])
print(sortedList)
print((sortedList1)) | true |
4d0e725efd60894619a1274d24eeb1d823966a72 | Darja-p/python-fundamentals-master | /Labs/02_basic_datatypes/02_05_convert.py | 731 | 4.5 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
a = 2
print (a)
a = float (a)
print(a)
b = 3.4 #the decimal part of the number will be lost
b = int (b)
print (b)
print (10 // 3) #the decimal part of the result will be lost
# just to test standard division print (10 / 3)
print (10 // 3.5) #the decimal part of the result will be lost
# just to test standard division print (10 / 3.5)
c ,d = input("Please insert two numbers: ").split()
c = float (c)
d = float (d)
print( c * d)
| true |
0ac789041795f5876f64b57d894d57cba7182993 | OrNaishtat/Python---Magic-Number | /TheMagicNumber.py | 2,032 | 4.1875 | 4 | ########################################################################################################################################
### NewLight - The Magic Number.
### The magic number generates a random number between 1 and 10, the user needs to guess the number.
### The user has a limited number of lives (NB_LIVES)
### If the user input is greater or lower than magic number terminal output will notify the user.
########################################################################################################################################
import random
###### ask_number function is responsible for the user for input - converting to int, and managing exceptions #####
def ask_number(nb_min, nb_max):
#number_str = input("What is the Magic Number between " + nb_min + "and " + nb_max) ## this gives concatination error, why?
number_int = 0
while number_int == 0:
number_str = input(f"What is the magic number (between {nb_min} and {nb_max}?) ")
try:
number_int = int(number_str)
except:
print("Must be a number!")
if number_int < nb_min or number_int > 10:
print("Error, you must enter a number between 1 and 10")
number_int = 0
return number_int
##### Variables #####
MIN_NUMBER = 1
MAX_NUMBER = 10
MAGIC_NUMBER = random.randint(MIN_NUMBER, MAX_NUMBER)
NB_LIVES = 5
number = 0
lives = NB_LIVES
##### Main loop is responsible for updating user with the number of lives left, greater/lower status, and if he won/lost #####
while not number == MAGIC_NUMBER and lives > 0:
print(f"You have {lives} lives!")
number = ask_number(MIN_NUMBER, MAX_NUMBER)
if number < MAGIC_NUMBER:
print("The Magic Number is GREATER")
lives -= 1
elif number > MAGIC_NUMBER:
print("The Magic number is LOWER")
lives -= 1
else:
print("You Won!")
if lives == 0:
print("You lost!")
print(f"The magic number was {MAGIC_NUMBER}") | true |
6836f4e8fada111cc10e3da114f6139277b1312f | nooknic/MyScript | /var.py | 277 | 4.25 | 4 | #Initialize a variable with an integer value.
var = 8
print(var)
#Assign a float value to the variable.
var = 3.142
print(var)
#Assign a string value to the variable.
var="Python in easy steps"
print(var)
#Assign a boolean value to the variable.
var = True
print(var)
| true |
5f26386ef1362913cba95ad2ec17ae5869fc90e3 | jagrutipyth/Restaurant | /Inheritance_polymorphism.py | 807 | 4.125 | 4 | class Restaurant:
def __init__(self,customer,money):
self.customer = customer
self.__money = money
def coupan(self):
print(f"Hello, {self.customer},please pay {self.__money} and take your coupan")
class IcecreamStand(Restaurant):
'''Using this class to show inheritence & polymorphism'''
def __init__(self,customer,money):
super().__init__(customer,money)
def coupan(self):
#self.coupan = coupan
#coupan = self.coupan
answer = (input("Do you have coupan?('Yes/No'): ").title())
if answer == 'Yes':
print(f"Hi {self.customer},please give your coupan.")
else:
super().coupan() #here calling coupan method from parent class - Restaurant
z = IcecreamStand('Jagruti',20)
print(z.coupan())
| true |
120762fb80c0df66a6102d87d0bac74ea94dbb4c | Ridwanullahi-code/python-list-data-type | /assignment.py | 961 | 4.25 | 4 | # base from the given list below create a python function using the following condition as specified below
# (a) create a seperated lists of string and numbers
# (b) sort the strings list in ascending order
# (c) sort the string list in descending order
# (d) sort the number list from the lowest to high
# (e) sort the number list from highest to lowest
gadget = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00,
"Televison", 1000, "Laptop Case", "Camera Lens",
]
string_list = []
number_list = []
for string in gadget:
if type(string) == str:
string_list.append(string)
else:
number_list.append(string)
print("Question a answer")
print(string_list)
print(number_list)
print("Question b answer")
sort_string = sorted(string_list)
print(sort_string)
print("Question c answer")
print(sort_string[::-1])
print("Question d answer")
sort_number = sorted(number_list)
print(sort_number)
print("Question e answer")
print(sort_number[::-1])
| true |
c7a76e6560b621b5e0c8b51a17685d016f46e4d2 | lowks/levelup | /hackerrank/staircase/staircase.py | 404 | 4.21875 | 4 | #!/bin/python
import sys
def staircase(total, number):
# Complete this function
hash_number = ""
for space in range(0, total - number):
hash_number += " "
for hash in range(0, number):
hash_number = hash_number + "#"
return hash_number
if __name__ == "__main__":
n = int(raw_input().strip())
for number in range(1, n+1):
print staircase(n, number)
| true |
bf61a8579548ab114612df83c57576df998186fa | jacealan/eulernet | /level1/9-Special Pythagorean triplet.py | 953 | 4.21875 | 4 | #!/usr/local/bin/python3
'''
Problem 9 : Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
https://projecteuler.net/problem=9
---
프로그래머 Programmer : 제이스 Jace (https://jacealan.github.io)
사용언어 Language : 파이썬 Python 3.6.4
OS : macOS High Sierra 10.13.3
에디터 Editor : Visual Studio Code
'''
def solution():
'''피타고라스의 수'''
sumofabc = 1000
for c in range(sumofabc // 3, sumofabc // 2):
for a in range(1, c // 2 + 2):
b = sumofabc - c - a
# print(a, b, c)
if b >= c:
continue
if a ** 2 + b ** 2 == c ** 2:
print("피타고라스의 수 :", a, b, c, a * b * c)
if __name__ == '__main__':
solution()
| false |
9964e05b7c8fd3ee6588d476fa2cbe240c7b921d | jacealan/eulernet | /level2/38-Pandigital multiples.py | 1,240 | 4.1875 | 4 | #!/usr/local/bin/python3
'''
Problem 38 : Pandigital multiples
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5,
giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
What is the largest 1 to 9 pandigital 9-digit number that can be formed
as the concatenated product of an integer with (1,2, ... , n) where n > 1?
https://projecteuler.net/problem=38
---
프로그래머 Programmer : 제이스 Jace (https://jacealan.github.io)
사용언어 Language : 파이썬 Python 3.6.4
OS : macOS High Sierra 10.13.3
에디터 Editor : Visual Studio Code
'''
def solution():
for i in range(1, 10000):
multiple = ''
for j in range(1, 10):
multiple += str(i * j)
if len(multiple) > 9 or '0' in multiple:
break
if len(multiple) == 9 and len(set(multiple)) == len(multiple):
print(i, j, multiple)
break
if __name__ == '__main__':
solution()
| true |
d1304b21ceb527d863c16c297877ae04b5405962 | daredtech/lambda-python-1 | /src/14_cal.py | 1,756 | 4.53125 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
"""
import sys
import calendar
from datetime import datetime
def user_calendar():
print('enter month and year: ')
user_input_value = input()
if user_input_value == '':
current_month = calendar.month(2019, 8, w=0, l=0)
print(current_month)
user_input_list = user_input_value.split(' ')
if len(user_input_value) == 1 and int(user_input_list[0])<=12:
current_month = calendar.month(2019, (int(user_input_list[0])), w=0, l=0)
print(current_month)
if len(user_input_list) == 2 and (int(user_input_list[0])) <=12:
current_month = calendar.month((int(user_input_list[1])), (int(user_input_list[0])), w=0, l=0)
print(current_month)
if len(user_input_list) == 2 and (int(user_input_list[1])) <=12:
current_month = calendar.month((int(user_input_list[0])), (int(user_input_list[1])), w=0, l=0)
print(current_month)
else:
return print('The expected format is : MM, YYYY')
user_calendar() | true |
a5924b232af9c4c761d7093cce952507ba9341a8 | gopikrishnansa/weather_in_your_location | /weather app.py | 1,417 | 4.15625 | 4 | import requests
class weather:
def get(self):
try:
#gets data from openweathermap api
#converting that info to json
#accessing json files
#printing the info here
global city,api_address,mainweather,descriptio,wind,name
name = input("enter your name: ")
city = input("enter the city you want to know: ")
api_address = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=0c42f7f6b53b244c78a418f4f181282a".format(city)
json_data = requests.get(api_address).json()
mainweather = json_data["weather"][0]["main"]
descriptio = json_data["weather"][0]["description"]
wind = json_data["wind"]["speed"]
print(" ")
except KeyError as wea:
#most common error is adding a location which is invalid (only valid input from user is location)
print("""
---------------------------------------------
| invalid city name, please give a valid one |
---------------------------------------------
""")
else:
print(""" hi {}, It is nice to see you. your selected location is {} and according to my observation I
can see {} ({}) there, wind speed is {} km/hr.""".format(name,city,mainweather,descriptio,wind))
b=weather()
b.get()
| true |
0e370f1c06a4399bf69cc0171b8d89e654c4958c | Westamus/PycharmProjects | /lesson_003/01_days_in_month.py | 1,940 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input("Введите, пожалуйста, номер месяца: ")
user_input = int(user_input)
month = int(user_input)
print('Вы ввели', month)
month_days_31 = [1, 3, 5, 7, 8, 10, 12]
month_days_30 = [4, 6, 9, 11]
for days in month_days_31:
if days == user_input:
print('Дней в этом месяце -', 31)
break
for days in month_days_30:
if days == user_input:
print('Дней в этом месяце -', 30)
break
if user_input == 2:
print('Дней в этом месяце -', 28)
# Решение без for
months_day_count = {'1': 31,
'2': 28,
'3': 31,
'4': 30,
'5': 31,
'6': 30,
'7': 31,
'8': 31,
'9': 30,
'10': 31,
'11': 30,
'12': 31,
}
user_input = input("Введите, пожалуйста, номер месяца: ")
if user_input.isdigit():
month = int(user_input)
if 1 <= month <= 12:
day_count = months_day_count[user_input]
print('Вы ввели', month)
print('Кол-во дней в месяце:', day_count)
else:
print('Месяца с таким номер не существует.')
else:
print('Необходимо ввести число.')
| false |
a7cd28c10d88473e318bf9daa1192d408d78f54a | sulleyi/CSC-120 | /Project1/card.py | 474 | 4.15625 | 4 | class card:
"""
Class for the card object
"""
def __init__(self, value, suit):
"""
initializes card object
:param self: instance of card
:param value: cards number or face value
:param suit: suit value of card (heart,diamond, club, or spade)
:return:
"""
self.value = value
self.suit = suit
def printCard(self):
print("[" + str(self.value) + " , " + self.suit + "]")
| true |
c2a75a3e85541ad15cba57dbc6488e4532082b22 | shayansaha85/python_basic_loops_functions | /Factorial.py | 307 | 4.25 | 4 | # Python Program to Find the Factorial of a Number
def findFactorial(number):
if number==0:
return 1
elif number==1:
return 1
else:
return number * findFactorial(number-1)
number = int(input("Enter a number = "))
print("{0}! = {1}".format(number,findFactorial(number))) | true |
a95fb7f69f3169c125d3fa9dfc65380b2ff5efed | JubindraKc/Test_feb_19 | /question2.py | 598 | 4.125 | 4 | '''
2. Create a class Circle which has a class variable PI with value=22/7.
Make two methods getArea and getCircumference inside this Circle class.
Which when invoked returns area and circumference of each ciecle instances.
'''
class Circle:
PI = 22/7
def __init__(self,radius):
self.radius = radius
def getArea(self):
return self.radius*self.radius*2*Circle.PI
def getCircumference(self):
return self.radius*2*Circle.PI
c1=Circle(2)
print("The area is:")
print(c1.getArea())
print("The circumference is:")
print(c1.getCircumference()) | true |
ecbdca79b8bca2250d1fc37b4449d4994c143096 | mpowers47/cs1301-intro-to-python | /Unit 3 - Control Structures/WordCount2.py | 1,981 | 4.5 | 4 | # Now let's make things a little more challenging.
#
# Last exercise, you wrote a function called word_count that
# counted the number of words in a string essentially by
# counting the spaces. However, if there were multiple spaces
# in a row, it would incorrectly add additional words. For
# example, it would have counted the string "Hi David" as
# 4 words instead of 2 because there are two additional
# spaces.
#
# Revise your word_count method so that if it encounters
# multiple consecutive spaces, it does *not* count an
# additional word. For example, these three strings should
# all be counted as having two words:
#
# "Hi David"
# "Hi David"
# "Hi David"
#
# Other than ignoring consecutive spaces, the directions are
# the same: write a function called word_count that returns an
# integer representing the number of words in the string, or
# return "Not a string" if the input isn't a string. You may
# assume that if the input is a string, it starts with a
# letter word instead of a space.
# Write your function here!
def word_count(my_string):
iterator = 0
try:
new_string = " ".join(my_string.split())
for character in new_string:
if character == " ":
iterator += 1
else:
continue
return iterator + 1
except:
return "Not a string"
# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs.
#
# If your function works correctly, this will originally
# print:
# Word Count: 4
# Word Count: 2
# Word Count: Not a string
# Word Count: Not a string
# Word Count: Not a string
print("Word Count:", word_count("Four words are here!"))
print("Word Count:", word_count("Hi David"))
print("Word Count:", word_count(5))
print("Word Count:", word_count(5.1))
print("Word Count:", word_count(True)) | true |
8f50331313f4b9b62dbcc35eeda564773bebddf3 | mpowers47/cs1301-intro-to-python | /Unit 4 - Data Structures/AfterSecond.py | 1,592 | 4.4375 | 4 | # Write a function called after_second that accepts two
# arguments: a target string to search, and string to search
# for. The function should return everything in the first
# string *after* the *second* occurrence of the search term.
# You can assume there will always be at least two
# occurrences of the search term in the first string.
#
# For example:
# after_second("11223344554321", "3") -> 44554321
#
# The search term "3" appears at indices 4 and 5. So, this
# returns everything from the index 6 to the end.
#
# after_second("heyyoheyhi!", "hey") -> hi!
#
# The search term "hey" appears at indices 0 and 5. The
# search term itself is three characters. So, this returns
# everything from the index 8 to the end.
#
# Hint: This may be more complicated than it looks! You'll
# have to look at the length of the search string and
# either modify the target string or take advantage of the
# extra arguments you can pass to find().
# Write your function here!
def after_second(target_string, search_string):
index1 = target_string.find(search_string)
index2 = target_string.find(search_string, index1 + 1)
var1 = index2 + len(search_string)
return target_string[var1:]
# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs.
#
# If your function works correctly, this will originally
# print 44554321 and hi!, each on their own line.
print(after_second("11223344554321", "3"))
print(after_second("heyyoheyhi!", "hey"))
| true |
2b969a489710375589779588bfe13a51025b0dfc | mpowers47/cs1301-intro-to-python | /Unit 2 - Procedural Programming/GoOutToLunch.py | 1,144 | 4.46875 | 4 | hungry = True
coworkers_going = False
brought_lunch = False
# You may modify the lines of code above, but don't move them!
# When you Submit your code, we'll change these lines to
# assign different values to the variables.
# Imagine you're deciding whether or not to go out to lunch.
# You only want to go if you're hungry. If you're hungry, even
# then you only want to go if you didn't bring lunch or if
# your coworkers are going. If your coworkers are going, you
# still want to go to be social even if you brought your lunch.
#
# Write some code that will use the three boolean variables
# defined above to print whether or not to go out to lunch.
# It should print True if hungry is True, and either
# coworkers_going is True or brought_lunch is False.
# Otherwise, it should print False.
# Write your code here!
def goLunch(hungry, coworkers_going, brought_lunch):
if hungry == True:
if coworkers_going == True or brought_lunch == False:
return True
else:
return False
else:
return False
print(goLunch(hungry, coworkers_going, brought_lunch)) | true |
8b4516e193fc6281abace1fa4c3205446c57d366 | Sameer411/First_Year_Lab_Assignment | /sem 2 Programs/Assignment5/sqrt.py | 499 | 4.3125 | 4 | import math
print("We have to find squareroot of a number:\n")
number=int(input("Please enter the number:"))
if number<0:
print("Please enter valid number:")
else:
print('Squareroot of the number {0} is {1}'.format(number,math.sqrt(number)))
#OUTPUT:
#pl-ii@plii-dx2480-MT:~/Desktop/FE-D-07/ASSIGNMENT6$ python sqrt.py
#We have to find squareroot of a number:
#Please enter the number:10
#Squareroot of the number 10 is 3.16227766017
#pl-ii@plii-dx2480-MT:~/Desktop/FE-D-07/ASSIGNMENT6$#
| true |
9ec48f6722ff8c3e5e6e21786aab2d10f045cd16 | paluch05/Python-rep | /Task17/Task17.py | 667 | 4.125 | 4 | def longest_sentence_and_most_common_word():
stream = open('artykul.txt', 'r', encoding='utf-8')
try:
content = stream.read()
n = content.split(".")
length_of_sentence = [len(i) for i in n]
from collections import Counter
count = Counter(content.lower().strip().split())
finally:
stream.close()
return count, length_of_sentence, n
if __name__ == '__main__':
count, length_of_sentence, n = longest_sentence_and_most_common_word()
print('The longest sentence in this article is: ', n[length_of_sentence.index(max(length_of_sentence))])
print('Most common words are:', count.most_common(10))
| true |
a9d359ded1e81d98b61397d883a82e22a4682758 | luizolima/estudo-python | /08-escopo_de_variaveis.py | 1,046 | 4.59375 | 5 | """
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais: São reconhecidas, ou seja, se escopo compreende, todo o programa.
2 - Variáveis locais: São reconhecidas apenas no blovo onde foram declaradas, ou seja, seu escopo está limitado ao bloco
onde foi declarada.
Para declarar variáveis em Python fazemos:
nome_da_variavel = valor_da_variavel
Python é um linguagem de tipagem dinâmica. Isso significa que ao declararmos uma variável, nós não colocamos o tipo de
dado dela.
Este tipo é inferido ao atríbuírmos o valor à mesma
Exemplo em C:
int numero = 42;
Exemplo em Java:
int numero = 42;
"""
numero = 42 # Exemplo de variável global
print(numero)
print(type(numero))
numero = 'Geek' # Podemos fazer uma reatribuição para a mesma variável em Python
print(numero)
print(type(numero))
nao_existo = 'oi'
print(nao_existo)
numero = 2
# novo = 0
if numero > 10:
novo = numero + 10 # A variável novo está declarada localmente dentro do bloco do if, portanto é local.
print(novo)
print(novo)
| false |
5dbd68eb09ca61915dba0136dbd97a4bb5fbe3ad | doitharsha007/ost | /8b.py | 848 | 4.125 | 4 | from math import floor # importing 'floor' function from 'math' module
start = int(input("Enter the start of the Armstrong number range - ")) #lower limit
end = int(input("Enter the end of the Armstrong number range - ")) #upper limit
if start > end or start < 0 or end < 0:
print("Invalid range")
else:
flag = 0
print("Armstrong number(s) between",start,"and",end,"- ",end="")
for i in range(start,end+1):
temp = i
sum1 = 0
while temp != 0:
remainder = temp % 10
sum1 = sum1 + pow(remainder,3)
temp = floor(temp / 10) # truncates to the previous highest integer
if sum1 == i:
flag = 1
print(sum1,end=" ")
if flag == 0:
print("zero numbers") # if there's no armstrong number within the specified range
| true |
d12e0cf63a30c0065fd77ded34de601eb64c7369 | doitharsha007/ost | /9b.py | 770 | 4.125 | 4 | # 9b) : Write a program to find maximum element in the list using recursive
# functions
def maximum(numbers):
if len(numbers) == 1: #if length of list is 1
return numbers[0]
else:
max1 = numbers[0]
if max1 > numbers[1]: #if first element > second element
del numbers[1]
return maximum(numbers)
else: #otherwise, first element < second element
return maximum(numbers[1:]) #list slicing, omit first element
s = input("Enter some numbers, separated by space - ")
numbers = [int(i) for i in s.split(" ")] #list comprehension, here integers are
#split using space, and each integer is inserted into the list
print("Maximum of ",numbers,"- ",maximum(numbers))
| true |
a6ab60f863d6d342baef9849a1f9ea71a263efe8 | umeshpatil080/examples | /python/Programs/CTCI/string_reversal.py | 807 | 4.25 | 4 | #-------------------------------------------------------------------------------
# Reversing a string
#-------------------------------------------------------------------------------
class StrReversal():
def __init__(self):
pass
def reverse(self, string = ""):
if(not string):
return string
lstring = list(string)
n = len(lstring)
i = 0
while(i < n/2):
tmp = lstring[i]
lstring[i] = lstring[n-1-i]
lstring[n-1-i] = tmp
i += 1
rstring = "".join(lstring)
return rstring
def main():
strRev = StrReversal()
string = "ABCD"
rstring = strRev.reverse(string)
print("string :{0}\nrstring: {1}".format(string, rstring))
if __name__ == '__main__':
main()
| false |
207c8a802058b19c23dfa1de8d754941c84c74eb | dobrienSTJ/Daniels-Projects | /SpeedDistanceTime.py | 1,153 | 4.28125 | 4 | #A simple Program that calculates the Speed, Distance and Time!
print("This is a simple Program that calculates the Speed, Distance and Time!")
triangle=input("Please choose a number to find out: 1. Speed 2. Distance 3. Time")
if triangle == "1":
print("We will find the Speed")
distance1=(int(input("Please enter the distance in Metres")))
time1=(int(input("Please enter the time in seconds")))
print("The speed will be in m/s")
answer1 = distance1/time1
print (answer1)
elif triangle == "2":
print("We will find the Distance")
speed2=(int(input("Please enter the the Speed in m/s")))
time2=(int(input("Please enter the time in Seconds")))
print("The distance will be in Metres")
answer2 = speed2*time2
print (answer2)
elif triangle == "3":
print("We will find the Time")
speed3=(int(input("Please enter the the Speed in m/s")))
distance3=(int(input("Please enter the distance in Metres")))
print("The time will be in Seconds")
answer3 = distance3/speed3
print (answer3)
else:
print("ERROR")
print("Thanks for using this program")
end=input("End Of Program.....")
| true |
293e24949673b471c1a83d42ca74818f625dfa53 | dobrienSTJ/Daniels-Projects | /Quadratic.py | 991 | 4.25 | 4 | #A simple Program that automically adds the variable on at the start of the calculation in the same unit
def variable(x):
x = (int(x))
x = x**2
xword = (str(x))
print(xword+" is your Variable!!")
print("Now we will move onto the calculating unit")
number1=(int(input("Please enter your First Number")))
number2=(int(input("Please enter your Second Number")))
choice=input("Would you like to Add, Subtract, Multiply or Divide? (Use Symbols)")
if choice == "+":
answer1 = x+number1+number2
print (answer1)
elif choice == "-":
answer2 = x-number1-number2
print (answer2)
elif choice == "x":
answer3 = x*number1*number2
print (answer3)
elif choice == "÷":
answer4 = x/number1/number2
print (answer4)
else:
print("ERROR")
variable2=(input("Please enter your Variable"))
variable(variable2)
| true |
70578b8fa3afdc6a9394a8531ab7a29ea06617dc | aasheeshtandon/Leetcode_Problems | /102_RECURSIVE_binary_tree_level_order_traversal.py | 1,052 | 4.46875 | 4 |
# Recursive Level Order Traversal of a Binary Tree.
## Time Complexity: O(n)^2 where n is number of nodes in the binary tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def height(root):
if root is None:
return 0
return max(height(root.left), height(root.right)) + 1
def printLevelOrder(root):
if root is None:
return
h = height(root)
for i in range(1, h + 1):
printCurrentLevel(root, i)
def printCurrentLevel(root, level):
if root is None:
return
if level == 1:
print(root.val, end=" ")
elif level > 1:
printCurrentLevel(root.left, level - 1)
printCurrentLevel(root.right, level - 1)
# Driver Program to test the above methods.
if __name__ == '__main__':
root = Node(3)
root.left = Node(1)
root.right = Node(8)
root.left.left = Node(1)
root.left.right = Node(2)
root.right.left = Node(6)
# Calling the Level Order Traversal Method.
printLevelOrder(root)
| true |
11cc8880c170c7ec22010502b9606cccf3c740ac | evelinasvarovskaya/evelina | /theme10/theme10.1.py | 255 | 4.1875 | 4 | value1 = int(input("Enter A: "))
value2 = int(input("Enter B: " ))
if value1>2 and value2<=3:
print("Неравенства A > 2 и B ≤ 3 справедливы.")
else:
print("Неравества A > 2 и B ≤ 3 несправедливы.") | false |
17ce117e7470a71e2117b023b2eae966a40a5a9a | MCornejoDev/Python | /EjerciciosIFElse/Ejercicio5.py | 689 | 4.125 | 4 | #Escriba un programa que pida tres números y que escriba si son los tres iguales,
#si hay dos iguales o si son los tres distintos.
print("COMPARADOR DE TRES NÚMEROS")
n1 = float(input("Dime un número : ")); n2 = float(input("Dime otro número : ")); n3 = float(input("Dime otro número : "))
if(n1 == n2 and n1 == n3 and n2 == n3): #Los tres números son iguales
print("Los tres números son iguales")
else:
if(n1 == n2 != n3 or n1 == n3 != n2 or n2 == n3 != n1): #Hay dos números iguales
print("Hay dos números iguales")
else:
if(n1 != n2 and n1 != n3 and n2 != n3):
print("Los tres números son distintos") #Los tres números son distintos | false |
482fa766ee6a9dedae61f9f62d555b124a8f67f3 | kjazleen/assignment | /assignment8.py | 1,236 | 4.21875 | 4 | #Q1 what is time tuple?
print("There is a popular time module available in python which provides function for working with time,and for converting"
" between representations ,the function (time.time()) returns the current system time in ticks since 12 am,january 1,1970(epoch)")
#"Index Attribute values"
#"o tm_year 2018"
#"1 tm_mon 1-12"
#"2 tm_mday 1-31"
#"3 tm_hour 0 to 23"
#"4 tm_min 0 to 59"
#"5 tm_sec 0 to 61(60 or 61 are leap-seconds"
#"6 tm_wday 0 to 6"
#"7 tm_yday 1 to 366"
#"8 tm_isdst -1,0,1 where -1 means library determines DST")'''
#Q2
import time
print(time.asctime())
#Q3
import datetime
d=(datetime.date.today())
print(d.month)
#Q4
import datetime
d=(datetime.date.today())
print(d.day)
#Q5
import datetime
a='2021/01/11'
d=(datetime.datetime.strptime(a,"%Y/%m/%d"))
print(d.day)
#Q6
import time
print(time.asctime(time.localtime()))
#Q7
import math
f=int(input("enter a no."))
print(math.factorial(f))
#Q8
import math
a=int(input("enter a no"))
b=int(input("enter a no"))
print(math.gcd(a,b))
#Q9
import os
print(os.getcwd)
print(os.environ)
| false |
51461972405b769a39923c6255218c83f53b0a7f | proneetsharma/maze_solver | /helper.py | 1,318 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import collections
import string
import copy
def next_movement(position):
x, y = position
next_pos = [(x-1, y), (x, y-1), (x+1, y), (x, y+1)]
return next_pos
def write_to_file(file_name, all_path, maze_map):
"""Function to write output to console and the optimal path
from start to each goal to txt file.
Please ensure that it should ALSO be possible to visualize each and every
step of the tree traversal algorithm in the map in the console.
This enables understanding towards the working of your
tree traversal algorithm as to how it reaches the goals.
Parameters
----------
filen_name : string
This parameter defines the name of the txt file.
path : [type]
[description]
"""
out = list()
for i in range(len(maze_map)):
a = list()
for j in range(len(maze_map[0])-1):
a.append(maze_map[i][j])
out.append(a)
f = open(file_name, "w+")
for path in all_path:
maze_path = copy.deepcopy(out)
for i in path:
x, y = i
maze_path[x][y] = "+"
for i in maze_path:
n = "".join(i)
print(n)
f.write(n)
f.write("\n")
f.close()
| true |
a791f10e75505502f07622fd0d08c05994b04216 | chaseyb/python-snake-game-v2 | /Button.py | 1,582 | 4.125 | 4 | class button(object):
"""
This is a button class that makes it easy to create buttons. It includes a button initializer, and several control
functions, such as changing colour when the button is hovered.
"""
def __init__(self, colour, hoverColour, display, text, left, top, width, height, textColour, offset, centerWidth,
centerHeight, font):
self.colour = colour
self.hoverColour = hoverColour
self.display = display
self.text = text
self.top = top
self.left = left
self.width = width
self.height = height
self.textColour = textColour
self.offset = offset
self.centerWidth = centerWidth
self.centerHeight = centerHeight
self.font = font
def displayText(self):
displayText = self.font.render(self.text, True, self.textColour)
self.display.blit(displayText, [self.centerWidth - (displayText.get_rect().width / 2),
self.centerHeight + (self.height / 2) - (displayText.get_rect().height / 2)
+ self.offset])
def showButton(self):
self.display.fill(self.colour, (self.left, self.top, self.width, self.height))
self.displayText()
def isHovered(self, cursor):
if self.left < cursor[0] < self.left + self.width and self.top < cursor[1] < self.top + self.height:
self.display.fill(self.hoverColour, (self.left, self.top, self.width, self.height))
self.displayText()
return True | true |
bdf38d484f83c59ac00cf2be84ae78236e1eecf1 | joe-bq/dynamicProgramming | /python/LearnPythonTheHardWay/FileSystem/Shelves/ShelvesOperation.py | 1,004 | 4.125 | 4 | '''
Created on 2012-11-16
@author: Administrator
file: ShelvesOperation.py
description: this file will demonstrate the use of the shelv object
what is shelve? shelves is something that gives you some basic persistence so you will be able to retrieve what you have shelved in last session
'''
import shelve
def demon_shelve():
book = shelve.open("addresses")
book['flintstone'] = ('fred', '555-1234', '1233 Bedrock Place')
book['rubble'] = ('barney', '555-4321', '1235 Bedrock Place')
book.close()
def shelve_out():
book = shelve.open("addresses")
if 'flintstone' in book:
flintstone = book['flintstone']
print("*** after retrieved the shelves")
print(flintstone)
rubble = book['rubble']
book.close()
if __name__ == '__main__':
book = shelve.open("addresses")
exists = 'flintstone' in book
book.close()
if exists:
shelve_out()
else:
demon_shelve()
| true |
292fa24444c2d56dee834171f54e39e819495951 | k-schmidt/Learning | /Data_Structures_and_Algorithms/1_1.py | 442 | 4.25 | 4 | '''
Write a short Python function, is_multiple(n, m), that takes two integer values
and returns True if n is a multiple of m, that is, n = mi for some integer i,
and False otherwise.
'''
def is_multiple(n, m):
try:
return True if (int(n) % int(m) == 0) else False
except ValueError:
print "Numbers must be Integer values"
if __name__ == '__main__':
is_multiple(50,3)
is_multiple(2,50)
is_multiple(50,2)
| true |
30dac93810bf90c35d6622ded8f249632216e5b4 | imlifeilong/MyAlgorithm | /leetcode/双指针/26. 删除有序数组中的重复项.py | 1,613 | 4.25 | 4 | """
输入:nums = [1,1,2]
输出:2, nums = [1,2,_]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。
思路
快慢指针 left 指向0 right 指向1
比较left 和 right 指向的值是否相等,如果相等,right向前移动
如果不相等,left移动一位,然后将right的值赋到left上
相当于 left 用来记录,right用来扫描,当right扫到新值(新值就是和当前left所指的值比较)时,left就记录下,
当right没有扫的新值时, 就一直扫下去直到遇见新值或结束
上面所有的前提是 所给的是 升序排列 的数组
"""
class Solution:
def removeDuplicates(self, nums):
left = 0
right = 1
while right < len(nums):
if nums[left] == nums[right]:
right += 1
else:
# right扫到不同的值时,left记录一下
left += 1
nums[left] = nums[right]
# right继续扫描后面的值
right += 1
# 最后返回left停止位置的长度
return left + 1, nums
if __name__ == '__main__':
nums = [1, 1, 2]
# nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
s = Solution()
res = s.removeDuplicates(nums)
print(res)
| false |
03afc7fb75e5a49441c5a90dee8bd5fd0b336a91 | imlifeilong/MyAlgorithm | /basic/排序/排序-选择排序.py | 1,103 | 4.40625 | 4 | # _*_ coding:utf-8 _*_
'''
选择排序过程:
1、首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,
2、然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
3、以此类推,直到所有元素均排序完毕。
比较次数n(n-1)/2
时间复杂度O(n2)
'''
def select_sort(data):
length = len(data)
for i in range(length):
# 选择第一个元素为记为最小值,min_index左边是排行顺序的
min_index = i
# 扫描剩下的元素,选取比min_index所指的值小的
for j in range(i + 1, length):
# 迭代找到最小的值的索引,赋给min_index
if data[j] < data[min_index]:
min_index = j
# 找到最小值后,排到顺序的后面
data[i], data[min_index] = data[min_index], data[i]
return data
if __name__ == "__main__":
data = [5, 3, 2, 6, 1, 7, 8, 4, 5, 1, 9, 5, 5, 6]
# data = [5, 3, 2, 6, 1]
res = select_sort(data)
print(res)
| false |
f2bfd56ab1e8b66be51c7646b8d797273457b5c1 | PatrickWalsh6079/Software_Security | /Brute force PIN entry/brute_force_PIN.py | 1,819 | 4.25 | 4 | """
Filename: brute_force_PIN.py
Author: Patrick Walsh
Date: 5/2/2021
Purpose: Program shows a simulation of an ATM display
screen that asks the user for their PIN. The program
is vulnerable to a brute force entry that randomly guesses
the PIN until it finds the right one. The program also
provides a mitigation technique to limit how often a PIN
can be entered and locks the account after a certain
number of incorrect PINs have been guessed.
"""
import time
import secrets
import string
PIN_CORRECT = '4437' # the correct PIN
attempt_num = 0 # number of brute force attempts
using_mitigation = True # if set to False, will not employ brute force mitigation
pin_guess = '' # start PIN as empty string
NUMBERS = string.digits # constant for generating random number values
print("WELCOME TO THE ATM!\nPLEASE ENTER A PIN\n\n")
def brute_force(pin):
"""
Takes in PIN as 4 character string and returns a
randomly generated combination of 4 digits.
"""
# PIN is 4 digits long
characters = [secrets.choice(NUMBERS), secrets.choice(NUMBERS), secrets.choice(NUMBERS),
secrets.choice(NUMBERS)]
for i in range(4): # generates random PIN with secrets module
pin += characters[secrets.randbelow(len(characters) - 1)]
return pin
while True:
if using_mitigation:
time.sleep(1) # limits attempts to once per second
if attempt_num > 4: # locks account after 5 failed login attempts
print('Maximum attempts reached. Account locked.')
break
if brute_force(pin_guess) == PIN_CORRECT:
print('PIN accepted')
print('Attempt number:', attempt_num)
break
else:
print(brute_force(pin_guess), 'Incorrect PIN')
attempt_num += 1
| true |
a3ac403d1c99f9eab7c7b0ae8f8f93b25621550f | Sulav13/python-experiments | /cw1/distance.py | 1,023 | 4.6875 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of
# robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and
# original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
x=0
y=0
while True:
dir = input("enter the direction step: ")
if not dir:
break
dir, steps = dir.split(' ')
if dir == "left":
x = x - int(steps)
elif dir == "right":
x = x + int(steps)
elif dir == "up":
y = y + int(steps)
elif dir == "down":
y = y - int(steps)
else:
pass
distance = (x**2 + y**2)**(1/2)
print("the output is: ",int(distance)) | true |
024a3571a0078a16507c2afd991a9d21b002e171 | swaroop325/python-programs | /4.py | 305 | 4.125 | 4 | def most_repeated_letters(word_1):
lettersCount = {}
for ch in word_1:
if ch not in lettersCount:
lettersCount[ch] = 1
else:
lettersCount[ch] += 1
return max(lettersCount, key=lettersCount.get)
str=input()
print most_repeated_letters(str)
| true |
e0f2a70c32cf95ed23f08ed72390e37d0adcaa84 | XNetLab/ProbGraphBetwn | /util.py | 548 | 4.1875 | 4 | #! /usr/bin/python
# coding = utf-8
import time
from functools import wraps
def fn_timer(function):
"""
Used to output the running time of the function
:param function: the function to test
:return:
"""
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = function(*args, **kwargs)
t1 = time.time()
print ("Total time running %s: %s seconds" %
(function.func_name, str(t1-t0))
)
return result
return function_timer | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.