blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e64d102e7bd5d1e77f9760261e55f25a2c0c45c7 | paulienuij/Advent-of-Code | /2017/Day 03 - Spiral Memory/Day 3 - Part 2.py | 1,765 | 4.125 | 4 | import numpy as np
import itertools
np.set_printoptions(suppress=True, linewidth=200)
def move_right(x, y):
return x, y+1
def move_down(x, y):
return x+1, y
def move_left(x, y):
return x, y-1
def move_up(x, y):
return x-1, y
def sum_around(spiral, x_0, y_0):
global step
total = spiral[x_0-1, y_0-1] + spiral [x_0-1, y_0] + spiral[x_0-1, y_0+1] + \
spiral[x_0 , y_0-1] + spiral [x_0 , y_0] + spiral[x_0 , y_0+1] + \
spiral[x_0+1, y_0-1] + spiral [x_0+1, y_0] + spiral[x_0+1, y_0 + 1]
step += 1
return total
'''
def sum_around(spiral, x_0, y_0):
#used to test fo correct spiraling
global step
step += 1
#print(spiral)
return step
'''
input_dat = 368078
step = 1
x_range = 12
y_range = 12
spiral = np.zeros((x_range, y_range))
x = int(x_range/2)
y = int(y_range/2)
spiral[x, y] = 1
N = 1
try:
while np.amax(spiral) <= input_dat:
# figure out how to spiral
#based on https://stackoverflow.com/questions/23706690/how-do-i-make-make-spiral-in-python
for n in range(N):
x, y = move_right(x, y)
spiral[x, y] = sum_around(spiral, x, y)
for n in range(N):
x, y = move_up(x, y)
spiral[x, y] = sum_around(spiral, x, y)
for n in range(N+1):
x, y = move_left(x, y)
spiral[x, y] = sum_around(spiral, x, y)
for n in range(N+1):
x, y = move_down(x, y)
spiral[x, y] = sum_around(spiral, x, y)
N += 2
except IndexError:
pass
morethaninput = []
for x in range (x_range):
for y in range(y_range):
if spiral[x, y] >= input_dat:
morethaninput.append(spiral[x, y])
print(spiral)
print(min(morethaninput))
| false |
c1d26340accae74e2412922ada47111f9470f9dc | conniec-dev/thinkpython_practices | /chapter15/ex2_part2.py | 651 | 4.34375 | 4 | import math
import turtle
class Point:
"""Represents a Point."""
class Circle:
"""Represents a circle.
attributes: center, radius
"""
def polyline(t, n, length, angle):
for i in range(n):
t.fd(length)
t.lt(angle)
def draw_circle(t, c):
angle = 360
arc = 2 * math.pi * c.radius * angle / 360
n = int(arc / 3) + 1
step_length = arc / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
pony = turtle.Turtle()
pony.speed(100)
cir = Circle()
cir.center = Point()
cir.center.x = 150
cir.center.y = 100
cir.radius = 75
draw_circle(pony, cir)
turtle.mainloop() | false |
9dd7881aa54985603811ec686f460498a7511bc1 | 107318041ZhuGuanHan/TQC-Python-Practice | /_8_string/801/main.py | 531 | 4.1875 | 4 | # 1.用迴圈裡面的i 2.用.index()
# ----------------------------------------------------------------------
# 1. -> 跟參考答案差不多
string = input("請輸入一個字串: ")
for i in range(0, len(string)):
print("Index of '%s': %d" % (string[i], i))
# ----------------------------------------------------------------------
# 2.
string = input("請輸入一個字串: ")
for s in string:
print("Index of '%s': %d" % (s, string.index(s)))
# ★index()使用格式: list / string .index(裡面的元素)
| false |
8fbe6b5691b46e096596ac6ccdef11296b21046c | 107318041ZhuGuanHan/TQC-Python-Practice | /_8_string/804/main.py | 291 | 4.25 | 4 | # 使用.upper()轉成每個英文字母大寫 / 使用.title()轉成句子中的每個字首大寫
# 這一題很智障
string = input("請輸入一個英文句子: ")
print("轉成每個英文字母大寫: " + string.upper())
print("轉成每個單字的字首大寫: " + string.title()) | false |
b1e86e5e5afca3f2ec66a712d8f4e69b4da1391d | 107318041ZhuGuanHan/TQC-Python-Practice | /_4_control_procedure/406/main.py | 631 | 4.15625 | 4 | while True:
tall = int(input("請輸入身高(cm): ")) # 這兩個需要拿進來不然會變成無限迴圈
weight = int(input("請輸入體重(kg): ")) # 這兩個需要拿進來不然會變成無限迴圈
if (tall == -9999) or (weight == -9999):
break # 先判斷要不要跳出去
bmi = weight / ((tall / 100) ** 2) # 計算BMI
# 開始印出訊息
print("\nBMI: %.2f" % bmi)
if bmi >= 30:
print("State: fat")
elif bmi >= 25:
print("State: over weight")
elif bmi >= 18.5:
print("State: normal")
elif bmi < 18.5:
print("State: under weight") | false |
b332f04d284ba8a220a4a57b55f06498060ca9ff | 107318041ZhuGuanHan/TQC-Python-Practice | /_1_basic/104/main.py | 231 | 4.125 | 4 | import math
radius = float(input("請輸入圓形的半徑: "))
pi = math.pi
perimeter = 2 * pi * radius
area = pi * radius ** 2
print("Radius = %.2f" % radius)
print("Perimeter = %.2f" % perimeter)
print("Area = %.2f" % area)
| false |
29c9a27a0674471b14d22678093a521e0df0c405 | billcates/unscramble | /Task2.py | 938 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
ph={}
for each in calls:
if each[0] not in ph:
ph[each[0]]=int(each[3])
elif each[0] in ph:
ph[each[0]]+=int(each[3])
if each[1] not in ph:
ph[each[1]]=int(each[3])
elif each[1] in ph:
ph[each[1]]+=int(each[3])
longest= max(ph.items(), key=lambda x: x[1])
print("{} spent the longest time, {} seconds, on the phone during September 2016.".format(*longest))
| true |
cee5342793520076be418adddd4ed120be89aae2 | Kristin1800/CS330-Lab-1 | /FizzBuzz.py | 515 | 4.28125 | 4 | # Kristin Goselin - FizzBuzz Program
for num in range(1, 100): # A loop that goes through numbers 1 - 100
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz') # if the numbers are divisible by three or five print out FizzBuzz
elif num % 3 == 0:
print('Fizz') # if the numbers are divisible by three print out Fizz
elif num % 5 == 0:
print('Buzz') # if the numbers are divisible by five print out Buzz
else:
print(num) #otherwise print out the according number
| false |
a3d20188dd9f568a2ec147889bdba48b1b07c5a1 | roy2020china/BingDemo | /13_no_sublists.py | 1,027 | 4.3125 | 4 | # Write a procedure, input a list with sublist elements, and output a list with no sublists.
# 写一个函数,输入一个含有列表的列表,输出一个不含有列表的列表。
# input /输入:[1, [2, 0], [3, 0, [4, 7, 5]]]
# output /输出: x = [1, 2, 0, 3, 0, 4, 7, 5]
def get_final_list(a_list):
final_list = []
to_check = a_list
#print to_check
while to_check:
if isinstance(to_check[0], list) or isinstance(to_check[0], tuple):
new_list = to_check[0]
del to_check[0]
#print to_check
to_check = new_list + to_check # NOT to_check += new_list
#print to_check
else:
final_list.append(to_check[0])
del to_check[0]
#print final_list
return final_list
def is_sublist(i):
if isinstance(i, list) or isinstance(i, tuple):
return True
else:
return False
# x = [1, [2, 0], [3, 0, [4, 7, 5]]]
# print get_final_list(x)
# >>>[1, 2, 0, 3, 0, 4, 7, 5]
| false |
ffc7e6f0406acb70d750b90dd071fb0fd18af0bc | roy2020china/BingDemo | /2_string_search_operation.py | 806 | 4.34375 | 4 | # Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
# 定义一个名叫find_last的函数,传入两个参数均为字符串,一个是搜索字符串,另一个是目标字符串。
# 功能实现:目标字符串在搜索字符串中最后一次出现的位置;如果目标字符串从未出现过,则返回 -1。
#
def find_last(search_str, target_str):
start_index = search_str.find(target_str)
if start_index == -1:
return start_index
while start_index != -1:
last_index = start_index
start_index = search_str.find(target_str, start_index + 1)
return last_index
| false |
9411f243c1835f7d03b69d3d4ec7fcf024f7ca33 | biancaespindola/python | /desafio 009.py | 214 | 4.125 | 4 | #faça um programa que leia um número interio qualquer e mostre sua tabuada
number = int(input("Enter a number: "))
x = 1
while x <= 10:
print("{} x {} = {}".format(number,x,number*x))
x = x + 1
| false |
68d8239f896099599e2a4807fe4428a78b5736af | biancaespindola/python | /desafio 017.py | 355 | 4.25 | 4 | #faça um programa que leia o comprimento do cateto oposto e do adjacente de um triangulo retangulo e mostre
#o comprimento da hipotenusa
import math
oppositeSide = float(input("Enter the opposite side: "))
adjacentSide = float(input("Enter the adjacent side: "))
print("The hypotenuse is: {:.3f}".format(math.hypot(oppositeSide,adjacentSide))) | false |
256678a267a4f729e2851aa36af4dd7da5c279ca | Arulprasath36/pythonGettingStarted | /ExceptionHandlingExample.py | 821 | 4.46875 | 4 | """
The below method will throw an error ZeroDivisionError: integer division or modulo by zero
and our program will stop there itself without continuing.
"""
def divide(numerator,denominator):
return numerator/denominator
#print((divide(2,3)))
#print((divide(2,0)))
#print((divide(denominator=2,numerator=6)))
#But no matter what the exception our program should continue to do that
# we are going to handle the exception. Lets modify the above method a bit
def divideWithExceptionHandling(numerator,denominator):
try:
return numerator / denominator
except ZeroDivisionError:
print("Denominator should not be zero")
print((divideWithExceptionHandling(2,3)))
print((divideWithExceptionHandling(2,0)))
print((divideWithExceptionHandling(denominator=2,numerator=6)))
| true |
30eddbcf32c470872bdd4c2ea917553efa85cbcb | pim2066-cmis/pim2066-cmis-cs2 | /cs2quiz2.py | 1,790 | 4.28125 | 4 | #PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) 5 == 5
#b) 6 > 4
#c) "HELLO" != "pig"
#
#2) What does 'return' do?
# It calculates the function and then spits out the result of it
#
#
#
#3) What are 2 ways indentation is important in python code?
#a) 'group' the function together/ to see where it starts
#b) To make it easier to read the function
#
#
#PART 2: Reading
#Type the values for 9 of the 12 of the variables below.
#
#problem1_a) 36
#problem1_b) square root of 3
#problem1_c) 0
#problem1_d) 5 (wrong)
#
#problem2_a) True
#problem2_b) False
#problem2_c) False
#problem2_d) True
#
#problem3_a) 0.3
#problem3_b) 0.5
#problem3_c) 0.5
#problem3_d) 0.5
#
#problem4_a) 9 = 7
#problem4_b) 6 = 5
#problem4_c) 1.5 = 0.125
#problem4_d) 5.5 = 5
#
#PART 3: Programming
#Write a script that asks the user to type in 3 different numbers.
#If the user types 3 different numbers the script should then print out the
#largest of the 3 numbers.
#If they don't, it should print a message telling them they didn't follow
#the directions.
#Be sure to use the program structure you've learned (main function, processing function, output function)
def process(a ,b, c):
if a > b and a > c:
return a
elif b > a and b > c:
return b
elif c > a and c > b:
return c
else:
return False
#function for comparing the numbers
def main():
type_num = raw_input("Type in three different numbers")
int_1 = raw_input("A: ")
int_2 = raw_input("B: ")
int_3 = raw_input("C: ")
#int stands for the interger that will be typed into
result = "The largest number is {}". format(process)
print output(result)
def output(result):
if result == False:
print "You didn't follow instructions"
else:
print "The largest number is {}". format(process(a ,b, c))
main()
| true |
91f9a719c67594f53d9a710ef6ce672cc9f02b26 | ayeganov/Cracking | /chapter_one/1.8/rotated_string.py | 688 | 4.21875 | 4 | #!/usr/bin/env python
import argparse
def is_rotated(s1, s2):
if len(s1) != len(s2):
return False
return "".join(sorted(s1)).find("".join(sorted(s2))) == 0
def is_rotated_fast(s1, s2):
if len(s1) != len(s2):
return False
s3 = s1 + s1
return s3.find(s2) >= 0
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Determines whether two strings are rotations.")
parser.add_argument('-s1', type=str, required=True)
parser.add_argument('-s2', type=str, required=True)
args = parser.parse_args()
print "Strings %s and %s are rotations of each other: %s" % (args.s1, args.s2, is_rotated_fast(args.s1, args.s2))
| true |
927a5319d1a2a0b3a55b74869fe9d1ccfb48cb85 | amymareerobinson/cp1404practicals | /prac_03/practice_extension/scores.py | 1,211 | 4.15625 | 4 | """
CP1404 2020 - Practice and Extensions
Student Name: Amy Robinson
Program - Score Results
"""
import random
MINIMUM_SCORE = 0
MAXIMUM_SCORE = 100
OUTPUT_FILE = "results.txt"
def main():
"""generate score results for a number of scores and print to OUTPUT_FILE"""
number_of_scores = int(input("Enter number of scores: "))
out_file = open(OUTPUT_FILE, 'w') # opens 'OUTPUT_FILE' for writing
for number in range(number_of_scores):
score = display_random_score(MINIMUM_SCORE, MAXIMUM_SCORE)
score_result = return_score_result(score)
print(f"{score:2} is {score_result}", file=out_file)
out_file.close() # closes out_file variable
def return_score_result(score):
"""generate a score result for parameter score"""
if score < 0 or score > 100:
result = "Invalid score"
elif score >= 90:
result = "Excellent"
elif score >= 50:
result = "Passable"
else:
result = "Bad"
return result
def display_random_score(minimum_score, maximum_score):
"""display a random score between minimum_score and maximum_score"""
random_score = random.randint(minimum_score, maximum_score)
return random_score
main()
| true |
5bb35de313e98c61be0521addd9e9e83e24e9fee | amymareerobinson/cp1404practicals | /prac_01/loops.py | 540 | 4.21875 | 4 | """
CP1404 2020 - Practical 1
Student Name: Amy Robinson
Program - Loops
"""
for i in range(1, 21, 2):
print(i, end=' ')
print()
# a. Count in 10s from 0 to 100:
for i in range(0, 101, 10):
print(i, end=' ')
print()
# b. Count down from 20 to 1:
for i in range(20, 0, -1):
print(i, end=' ')
print()
# c. Print n stars:
number_of_stars = int(input("Number of stars: "))
for i in range(number_of_stars):
print("*", end='')
print()
# d. Print n lines of increasing stars:
for i in range(number_of_stars + 1):
print(i * "*")
| false |
7f66fc0832797c59e10f9951081e099153a2a43b | BimalDora/Python-Projects | /guess_the_number.py | 1,016 | 4.15625 | 4 | # Number Guessing Game
import time, random, math
print('***Welcome to Number Guessing Game***')
time.sleep(1)
lower = int(input("Enter lower bound: "))
upper = int(input("Enter upper bound: "))
secret_number = random.randint(lower, upper)
total_guess_allowed = round(math.log2(upper - lower + 1))
guess_taken = 1
while guess_taken <= total_guess_allowed:
print(f'You have {total_guess_allowed + 1 - guess_taken} guesses left to guess the correct number.')
try:
guess = int(input('Enter your guess: '))
except:
print('Hint: Enter a number nothing else.')
continue
if guess == secret_number:
break
elif guess > secret_number:
print('You Guessed too High.')
else:
print('You Guessed too Small.')
guess_taken += 1
if guess == secret_number:
print(f'\tCORRECT GUESS \n\tYou guessed the number in {guess_taken} guesses.')
else:
print(f'\tThe number is {secret_number}')
print('\tBetter Luck Next Time')
| true |
09ae57b5832a77dd276ea50cce7db7536b31559d | eshika93/Pythonclass | /inheritance.py | 1,204 | 4.1875 | 4 | # child class " IS A" parent class
# class Person:
# def __init__(self, name, contact):
# self.name = name
# self.contact = contact
# def walk(self):
# print(f"{self.name} is walking.")
# class Student(Person):
# def __init__(self, name, contact):
# super().__init__(name, contact)
# class Teacher(Person):
# def __init__(self, name, contact):
# super().__init__(name, contact)
# st = Student("ram", "12345")
# st.walk()
# t = Teacher("shyam", "543245")
# t.walk()
class Bird:
def __init__(self, name):
self.name = name
def fly(self):
print(f"{self.name} is flying.")
class Pigeon(Bird):
def __init__(self, name):
super().__init__(name)
class Osctich(Bird):
def __init__(self, name):
super().__init__(name)
def fly(self):
print(f"{self.name} could not fly.")
class Hummingbird(Bird):
def __init__(self, name):
super().__init__(name)
def fly(self):
super().fly()
print(f"{self.name} can also fly backward.")
p = Pigeon("sabin")
p.fly()
o = Osctich("monstor")
o.fly()
h = Hummingbird("sujan")
h.fly()
# p = Pigeon("saugat")
# p.fly() | false |
f5429642356d3d9cb997c3beae2a1588379c87c5 | Andrea-Wu/AlgoExamPrep | /bellman_ford.py | 1,493 | 4.375 | 4 | import math
def main(graph, target):
#implement Bellman-Ford algorithm
#wtf is the bellman ford algorithm
#for each vertex, send a "message" about the shortest path to that node that we know so far
#the order in which the messages are sent is fixed
#we must send |V|-1 messages (same as the # of nodes)
#first we should figure out how to represent this. I will use an "adjacency linked list"
#this example graph is taken from the emory website
#as you see, node 0 is connected to node 1 with weight 3
# and node 0 is connected to node 3 with weight 2
# and node 0 is connected to node 8 with weight 4
#([[[3,8],[1,4]] , [2,1] , [3,1] , []])
#for this example I'm going to assume this is a directed graph.
#actually i'm wondering if bellman ford has any purpose if the graph is acyclic
dist = {}
#init distance to source node = 0
dist[0] = 0
#initialize each distance to infinity? maybe not necessary?
for i in range(1,len(graph)):
dist[i] = math.inf
for i in range(len(graph) -1):
for node in range(len(graph) -1):
#send a message from each node to it's childs
for child in graph[node]:
childNum = child[0]
childDist = child[1]
dist[childNum] = min(dist[childNum], dist[node] + childDist )
return dist[target]
if __name__ == "__main__":
print(main([[[3,5], [1,4]], [[2,1]], [[3,1]], [[]]], 3))
| true |
8b38181f7bf647ae3d52b2db739483b879bd9fad | Adhi-github/learn_python_programme- | /Typecasting.py | 1,111 | 4.40625 | 4 |
'You Can to This typecasting method '
#typecasting means change The data type
'for example to Say :int to string (or)string to int '
#You can Do type casting Two way
'''1.directly change in variable
2.or You Can do in print statement '''
#directly change
y=6 - Just comment It Other wise You got error
name ='kutty'
'Now You can change in direct variable type '
y='6'
print (name+y) #return kutty6
#or You can change direct print statement
print (str(name +y)) #return kutty6
'escalating function '
#number of escalating parameters Are There '
'''
1.\n -return New line
2.\t -return 4 tab space
3.\\ -return \single backspace
4.\n\n -return Two line
5.\'-return single quotes
6.\"-return double quotes
'''
#\n escalating
print ('hi \n Hello ')#return hi and Hello in Two separate line
#\t escalating
print ('hi\t hello ')#return hi hello
#\' escalating
print ('hi\'Hello')#return hi'Hello
#Why ('' or "" )Are mentioned in print statement
'''*Because anything You written in print statement ,
print consider That Is string , so That Why You Have to Had It *'''
| false |
83c1e362073657f6fd1c8795193c554f9504ef19 | codio-content/cs-intro-python-conditionals | /.guides/example-code/fibonacci_example.py | 607 | 4.125 | 4 | fibcache = {} #dictionary of Fibonacci numbers
def fibonacci(n):
"""Check to see if a Fibonacci number has been calculated (in the dictionary).
If not, add it to the dictionary and return it.
If yes, return the number from the dictionary."""
if n not in fibcache.keys():
fibcache[n] = _fibonacci(n)
return fibcache[n]
def _fibonacci(n):
"""Calculate Fibonacci number"""
if n <= 1:
return n
else:
fib = fibonacci(n-1) + fibonacci(n-2)
return fib
fibonacci_length = 90
for num in range(fibonacci_length):
print(fibonacci(num))
| true |
a823d0d811f3b3c9b79d9e80cc6a2951b5d8d3f3 | codio-content/cs-intro-python-conditionals | /.guides/secure/recursive_tree_solution.py | 439 | 4.125 | 4 | import turtle
t = turtle.Turtle()
def recursive_tree(branch_length, angle, t):
"""Draw a tree recursively"""
if branch_length > 5:
t.forward(branch_length)
t.right(angle)
recursive_tree(branch_length - 15, angle, t)
t.left(angle * 2)
recursive_tree(branch_length - 15, angle, t)
t.right(angle)
t.backward(branch_length)
recursive_tree(45, 20, t)
turtle.mainloop() | false |
2b11c232e843408a985ef935f315e26fe438243a | king-ly/leetcode-python | /com/leetcode/arrays/order/88.py | 1,080 | 4.15625 | 4 | from typing import List
"""
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
归并排序
"""
i, j = 0, 0
while j < n:
if i >= m + j or nums1[i] > nums2[j]: #当i >=m+j的时候说明nums1已经遍历完了,就剩下nums2了
nums1.insert(i, nums2[j])
nums1.pop()
j += 1
i += 1
if __name__ == '__main__':
nums1 = [1, 2, 3, 0, 0, 0]
nums2 = [2, 5, 6]
Solution().merge(nums1, 3, nums2, 3)
print(nums1)
| false |
546365aecf570c612cab4de409aed4feabda968c | mauriziokovacic/ACME-Maya | /linspace.py | 592 | 4.1875 | 4 | def linspace(start, end, n, dtype=float):
"""
Returns a list of n even spaced scalars in range [start, end]
Parameters
----------
start : int or float
the starting value
end : int or float
the ending value
n : int
the number of scalars
dtype : type (optional)
the type of the scalars (default is float)
Returns
-------
list
a list of n scalars in range [start, end]
"""
r = [i / float(n - 1) for i in list(range(n))]
return [dtype((1 - t) * start + t * end) for t in r]
| true |
cbb127b45a3fe120482dafbda29cad2f287111b4 | brunofracalossi/codingExercises | /hackerrankChallenges/insertionsort1.py | 613 | 4.21875 | 4 | #https://www.hackerrank.com/challenges/insertionsort1
def printArray(array):
for i in xrange(len(array)):
print array[i],
print ""
def insertionSort(array):
value = array[len(array) - 1]
for i in xrange(len(array) - 2):
if value < array[i]:
position = i
break
size = len(array) - 2
while size >= position:
array[size + 1] = array[size]
size = size - 1
printArray(array)
array[position] = value
printArray(array)
m = input()
array = [int(i) for i in raw_input().strip().split()]
insertionSort(array)
| false |
2f3d37a0f0ed9d90e1ff3cbdeadf70bf2dac3d2d | bmuha1/princeton_algorithms | /2-stacks_and_queues/deque_list.py | 1,778 | 4.4375 | 4 | #!/usr/bin/python3
# Implement deque using list
class Deque:
# Implement deque using list
def __init__(self):
# Initialize deque
self.list = []
def is_empty(self):
# Is the deque empty?
return len(self.list) == 0
def size(self):
# Return the number of items on the deque
return len(self.list)
def add_first(self, item):
# Add the item to the front
if not item:
raise TypeError('Illegal argument')
self.list.insert(0, item)
def add_last(self, item):
# Add the item to the back
if not item:
raise TypeError('Illegal argument')
self.list.append(item)
def remove_first(self):
# Remove and return the item from the front
if self.is_empty():
raise IndexError('No such element')
return self.list.pop(0)
def remove_last(self):
# Remove and return the item from the back
if self.is_empty():
raise IndexError('No such element')
return self.list.pop()
def __str__(self):
# Print all the items in the deque
if self.is_empty():
return 'Deque is empty'
s = self.list[0]
for i in range(1, self.size()):
s += ', ' + self.list[i]
return s
if __name__ == '__main__':
l = Deque()
print(l, l.size(), l.is_empty())
l.add_last('dog')
print(l, l.size(), l.is_empty())
l.add_first('cat')
print(l, l.size(), l.is_empty())
l.add_first('ape')
print(l, l.size(), l.is_empty())
print(l.remove_last())
print(l, l.size(), l.is_empty())
print(l.remove_first())
print(l, l.size(), l.is_empty())
print(l.remove_first())
print(l, l.size(), l.is_empty())
| true |
57c796f3cb3c2b8d0bdf969cade91521ba471139 | bmuha1/princeton_algorithms | /2-stacks_and_queues/linked_stack_of_strings.py | 1,373 | 4.21875 | 4 | #!/usr/bin/python3
# Implement linked stack of strings
class Node:
# Implement node containing string
def __init__(self, s, next=None):
# Initialize node
self.item = s
self.next = next
class LinkedStackOfStrings:
# Implement linked stack of strings
def __init__(self):
# Initialize linked list
self.head = None
def __str__(self):
# Print linked stack of strings
if self.head is None:
return 'Empty list'
current = self.head
string = str(current.item)
while current.next is not None:
current = current.next
string += ' ' + str(current.item)
return string
def pop(self):
# Pop the first item
item = self.head.item
self.head = self.head.next
return item
def push(self, s):
# Push a string onto the stack
first = Node(s, self.head)
self.head = first
def is_empty(self):
# Check if linked stack is empty
return self.head is None
if __name__ == '__main__':
l = LinkedStackOfStrings()
l.push('to')
l.push('be')
l.push('or')
l.push('not')
l.push('to')
print(l.pop())
l.push('be')
print(l.pop())
print(l.pop())
l.push('that')
print(l.pop())
print(l.pop())
print(l.pop())
l.push('is')
| true |
fd9995f8f373859d96384d525892bced5dcc194b | bmuha1/princeton_algorithms | /2-stacks_and_queues/deque_linked_list.py | 2,718 | 4.21875 | 4 | #!/usr/bin/python3
# Implement deque using linked list
class Node:
# Implement node
def __init__(self, s, prev=None, next=None):
# Initialize node
self.item = s
self.prev = prev
self.next = next
def __str__(self):
# Print a node
return str(self.item)
class Deque:
# Implement deque using linked list
def __init__(self):
# Initialize deque
self.head = None
self.tail = None
def is_empty(self):
# Is the deque empty?
return self.head is None
def size(self):
# Return the number of items on the deque
size = 0
temp = self.head
while temp:
size += 1
temp = temp.next
return size
def add_first(self, item):
# Add the item to the front
if not item:
raise TypeError('Illegal argument')
new = Node(item, None, self.head)
if self.head:
self.head.prev = new
self.head = new
if not self.tail:
self.tail = new
def add_last(self, item):
# Add the item to the back
if not item:
raise TypeError('Illegal argument')
new = Node(item, self.tail, None)
if self.tail:
self.tail.next = new
self.tail = new
if not self.head:
self.head = new
def remove_first(self):
# Remove and return the item from the front
if self.is_empty():
raise IndexError('No such element')
first = self.head
self.head = self.head.next
if self.head:
self.head.prev = None
return first.item
def remove_last(self):
# Remove and return the item from the back
if self.is_empty():
raise IndexError('No such element')
last = self.tail
self.tail = self.tail.prev
if self.tail:
self.tail.next = None
return last.item
def __str__(self):
# Print all the items in the deque
if self.is_empty():
return 'Deque is empty'
temp = self.head
s = str(temp)
while temp.next:
temp = temp.next
s += ', ' + str(temp)
return s
if __name__ == '__main__':
l = Deque()
print(l, l.size(), l.is_empty())
l.add_last('dog')
print(l, l.size(), l.is_empty())
l.add_first('cat')
print(l, l.size(), l.is_empty())
l.add_first('ape')
print(l, l.size(), l.is_empty())
print(l.remove_last())
print(l, l.size(), l.is_empty())
print(l.remove_first())
print(l, l.size(), l.is_empty())
print(l.remove_first())
print(l, l.size(), l.is_empty())
| true |
b851e00162cfc5c80bb797cc07ba5ebd18c230e4 | veerajsolankee/Number-Guessing-Game | /97Project.py | 559 | 4.34375 | 4 | import random
number = random.randint(1, 9)
chances=0
print("Guess the number between 1 to 9 if you win you get a price if you lose you lose a chance you will get 5 chances ")
while chances < 5:
guess=int(input("enter your guess"))
if guess==number:
print("congratulation")
break
elif guess<number:
print("try a greater number ")
elif guess>number:
print("guess a lesser number ")
chances=chances-1
if chances>5:
print("Game Over.The correct answer is number",number )
| true |
465bc65123198aa8d8a436057f25f5b0dca80a5f | Harpal-Singh93/Python_course | /pythontutorial/recursivetut34.py | 1,166 | 4.53125 | 5 | # # factorial of a number using iterative approach
# ### as we know for calculating factorial of a number we use the formula
# ### n!=n*(n-1)*(n-2)....3*2*1
# ### n!=n*(n-1)!
# ### 0!=1
#
# # so this is iterative approach for calculating factorial
#
# def iterative_fun(n):
# if n==0:
# return 1
# else:
# fac=1
# for i in range(n):
# fac=fac*(i+1)
# return fac
#
# # this is recurisve approach
#
# def recursive_fun(n):
# if (n==0) or (n==1):
# return 1
# else:
# return n*recursive_fun(n-1)
#
# # inside working of recursive function like this example of 4!
# # 4*recursive_fun(3)
# # 4*3*recursive_fun(2)
# # 4*3*2*recursive_fun(1)
# # 4*3*2*1=24
#
# print('enter a number whose factorial you want')
# num=int(input())
# print(iterative_fun(num))
# print(recursive_fun(num))
#program for a fibonacci series 0,1,1,2,3,5,8,13,21,34,55 so on
def fibo_fun(num):
if (num==1):
return 0
elif (num==2):
return 1
else:
return fibo_fun(num-1)+fibo_fun(num-2)
print('enter the position which fibonacci number you want ')
num2=int(input())
print(fibo_fun(num2)) | false |
1a3c3777b5c7b942f18769197f0c617b870c9080 | sorsini4/PythonBaseball | /maps.py | 791 | 4.40625 | 4 | #strike_outs = [70, 98, 120, 84]
#def multiply_by_two(x):
# return x/2
#strike_out_values = map(multiply_by_two, strike_outs)
#strike_out_values = list(strike_out_values)
#map "maps" over a list and runs a function across said list. it returns a map object which is NOT iterable, but you can convert
#it to a list object to be able to be iterable. the below code is the same exact code with same output, just instead with a
#lambda expression
strike_outs = [70, 98, 120, 84]
strike_out_values = map(lambda x: x/2, strike_outs)
strike_out_values = list(strike_out_values)
print(strike_out_values)
#the syntax for writing lambda functions is rather simple, it is just lambda argument: return_value, you just specify the arg
#then how you want to manipulate that specific argument
| true |
111686de47b1e1d7ac2e675732965559443089b1 | MagickalWiz/python | /Algorithim.py | 738 | 4.15625 | 4 | print("Do you know the Answer to Life, the Universe, and Everything?")
print("Use numbers")
word1 = input("Enter the answer: ")
if (word1 == 42):
print("That is the Answer to Life, the Universe, and Everything.")
if (word1 != 42):
print("Do you even know the Question of Life, the Universe, and Everything?")
if (word1 == 2):
print("This is an answer to the false question created by the mice of Maragrathea.")
print("The Answer is Forty-two.")
word2 = input("Enter the number of roads a man must walk down: ")
if (word2 == 42):
print("You have failed. That was made up by the mice of Maragrathea.")
if (word2 != 42 or word2 == 1):
print("There is no right answer to this question."),
print("The mice made up that question.")
| true |
5e48b42e9c82bf933fbf7bad55734ae4df03ad07 | Ajay-droid-cmd/assignment_1 | /circle.py | 741 | 4.5 | 4 | ''' a) Write a Python program to calculate surface volume and area of a sphere
b) Write a Python program to calculate arc length of an angle. '''
import math
print("Surface volume& area of a sphere")
x=float (input("Enter the radius of the sphere"))
a=4*math.pi*x*x
v=4/3*math.pi*x*x*x
print("\nSurface volume = %2f"%a)
print("\nArea of sphere = %2f"%v)
# Write a Python program to calculate arc length of an angle
print("\n arc length ")
def arclength(d,a):
if a>=360 :
print("Angle cannot be formed")
return 0
else:
arc=(math.pi*d)*(a/360.0)
return arc
d=float(input("Enter the diameter"))
a= float(input("Enter the angle"))
arclen = arclength(d,a)
print(arclen)
| true |
4a9ebbfece893861bd983ed620bc9d046636823b | zaibabegum/basic-python-programs | /operators.py | 294 | 4.28125 | 4 | #operator- it is a special symbol that is used to perform arithmetic or logical operations
#addition,subrataction,multiplication ,division etc
x=1
y=2
z=3
res=x+y+z
print(res)
#concatenate strings
firstname="zaiba"
lastname="begum"
name=firstname +" "+ lastname
print("name:",name)
| true |
bcc88b891dbd5960b277bac87e875aa5bac32791 | alena22292/test-assignment | /tasksPython/ordering_num.py | 409 | 4.4375 | 4 | # Ordinal numbers indicate their position in a list, such as 1st or 2nd
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if nums:
for num in nums:
if num == 1:
print(str(num) + "st")
elif num == 2:
print(str(num) + "nd")
elif num == 3:
print(str(num) + "rd")
else:
print(str(num) + "th")
else:
print("The list of numbers is empty")
| true |
2edb258d7fe645ac8e5fc53f481d791f30914ab9 | LavanyaTulsian/Assignments | /Artificial Intelligence assignment-1 answer of question 2.py | 1,253 | 4.3125 | 4 | Q2. Develop a python code for the following example: A binary interactive system is provided with a series of information:
a. I am a human being
b. I am good
c. Good graders study well
d. Humans love graders
e. Every human does not study well
With the help of this information, where machine can only provide yes/no answer, solve the following query.
Is every human good grader? (4)
#ans:
print("only answer as yes or no")
l=[]
l2=[]
a=input("i am a human being: ")
if a!='yes' and a!='no':
print("wrong input")
exit()
else:
l.append(a)
b=input("i am good: ")
if b!='yes' and b!='no':
print("wrong input")
exit()
else:
l.append(b)
c=input("Good graders study well: ")
if c!='yes' and c!='no':
print("wrong input")
exit()
else:
l.append(c)
d=input("Humans love graders: ")
if d!='yes' and d!='no':
print("wrong input")
exit()
else:
l.append(d)
e=input("Every human does not study well: ")
if e!='yes' and e!='no':
print("wrong input")
exit()
else:
l.append(e)
print(l)
if l[0]=="yes" and l[1]=="yes" and l[2]=="yes" and l[3]=="yes" and l[4]=="no":
print("every human is good grader")
else:
print("No, every human is not a good grader")
| true |
e62b0e6398183a00e5c76f718f41b6ba91c00578 | Sai-nook73/TheAlgorithms | /SortingAlgorithms/ShellSort.py | 958 | 4.1875 | 4 | def shellSort(collection):
lenght = len(collection)
middle, counter = lenght // 2, 0
while middle > 0:
for i in range(0, lenght - middle):
j = i
while (j >= 0) and (collection[j] > collection[j + middle]):
temp = collection[j]
collection[j] = collection[j + middle]
collection[j + middle] = temp
j, counter = j - 1, counter + 1
print(" ", [counter], "-->", collection)
middle = middle // 2
return collection, counter
def visualization():
from random import randint
lenght = 10
collection = [randint(0, lenght) for i in range(lenght)]
print("Initial list:", collection)
print("Visualization of algorithm work.")
collection, counter = shellSort(collection)
print("Final list:", collection)
print("Total numbers of passages:", counter)
def main():
import timeit
elapsedTime = timeit.timeit(visualization, number = 1)
print("Elapsed time: ", round(elapsedTime, 3), "sec.")
if __name__ == '__main__':
main() | true |
c7de0aa7c760aa27dff7a9d22d32e0e76cda764c | CelvinBraun/hangman_cli | /hangman/hangman/main.py | 1,354 | 4.125 | 4 | import random
import hangman_art as art
import hangman_words as words
end_of_game=0
#Random chose of word out of hangman_word.py
while end_of_game!="1":
chosen_word = random.choice(words.word_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6
print(art.logo)
display = []
for _ in range(word_length):
display += "_"
while not end_of_game:
#Input letter
guess = input("Guess a letter: ").lower()
if guess in display:
print(f"You already used the letter: {guess}")
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
#Check if user is wrong.
if guess not in chosen_word:
print(f"{guess} isn´t in the word!")
lives -= 1
if lives == 0:
end_of_game = True
print(art.stages[0])
print("You lose.")
end_of_game=int(input("'1' for another round, '2' for exit."))
print(f"{' '.join(display)}")
if "_" not in display:
end_of_game = True
print("You win.")
end_of_game=int(input("'1' for another round, '2' for exit."))
print(art.stages[lives]) | true |
34b8332a7411188a5cfa32f45c7222b4a6cb008d | scoutmcfall/salesperson-report | /sales_report.py | 1,974 | 4.1875 | 4 | """Generate sales report showing total melons each salesperson sold."""
#--------------------
#open the sales report file
f = open('sales-report.txt')
melon_dict = {}
for line in f:#for each line in the file, split it up by |
line = line.rstrip()
entries = line.split('|')#now we have a list called entries for each line in the text file
for i in range(len(entries)-2):#populate the dictionary with names as keys
key= entries[0]
melon_dict[key] = melon_dict.get(key, []) #search the dict for names and put a list if no name
melon_dict[key].append(float(entries[i+1]))#if the name is in there, put the next two items in entries
melon_dict[key].append(int(entries[i+2]))#what if there's more entries?
for name, value in melon_dict.items():
total_cost = sum(value[0::2])
total_count = sum(value[1::2])
print(name.upper()) #prints name in uppercase
print(f'sold ${total_cost}: {total_count} melons')
print("====================")
#-------------------------------
#make empty lists for salespeople and melons sold
# salespeople = []
# melons_sold = []
# salesperson = entries[0]#assign the 0th item to salesperson
# melons = int(entries[2])#assign the int value of the 2nd item to melons
# if salesperson in salespeople:#if the salesperson is already in salespeople list
# position = salespeople.index(salesperson)#assign position to the index of salesperson in salespeople
# melons_sold[position] += melons#add the int value of melons to the melons sold list to the person at their index
# else:
# salespeople.append(salesperson)#otherwise, add the salesperson to the salespeople list
# melons_sold.append(melons)#and add the melons value to the melons sold list
# for i in range(len(salespeople)):#iterate through the salespeople list
# print(f'{salespeople[i]} sold {melons_sold[i]} melons')#and print out how many melons each person sold
| true |
dab6b3a6fbd94e074388dc818315315d8ffaac78 | py1-10-2017/rgero215_PY1-10-2017 | /Multiples Sum Average/multiple_sum_average.py | 945 | 4.71875 | 5 | """
Multiples
Part I - Write code that prints all the odd numbers from 1 to 1000.
Use the for loop and don't use a list to do this exercise.
Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
Sum List
Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]
Average List
Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3]
"""
#odd numbers from 1 to 1,000
for counter in range(1, 1000):
if counter % 2 == 1:
print counter
#multiples of 5 from 5 up to 1,000,000 not including 1,000,000
#to include 1,000,000 I can subtitude 1000000 for 1000001
for counter in range(5, 1000000):
if counter % 5 == 0:
print counter
#sum of elements on list a
a = [1, 2, 5, 10, 255, 3]
result = 0;
for item in a:
result += item
print result
#average of list a
avg = 0
for item in a:
avg += item
print avg / len(a)
| true |
0e363717d5b8ebb034c7b4b5475b143e4c72b238 | Code-Institute-Submissions/Amzzy78-quiz_game | /run.py | 2,972 | 4.1875 | 4 | # ---------------------------------
def new_game():
guesses = []
correct_guesses = 0
question_num = 1
# Nested for loop
for key in questions:
print("-----------------------------")
print(key)
for i in options[question_num-1]:
print(i)
# User input and prompt.
guess = input("Enter (A, B, C, D):\n ")
guess = guess.upper()
guesses.append(guess)
# Fill in the check_answer function and pass the key for current question and guess function.
correct_guesses += check_answer(questions.get(key),guess)
# Increment each question number after each iteration.
question_num += 1
# Display the final score outside the for loop.
display_score(correct_guesses, guesses)
# Set up parameters for the check_answer function
# ---------------------------------
def check_answer(answer, guess):
if answer == guess:
print("CORRECT!")
return 1
else:
print("WRONG!")
return 0
# ---------------------------------
def display_score(correct_guesses, guesses):
print("-----------------------------")
print("RESULTS")
print("-----------------------------")
print("Answers: ", end="")
# Display questions loop
for i in questions:
print(questions.get(i), end=" ")
print()
print("Guesses: ", end="")
# Display guesses loop
for i in guesses:
print(i, end=" ")
print()
score = int((correct_guesses/len(questions)) * 100)
print("Your score is: "+str(score)+"%")
# ---------------------------------
def play_again():
response = input("Do you want to play again? (yes or no):\n")
response = response.upper()
if response == "Yes":
return True
else:
return False
# ---------------------------------
questions = {
"Who trained for 20 years in subjects such as law, astronomy, philosophy, poetry, medicine, music, geometry divination, and magic?: ": "A",
"What is a common ancient Irish beverage used also for ritual where it would be spiked with certain herbs ?: ": "B",
"In Irish Folklore what was eaten eaten by the Salmon, fished up by the druid, and cooked by young Finn, who, as sorcerer’s apprentice, burns his thumb on the Salmon’s skin, sticks thumb in mouth, and attains all the wisdom in his master’s stead?: ": "C",
"In Irish Mythology what is the name of the story of the son of a warrior chieftain, who experiences an ‘Isle of intoxicating wine fruits’ during his journey to avenge his father’s death?: ": "A",
}
options = [["A. Druids", "B. Fionn mac Cumhaill", "C. Michael D Higgins", "D. Biddy Early"],
["A. Poitin", "B. Mead", "C. Guinness", "D. Whiskey"],
["A. Algae", "B. Seaweed", "C. Hazelnuts", "D. Potatoes"],
["A. The Voyage of Máel Dúin", "B. Tír na nÓg", "C. The Children of Lir", "D. Táin Bó Cúailnge"]]
# Call the new_game function to begin a new game
new_game()
while play_again():
new_game()
print("Bye!") | true |
09864a8ec62fae0093ab5edbab9d7ee8330c7a60 | joelburton/bst-practice | /traverse.py | 1,181 | 4.25 | 4 | """Traverse binary trees."""
from bst import bst
def preorder(node):
"""Pre-order traversal of tree.
This works out to be "top-down, left-to-right"
>>> preorder(bst)
5 3 1 0 4 7 6 9
"""
if node is None:
return
print node.data,
preorder(node.left)
preorder(node.right)
def postorder(node):
"""Post-order traversal of tree.
This works out to be "bottom-up, left-to-right"
>>> postorder(bst)
0 1 4 3 6 9 7 5
"""
if node is None:
return
postorder(node.left)
postorder(node.right)
print node.data,
def inorder(node):
"""In-order traversal of tree.
>>> inorder(bst)
0 1 3 4 5 6 7 9
"""
if node is None:
return
inorder(node.left)
print node.data,
inorder(node.right)
def rev_inorder(node):
"""Reverse in-order traversal of tree.
>>> rev_inorder(bst)
9 7 6 5 4 3 1 0
"""
if node is None:
return
rev_inorder(node.right)
print node.data,
rev_inorder(node.left)
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "w00t!" | true |
1d9357ff5e25aaf3b99e4f25f65cda574bebf9a5 | Wesleycampagna/study_of_ia | /gradiente_cost/gradiente.py | 1,811 | 4.25 | 4 | """ A ideia e fazer o gradiente para 2x^3 + 3x^2 + 2 """
#base foi deste rapaz: https://github.com/codificandobits/Programacion_Gradiente_Descendente_en_Python/blob/master/gradiente_descendente.py
import matplotlib.pyplot as plt
from numpy import linspace
#teta_jota = teta_jota - alpha * termo de derivacao --> formula
#logo a derivada para a funcao e 3*2x^2 + 2*3x + 3 = 6x^2 + 6x (flutua muita casa nao da)
teta_jota = 100
alpha = 0.0095 #alpha's para teste = 1.0, 0.15 0.025 0.0025
#iterations = 1000
casas_decimais = 7
it = []
y = []
def grad_(it, y_v):
iterator = 0
new_teta_jota = teta_jota
old_teta_jota = teta_jota -1 #diferente pra entra no while
#for i in range (iterations):
while new_teta_jota != old_teta_jota:
# f(x) e sua derivada -> onde é x substitui por 'new_teta_jota'
f_x = round(new_teta_jota**2 + 1, casas_decimais)
derivada = 2*new_teta_jota
old_teta_jota = new_teta_jota
new_teta_jota = round(new_teta_jota - alpha * derivada, casas_decimais)
print('x: ', new_teta_jota, 'f(x): ', f_x, 'x$: ', old_teta_jota)
y_v.append(f_x)
it.append(iterator+1)
iterator += 1
if iterator == 1000:
print('\n--> NAO CONVERGIU EM 1000 TENTATIVAS!')
break
return iterator
iterations = grad_(it, y)
plt.subplot(1, 2, 1)
plt.plot(it, y)
plt.xlabel('x')
plt.ylabel('f(x)')
X = linspace(-3,3,iterations)
Y = X**2 + 1
plt.subplot(1,2,2)
plt.plot(X,Y,0.0,1.0,'ro')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
#(((6*x) ** 2) + (6*x) + 3)
""" SERIA EQUIVALENTE
f_x = round((((2*new_teta_jota) **3) + ((3*new_teta_jota) ** 2) + 3), 4)
derivada = round((((6*new_teta_jota) **2) + (6*new_teta_jota)), 4) """
| false |
1a706c5003eb90c1624d4014eadcf1d72ca6cc8b | rupeshjaiswar/Learning | /python-learning/complex_number.py | 384 | 4.15625 | 4 |
x = complex(input("Enter 1 complex number:"))
print("Complex Number x:", x)
y = complex(input("Enter 2 complex number:"))
print("Complex Number y:", y)
print("Addition of two Complex Number:", x + y)
print("Subtraction of two Complex numbers:", x - y)
print("Multiplication of two complex numbers:", x * y)
print("Division of two complex numbers:", x / y)
| false |
9342592a58ed1105387644481191e4af542279ac | katamit/dataStructure_practices | /Data_structure_and_alogirthm_in_python_by_Michael_Goodrich/ch2/Range.py | 1,211 | 4.375 | 4 | ''' This the demonstration of range function in python'''
class Range:
"""A class that mimic's the built-in range class"""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance
Semantic is similar to built-in range class
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop == None:
stop, start = start, 0 # special case of range(n)
#calculate the effective lenght once
self._length = max(0, (stop -start + step -1)//step)
# need knowledge to start and step(but not stop) to support __getitem__
self._start = start
self._step = step
def __len__(self):
"""Return number of entries in the range"""
return self._length
def __getitem__(self, k):
"""Return entry at index k(using standar interpreation if negative)"""
if k < 0:
k += len(self) #attempt to convert negative index; depends on __len__
if not 0 <= k < self._length:
raise IndexError('index out of range')
return self._start + k*self._step
#------------------------------------------------------------------------------------------
def test():
r = Range(8, 140, 5)
print(r)
print(len(r))
print(r[25])
print(r[-1])
if __name__ == "__main__":
test() | true |
98efd02a9e5b7cedb374bfb7c5cfcb316e132612 | Pratik110/Python | /Array/Max_Sum_Sub_Array.py | 1,927 | 4.15625 | 4 | Algorithm = "Kadane's Algorithm"
Link = "https://leetcode.com/problems/maximum-subarray/"
Logic = "https://youtu.be/w_KEocd__20"
Description = "Given an integer array nums, find the contiguous subarray " \
"(containing at least one number) which has the largest sum " \
"and return its sum."
Example_1 = "Input: nums = [-2,1,-3,4,-1,2,1,-5,4]" \
"Output: 6" \
"Explanation: [4,-1,2,1] has the largest sum = 6."
Example_2 = "Input: nums = [5,4,-1,7,8]'" \
"Output: 23"
nums = [-2,1,-3,4,-1,2,1,-5,4]
# Approach 1
# Brute Force solution in BigO(n^3)
class Solution1:
def maxSubArray(self, nums):
maxm = 0
l = len(nums)
for i in range(l):
for j in range(i,l):
subArraySum = self.sum(nums[i:j+1])
if subArraySum > maxm:
maxm = subArraySum
return maxm
def sum(self,array):
s = 0
for i in array:
s+=i
return s
print(Solution1().maxSubArray(nums))
# Approach 2
# Optimization of the Brute Force solution by reducing
# the time complexity to BigO(n^2) from BigO(n^3)
class Solution2:
def maxSubArray(self,nums):
maxm = 0
l = len(nums)
for i in range(l):
s = 0
for j in range(i,l):
s+=nums[j]
if s>maxm:
maxm = s
return maxm
print(Solution2().maxSubArray(nums))
# Approach 3
# Solving the problem using Kadane's Algorithm which reduces the time complexity to BigO(n)
class Solution3:
def maxSubArray(self,nums):
currSum = 0
maxSum = nums[0]
l = len(nums)
for i in range(l):
currSum+=nums[i]
if currSum > maxSum:
maxSum = currSum
if currSum < 0:
currSum = 0
return maxSum
print(Solution3().maxSubArray(nums)) | true |
77cf740bbfe8a2273711462616098233a37e84fe | Pratik110/Python | /Array/Matrix/Rotate_Matrix.py | 1,554 | 4.25 | 4 | Link = "https://leetcode.com/problems/rotate-image/"
Description = "You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise)." \
"You have to rotate the image in-place, which means you have to modify the input 2D matrix directly." \
"DO NOT allocate another 2D matrix and do the rotation."
Example = "Input: matrix = [[1,2,3]," \
" [4,5,6]," \
" [7,8,9]]" \
"" \
"Output: [[7,4,1]," \
" [8,5,2]," \
" [9,6,3]]"
# Approach 1
# We're going to first transpose the matrix then flip it, that'll get the job done.
class Solution1:
def rotate(self,matrix):
# Step 1 : Transpose the matrix
r = len(matrix)
c = len(matrix[0])
for i in range(r):
for j in range(i,c):
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp #instead of going through the traditional method of swapping, we can simply do
#matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j], i.e, a,b = b,a
# Step 2 : Flip the matrix
for i in range(r):
for j in range(c//2):
temp = matrix[i][j]
matrix[i][j] = matrix[i][c-j-1]
matrix[i][c - j - 1] = temp
return matrix
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
print(Solution1().rotate(matrix))
| true |
42d7264f9b5b1259ffdac0fbcefc886781d96078 | KingFoofle/Python-Practice | /Problem2/Problem2.py | 825 | 4.25 | 4 | import test_Problem2
# Given a 2D Array, return the sum of the DIAGONAL numbers
# For example, [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9] <--- This is a 3x3 matrix.
# ]
# The diagonal would be 1, 5, 9 = 15
# HINT: Assume that the matrix will always be nxn
def diagonalSum(matrix):
pass
# ------- DO NOT EDIT THE CODE BELOW -------
def main():
try:
test_Problem2.Test().test_diagonal_sum()
except AssertionError as e:
print(e)
print("Your code must pass all tests to succeed. Try again!")
else:
print("Congratulations! You passed!")
print("\nTry another version of this problem at:")
print("https://www.hackerrank.com/challenges/diagonal-difference/problem")
print("------------------------------------")
if __name__ == "__main__":
main() | true |
fb931d1d17115203f35c10052921e3e6a37c6a17 | SaintClever/Python-and-Flask-Bootcamp-Create-Websites-using-Flask- | /_Python Crash Course/47. Hints and Help for Function Tasks.py | 1,164 | 4.5 | 4 | # Hints and Help for Function Tasks
# Hi there!
#
# Up next are your function tasks. I want to quickly mention a few functions that may be useful to you that you may not have seen yet. Specifically these functions will be useful for Task #7 , the last task.
#
# The modulus operator
#
# This % mod operator returns back the remainder after a division. For example 3 divided by 2 and be shown to be 1 remainder 1. Since 2 goes into 3 one time, with a remainder of 1 (2+1=3). You can use the % operator in Python to view the remainder. For example:
#
# 3 % 2
#
# returns 1
#
# 17 % 15
#
# returns 2 (since its the remainder after the division of 17/15)
#
# 100 % 10
#
# returns 0, since 10 goes into 100 evenly.
#
# This is really useful for figuring out if a number is even or not. You just simply check if the number % 2 returns 0. If it does, then its even.
def even_check(num):
if num % 2 == 0:
print("Number was even")
else:
print("Odd number")
The sum() # function
# Just like max() and min(), Python also has a built in sum() function that can return the sum() of all the numbers in a list.
sum([1,2,3,4]) # will return back 10.
| true |
027c4f993deef0ee4e546b117a9010c4e525c5ae | Prince345/Plastic-Pollution | /Hunter.py | 2,276 | 4.1875 | 4 | ''' This is the beginning of the scenario in which the picars demonstrate the
human race first entering the equation and how they interact with the oceans.
The picars will go along and fish in the oceans as "humans".
For this scene set a paper with a spear on it to show the picar
as a human that is spear fishing.
'''
STARTING_SPEED = 50
import comm
import Pyro4
import traceback
import picar
from picar.obstacle_sensor import *
from picar.front_wheels import *
from picar.back_wheels import *
import time
steering = Front_Wheels() # create a Front_Wheels object for steering the car
motors = Back_Wheels() # create a Back_Wheels object to move the car
objSensor = Obstacle_Sensor() # create an Object_Sensor() object to detect distance to objects
picar.setup()
steering.ready()
motors.speed = STARTING_SPEED
motors.ready()
#class HuntingDance:
@Pyro4.expose
def fisherman():
''' This is as if a human is looking around in the water
for the fish, waiting for an opportunity.
'''
motors.stop()
for i in range(2):
steering.turn(140)
time.sleep(2)
steering.turn(40)
time.sleep(2)
steering.turn_straight()
motors.speed = 90
motors.forward()
time.sleep(1)
motors.stop()
motors.speed = 50
#Sound to be implemented
@Pyro4.expose
def caughtFish():
''' This is the fish squirming as it gets caught before dying.
'''
motors.stop()
motors.speed= 15
motors.forward()
for i in range(3):
steering.turn_left()
time.sleep(1)
steering.turn_right()
time.sleep(1)
steering.turn(140)
steering.turn(110)
time.sleep(1)
motors.stop()
motors.speed= 50
steering.turn_straight()
@Pyro4.expose
def failedCatch():
''' This is the audio played when the human
fails to catch the fish he has spotted.
'''
motors.stop()
#Wiggle
for i in range(2):
steering.turn_left()
time.sleep(0.5)
steering.turn_right()
time.sleep(0.5)
steering.turn_straight()
motors.speed = 90
motors.backward()
time.sleep(3)
motors.stop()
motors.speed= 50
'''if __name__ == "__main__":
comm.startServer("10.33.22.155","PicarHunter",{"HuntingDance",HuntingDance})
'''
| true |
c18798cd49e9e5c6e170ae9eb45442082a08a55b | bcsaldias/syllabus-1 | /Actividades/AC04/main.py | 1,067 | 4.25 | 4 | # coding=utf-8
# Completen los métodos
# Les estamos dando un empujoncito con la lectura del input
# Al usar la clausula: "with open('sonda.txt', 'r') as f", el archivo se cierra automáticamente al salir de la función.
def sonda():
with open('sonda.txt', 'r') as f:
for line in f:
pass
def traidores():
with open('bufalos.txt', 'r') as f:
for line in f:
pass
with open('rivales.txt', 'r') as f:
for line in f:
pass
def pizzas():
with open('pizza.txt', 'r') as f:
for line in f.read().splitlines():
pass
if __name__ == '__main__':
exit_loop = False
functions = {"1": sonda, "2": traidores, "3": pizzas}
while not exit_loop:
print(""" Elegir problema:
1. Sonda
2. Traidores
3. Pizzas
Cualquier otra cosa para salir
Respuesta: """)
user_entry = input()
if user_entry in functions:
functions[user_entry]()
else:
exit_loop = True
| false |
5c77c101066c914396571b6e5da960505e36427d | vitdanilov/python_devops | /dev/1/task6.py | 1,099 | 4.28125 | 4 | # 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня,
# на который результат спортсмена составит не менее b километров.
# Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня.
a = float(input("Введите сколько км спортсмен пробежал за первый день : "))
b = float(input("К какому результату в км стремится спортсмен? : "))
c = a
i = 1
while c<b:
c = c + a*10/100;
i += 1
# print("День {}".format(i))
# print("Расстояние {}".format(c))
print("Номер дня: {}".format(i)) | false |
44aa6e9e852c2828eda465e6f3abb04256e72d0a | vitdanilov/python_devops | /dev/4/task4_2.py | 773 | 4.21875 | 4 | # 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
# Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
# Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55].
# Результат: [12, 44, 4, 10, 78, 123].
first_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
second_list = [x for i,x in enumerate(first_list) if i > 0 and first_list[i] > first_list[i - 1]]
print(second_list)
| false |
53676f7a7cc95d61b67dd68a4455975f4c7b12f7 | Parthi96/Python_training | /regex.py | 301 | 4.1875 | 4 | import re
text = 'My number is 123-4567-8901.'
phoneNumber = re.compile(r'(\d\d\d)-(\d\d\d\d-\d\d\d\d)')
phone = phoneNumber.search(text)
print('Phone Number STD code is ' + phone.group(1))
print('Phone Number without STD is ' + phone.group(2))
print('Phone Number with STD code is ' + phone.group()) | false |
5a0bddc4ac77d031a9a1a1072053031ea320ad34 | Viola8/Python-Exercises | /str_palindrom.py | 398 | 4.40625 | 4 | # Ask the user for a string and print out whether this string is a palindrome or not.
# (A palindrome is a string that reads the same forwards and backwards.)
# good only for a word:
user_string = (input("Please write a string: ")
new_string=user_string[::-1]
if new_string == user_string:
print("Wow! This is a palindrom!")
else:
print("Thank you for the participation!")
| true |
8fa7dc8672f4ab49221075fb7d623da0066f844a | Viola8/Python-Exercises | /lst4.py | 744 | 4.15625 | 4 | # Write a Python program to get the difference between the two lists.
list1 = [1,2,3,4,5,6,7]
list2 = [2,3,4,8,9]
for i in list1:
if i not in list2:
print(i)
#or
list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))
total_diff = diff_list1_list2 + diff_list2_list1
print(total_diff)
# Write a Python program to remove duplicates from a list.
list1 = [1,2,3,4,4,5,5,5]
set_list1 = set(list1)
print(list(set_list1))
#or
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
| true |
4f6eed87fd970d2460900f6d1b9e8d113a90b073 | Viola8/Python-Exercises | /collections.py | 1,151 | 4.375 | 4 | # Write a Python program to get the frequency of the elements in a list.
import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print("Original List : ",my_list)
freq = collections.Counter(my_list)
print("Frequency of the elements in the List : ",freq)
# Write a Python program to find all anagrams of a string in a given list of strings using lambda.
from collections import Counter
texts = ["bcda", "abce", "cbda", "cbea", "adcb"]
str = "abcd"
print(list(filter(lambda x: (Counter(str) == Counter(x)), texts)))
# Write a Python program to combine two dictionary adding values for common keys.
from collections import Counter
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter(d2)
print(d) # Counter({'b': 400, 'd': 400, 'a': 400, 'c': 300})
# Write a Python program to find the highest 3 values in a dictionary.
from collections import Counter
d3 = {'a': 12, 'b': 24, 'c':36, 'd':48, 'e':60, 'f':72}
k = Counter(d3)
high = k.most_common(3) # Finding 3 highest values
for i in high:
print(i[0]," :",i[1]," ")
# Output:
# f : 72
# e : 60
# d : 48
| true |
02e28d29957f3c61123db972d82c213a0908026e | Viola8/Python-Exercises | /lambda6.py | 1,590 | 4.25 | 4 | # Write a Python program to sort each sublist of strings in a given list of lists using lambda.
lst = [['orange','green'], ['black', 'white'], ['white', 'black', 'orange']]
ordered_sublists = [sorted(w,key = lambda w: w[0]) for w in lst]
print(ordered_sublists) # [['green', 'orange'], ['black', 'white'], ['black', 'orange','white']]
# Write a Python program to sort a given list of lists by length and value using lambda.
lst2 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]]
print(sorted(lst2, key = lambda l: (len(l), l))) # [[0], [2], [0, 7], [1, 3], [9, 11], [13, 15, 17]]
# Write a Python program to find the maximum value in a given heterogeneous list using lambda.
list1 = ['Python', 3, 2, 4, 5, 'version']
print(max(list1, key = lambda w: (isinstance(w, int), w))) # output: 5
# Write a Python program to sort a given matrix in ascending order according to the sum of its rows using lambda.
list2 = [[1, 2, 3], [2, 4, 5], [1, 1, 1]]
list3 = [[1, 2, 3], [-2, 4, -5], [1, -1, 1]]
print(sorted(list2, key=lambda i: sum(i)))
print(sorted(list3, key=lambda i: sum(i)))
# Write a Python program to extract specified size of strings from a give list of string values without lambda and with Lambda.
list4 = ['Python', 'list', 'exercises', 'practice', 'solution']
# without lambda
extracted_words = []
for w in list4:
if len(w)==8: # length of the string to extract is 8
extracted_words.append(w)
print(extracted_words) # ['practice', 'solution']
# with lambda
print(list(filter(lambda x: len(x) == 8, list4))) # ['practice', 'solution']
| true |
f52e2a26800a690ad9482b161777b5c403de979d | Viola8/Python-Exercises | /str3.py | 558 | 4.5 | 4 | # Write a Python program to convert the given string to list.
str1 = "Convert a string to a list"
print(str1.split())
def Convert_str_to_lst(string):
lst = list(string.split(" "))
return lst
str1 = "Convert a string to a list"
print(Convert_str_to_lst(str1))
# 2
def Convert_str_to_lst(string):
lst = list(string.split("-"))
return lst
str1 = "Convert-a-string-to-a-list"
print(Convert_str_to_lst(str1))
# 3
def Convert(string):
list1=[]
list1[:0]=string
return list1
str1="ABCD"
print(Convert(str1))
| true |
4c5aa2bdff628ba22491f8d116ce50915f87a1bc | DamianNery/Tecnicas-De-Programacion | /5Mayo/09/AdivinaNumero.py | 734 | 4.25 | 4 | #!/usr/bin/env python3
#8 Hacer un programa que genere un número de N cifras y pregunte al usuario
#números hasta que lo adivine. Mostrar la cantidad de intentos usados para
#adivinar el número.
import random
def AdivinarNro():
N=int(input("Ingrese la cantidad de cifras: "))
numero=intentos=0
usuario=" "
for i in range (N):
numero+=random.randrange(0,10)*(10**i)
# print(numero) //para saber que numero es antes del while
numero=str(numero)
while (usuario!=numero):
usuario=str(input("Ingrese numero: "))
intentos+=1
print("La cantidad de intentos fue de %d veces" % intentos)
print("El numero es: " + usuario)
AdivinarNro()
| false |
c46f5094d450704a45b87f6b4e900d4dc77bacad | ikonstantinov/python_everything | /apr20/lazy_expr.py | 889 | 4.125 | 4 | """
ленивые вычисления
"""
def infinity_list():
i = 0
while True:
yield i
i += 1
g = infinity_list()
print(next(g))
for i in infinity_list():
if i*i > 50:
break
else:
print(i, i*i)
"""itertools examples"""
import itertools
d = itertools.takewhile(lambda x: x < 50, (x * x for x in itertools.count(0)))
print(list(d))
"""алгоритм сжатия: groupby -> itertools"""
l = [0] * 5 + [1] * 2 + [0] * 3 + [1] * 5
for i, j in itertools.groupby(l):
print(i, len(list(j)))
"""решето Эратосфена, см в книге"""
def filter_multi(n, gen):
for i in gen:
if i % n:
yield i
def get_prime():
c = itertools.count(2)
while 1:
prime = next(c)
c = filter_multi(prime, c)
yield prime
c = list(itertools.islice(get_prime(), 0, 10))
print(c) | false |
dd1ae04397f5107a7bdd996530bbe0cbbc1746ae | DurodolaBolu/Python-Crash-Course | /finishing.py | 1,873 | 4.125 | 4 | # function to find the square root of any number
import math
def square_root():
n = int(input('Enter the number you want to find the square root: '))
return math.sqrt(n)
print(square_root())
# function to get input from a user and greet them in upper case
def get_input():
name = input('please enter your name: ')
return name
def greet_user():
greet = get_input()
greeting = f'you are welcome {greet}'
return greeting.upper()
print(greet_user())
# program to pick two numbers randomely and find the square of the other.
from random import randint
x = randint(1,10)
y = randint (2,5)
print (x**y)
# program to find factors of a number and their products
class Factor():
def __init__(self, number):
self.number = number
def factors(self):
facts = []
for each_num in range(1,self.number+1):
if self.number%each_num == 0:
facts.append(each_num)
return facts
def factor_multiplier(self):
multiplier = 1
for each_num in range(1,self.number+1):
if self.number%each_num == 0:
multiplier *= each_num
return multiplier
numb = int(input('enter the number you want to find its factor product: '))
Object1 = Factor(numb)
print(Object1.factors())
print(Object1.factor_multiplier())
# A dice rolling simulator having sides 10 and 20 each and roll the dice 10 times
from random import randint
class Dice:
def __init__(self, sides1 = 10, sides2 = 20):
self.die1 = sides1
self.die2 = sides2
def roll_dice(self):
counter = 0
roll_limit = 10
while counter < 10:
die1 = randint(1,self.die1)
die2 = randint(1,self.die2)
print(f'you rolled {die1} and {die2}')
counter +=1
my_dice = Dice()
my_dice.roll_dice()
| true |
04c64155089309f27522cd59a659f1eaa82e3040 | Srialok01/Python_Practise | /12_GuessingGame_WhileLoop.py | 485 | 4.28125 | 4 | """
Problem statement : Set a secret no , Ask people to guess the secret no in 3 Chances,
If guessed correctly print - You are right else print you are out of chances
"""
secret_Number = 9
guess_count = 3
guess_chance = 0
while guess_chance < guess_count:
answer = int(input(" Guess the number between 1 to 9 :"))
guess_chance += 1
if answer == secret_Number:
print("Whoaaa !!! You guessed it right ")
break
else:
print(" You are out of chances !!!")
| true |
7cdad4039f8a97aa7b9af011a435851cb1d0d8ba | mbasnet201819/Lab | /Lab/Convert Sec to day.py | 334 | 4.34375 | 4 | ### WAP to convert sec to day, hour, minutes and seconds
second = float(input("Enter the time in seconds: "))
day= (((second//60)//60)//24)
print(f"Total day for given seconds: {day}")
hour= ((second//60)//60)
print(f"Total hours for given seconds: {hour}")
minute = (second)//60
print(f"Total minute for given seconds: {minute}") | true |
3d55149f2a25fa6ec5e03baefe3e0a8e4ab9aebf | sahilrl/University | /python/fibonacci_binet.py | 737 | 4.1875 | 4 | '''Fibonacci number at nth position. This program calculate the
fibonacci number at nth position using Binet's Formula.
The positional value is taken as user input n. '''
def restart():
n = input("Please enter the postional value to check Fibonacci number: ")
if n.isdigit() is True:
n = int(n)
c = (((1 + 5**.5) / 2)**n - ((1 - 5**.5) / 2)**n) / 5**.5
print("The fibonacci number at position " + str(n) + " is " + str(c))
else:
print("Please try again...")
restart()
restart()
while True:
print("Do you want to check on another position?(y/n) ")
i = input()
if i in ("si", "da", "yes", "y"):
restart()
else:
print("Goodbye!")
break
| true |
ded0efa8234496b87c6062d734766e31d6833d35 | nwrunner/CodeFightChallenges | /firstNotRepeatingCharacter.py | 960 | 4.21875 | 4 | '''
Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you would be asked to do during a real interview.
Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example
For s = "abacabad", the output should be
firstNotRepeatingCharacter(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
For s = "abacabaabacaba", the output should be
firstNotRepeatingCharacter(s) = '_'.
There are no characters in this string that do not repeat.
'''
def firstNotRepeatingCharacter(s):
s_len = len(s)
while s_len > 0:
next_char = s[0]
s = s.replace(next_char, "")
new_len = len(s)
if (new_len + 1 == s_len):
return next_char
s_len = new_len
return "_"
| true |
7c1d6f231300dee654d59c33d068ac73849de698 | Mallik-G/dataload | /utils/utils.py | 2,969 | 4.25 | 4 | import copy
import os
import time
def merge_dicts(a, b):
"""
Recursively merge 2 dictionaries. This does not use deepcopy (performance
is too slow for large data) and thus it will modify the dict in place.
Args:
a - The primary dictionary
b - The dictionary to merge into a
Returns:
A new dictonary with b merged into a
Example:
>>> merge_dicts(_, [])
[]
>>> a, b = {'a': 1}, {'b': 2}
>>> c = merge_dicts(a, b)
>>> c == {'a': 1, 'b': 2} and (a is c) and (a is not b) and (b is not
c)
True
>>> merge_dicts({'a':{'b':2, 'c':3}}, {'a':{'b':4, 'd':5}})
{'a': {'c': 3, 'b': 4, 'd': 5}}
"""
if not isinstance(b, dict):
return b
result = a
for k, v in b.items():
if k in result and isinstance(result[k], dict):
result[k] = merge_dicts(result[k], v)
else:
result[k] = v
return result
def expand_objects(record):
"""
Expand attributes expressed in dot-notation and merge back into dictionary.
Args:
a - The primary dictionary
b - The dictionary to merge into a
Returns:
A new dictonary with b merged into a
Example:
>>> a = {"foo.bar": "hello", "foo.baz": "world!"}
>>> b = expand_objects(a)
>>> b == {"foo": {"bar": "hello", "baz": "world!"}}
True
"""
new_record = copy.deepcopy(record)
for key, value in record.items():
parts = key.split(".")
if len(parts) > 1:
parts.reverse()
current = {parts[0]: value}
for part in parts[1:]:
current = {part: current}
del new_record[key]
new_record = merge_dicts(new_record, current)
return new_record
def count_lines_in_file(file, ignore_header=True):
"""
Counts number of records in a file. This assumes each record is defined in
a single line. Similar but not limited to CSV files. By default, consider
and ignores the header row (First row) from the count.
Args:
file - Path to file
ignore_header - If True, ignores first line in count. If False, returns
count of all lines in file
"""
count = sum(1 for _ in open(file,encoding="utf-8"))
if ignore_header:
return count - 1
return count
def delete_file(file, logger):
if os.path.exists(file):
logger.info("Deleting file")
os.unlink(file)
def rate_limiter(start_time, min_execution_time):
"""
As a very crude rate limiting mechanism, sleep if processing the batch
did not use all of the minimum time.
Args:
start_time - to calculate the total amount of time spent.
min_time - the minimum time a api call should wait
"""
execution_time = time.time() - start_time
if execution_time < min_execution_time:
time.sleep(min_execution_time - execution_time)
| true |
f42f7c9eeebaa7920a23c8537ea2931bb86ca051 | Vlek/course_automate_the_boring_stuff | /lesson_11/exceptionhandling.py | 733 | 4.1875 | 4 | """
lesson 11: try and except statements
the try and except statements allow one to write code that will be
able to handle exceptions and do something different when it's
the case that one occurs.
"""
from typing import Union
def divideBy(x) -> Union[int, float, None]:
try:
return 42 / x
except ZeroDivisionError:
print("Error: attempted to divide by zero")
def numCats() -> None:
num = input("How many cats do you have?")
try:
if int(num) >= 4:
print("That is a lot of cats")
else:
print("That is not that many cats.")
except ValueError:
print("You did not enter a number")
if __name__ == "__main__":
print(divideBy(0))
numCats()
| true |
a20168838abf8f8db481596e9c0a83922b7e9ea5 | MarcisGailitis/12-Beginner-Python-Projects | /hangman.py | 1,199 | 4.125 | 4 | guess_word = True
guess_letter = True
while guess_word:
counter = 0
word_out = []
guessed_letters = list()
word = input('Enter the word for hangman game: ')
letter_list = set(word)
print(f'\nCurrent word: {"* " * len(word)}')
while guess_letter:
print(
f'\nYou have used following letters: {", ".join(guessed_letters)}')
counter += 1
input_letter = input(
f'Try Nr {counter}. Enter a letter or quit to exit: ')
if input_letter == 'quit':
break
if input_letter in guessed_letters:
print('You already guessed that letter')
else:
guessed_letters.append(input_letter)
for letter in word:
if letter in guessed_letters:
word_out.append(letter)
else:
word_out.append('*')
print(f'\nCurrent word: {" ".join(word_out)}')
if letter_list == set(word_out):
print('Success!')
guess_letter = False
word_out.clear()
cont = input('Another (y/n)?: ')
if cont in ('n', 'no'):
guess_word = False
| false |
9adba2cb9dba73a50fa5d38c6739c00267a1b5d3 | VeeraPrathapSelenium/PythonRegularSession | /Operators/TempData.py | 266 | 4.125 | 4 | x,y=10,20
if x>y:
print("X is greater than Y and the value of X is :{xvalue} The value of Y is :{yvalue}".format(xvalue=x, yvalue=y))
else:
print("Y is greater than X and the value of X is :{xvalue} The value of Y is :{yvalue}".format(xvalue=x, yvalue=y))
| true |
70cc4e336e8815b80a44d40f846c263abafa7743 | frclasso/Apresentacao_Biblioteca_Padrao_Python_Unifebe_2018 | /03_Math/02_cgd_sqrt.py | 820 | 4.125 | 4 | #!/usr/bin/env python3
import math
# raiz quadrada / square root
print(f"Raiz quadrada: {math.sqrt(64)}")
print()
# Potencia pow()
# print(f"Tres ao quadrado: {3 ** 2}")
# print(f"Tres ao quadrado utilizando math.pow(): {math.pow(3,2)}")
"""MDC (Maximo Divisor Comum -
GCD(GCD Greatest common denominator)"""
# Definindo uma função tradicional
# def mdc(dividendo,divisor):
# if divisor == 0:
# return dividendo
# return mdc(divisor, dividendo % divisor)
# print()
#
# print(f'MDC 10 e 5 ==> {mdc(10, 5)}')
# print(f'MDC 32 e 24 ==> {mdc(32, 24)}')
# print(f'MDC 5 e 3 ==> {mdc(5, 3)}')
# print()
#
# # Utilizando a função math.gcd()
# print(f"GCD de 10 e 5 ==> {math.gcd(10, 5)}")
# print(f"GCD de 32 e 24 ==> {math.gcd(32, 24)}")
# print(f"GCD de 5 e 3 ==> {math.gcd(5, 3)}")
# print()
#
| false |
d867f8c96a0cc54fb2c988732f6464d4346930c5 | NicolasAbroad/automate-the-boring-stuff | /cat names checker | 619 | 4.21875 | 4 | #!python 3
# Cat names checker - enter cat names into list, then compare inputted name to list.
cat_names = []
while True:
print ('Enter name of cat ' + str(len(cat_names) + 1) +
' (Or enter nothing to stop.); ')
name = input()
if name == '':
break
cat_names += [name]
for s in range(len(cat_names)):
print(cat_names[s])
def check(list): #Checks if name is present in list
name = input('Enter name to check if in list: ')
if name in list:
print(name + ' is in list.')
else:
print(name + ' is not in list.')
check(cat_names)
input('Press enter to exit.')
| true |
b36e6566e52ed75725d8cd16c6385a17ed0f25fe | cmdellinger/Google-challenges | /2018/bomb_baby/problem 5 RuntimeError.py | 1,385 | 4.125 | 4 | """
Google Problem 5: Bomb, Baby!
Written by cmdellinger
Usage:
import solution
answer(M, F)
Returns a string number of generation cycles required to generate #M and #F bombs.
1. Each generation cycle, either:
M bombs can generate F bombs
OR
F bombs can generate M bombs
2. If the amount of M and F bombs can't be generated return "impossible"
"""
def answer(M = '', F = ''): # -> string
''' returns number of generation cycles as a string needed to generate the passed M and F bombs '''
goal = {M: int(M), F: int(F)}
def step(counter = (0,0,0)): # -> int
''' description '''
def gen_M(counter = ()): # -> int
gen_counter = (counter[0]+1, counter[1]+counter[2], counter[2])
return step(gen_counter)
def gen_F(counter = ()): # -> int
gen_counter = (counter[0]+1, counter[1], counter[1]+counter[2])
return step(gen_counter)
if counter[1] == goal[M] and counter[2] == goal[F]:
return counter[0]
elif counter[1] > goal[M] or counter[2] > goal[F]:
return -1
else:
return max(gen_M(counter), gen_F(counter))
steps = step((0,1,1))
if steps == -1:
return "impossible"
else:
return str(steps)
#print answer("2","1")
#print answer("4","7")
| true |
c62e31828f2f0e6a078322e2f726d3495bf8fdc5 | dylantho/pytho189 | /Module_6/more_functions/inner_functions_assignment.py | 1,567 | 4.5 | 4 | """
Program: inner_functions_assignment.py
Author: Dylan Thomas
Last date modified: 10/05/2020
"""
def measurements(a_list):
"""This function creates a statement of the perimeter and area of a square or rectangle
:param a_list, a list of one or two numbers
:returns A statement of the area and perimeter
"""
width = 0
length = a_list[0]
if len(a_list) == 2:
width = a_list[1]
def area(a_list):
"""This function takes in a list to calculate the area of a rectangle or square
:param a_list, a list of one or two numbers
:returns The area of the rectangle or square
"""
areaCalc = 0
if len(a_list) == 1:
areaCalc = length * length
elif len(a_list) == 2:
areaCalc = length * width
else:
print("There should only be one or two values.")
return areaCalc
def perimeter(a_list):
"""This function takes in a list to calculate the perimeter of a rectangle or square
:param a_list, a list of one or two numbers
:returns The perimeter of the rectangle or square
"""
perimeterCalc = 0
if len(a_list) == 1:
perimeterCalc = length * 4
elif len(a_list) == 2:
perimeterCalc = (length * 2) + (width * 2)
else:
print("There should only be one or two values.")
return perimeterCalc
listPerimeter = str(perimeter(a_list))
listArea = str(area(a_list))
return "Perimeter = " + listPerimeter + " Area = " + listArea
| true |
7fdd96b1f6412914552a4272d370bd621b83c561 | PauraviW/leetcode-problems | /HashTable_Questions/Easy/DesignHashMap706.py | 1,400 | 4.15625 | 4 | import collections
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashTable = {}
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
self.hashTable[key] = value
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
if key in self.hashTable:
return self.hashTable[key]
else:
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
if key in self.hashTable:
del self.hashTable[key]
# Your MyHashMap object will be instantiated and called as such:
obj = MyHashMap()
obj.put(1,1)
param_2 = obj.get(6)
print(param_2)
obj.remove(2)
hashMap = MyHashMap()
hashMap.put(1, 1);
hashMap.put(2, 2);
print(1,hashMap.get(1)); # returns 1
print(3, hashMap.get(3));
print(2, hashMap.get(2));# returns -1 (not found)
hashMap.put(2, 1); # update the existing value
print(2, hashMap.get(2));
hashMap.remove(2); # remove the mapping for 2
print(2, hashMap.get(2));
hashMap.get(2); # returns -1 (not found)
print(2, hashMap.get(2)); | true |
432db8cab8b5a105dc9b8b1ff6c4dcf51888c955 | amiaopensource/characterization_compare | /helpers/Search.py | 764 | 4.125 | 4 | def search_dict(my_dict, field):
"""Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in my_dict.iteritems():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
results = search_dict(value, field)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = search_dict(item, field)
for another_result in more_results:
fields_found.append(another_result)
return fields_found | true |
1afabaf1d95e8f6d332ed3d06ab9b7578da7e669 | alexisjcarr/Data-Structures | /stack/stack.py | 2,994 | 4.34375 | 4 | """
A stack is a data structure whose primary purpose is to store and
return elements in Last In First Out order.
1. Implement the Stack class using an array as the underlying storage structure.
Make sure the Stack tests pass.
2. Re-implement the Stack class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Stack tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Stack?
"""
# class Stack:
# def __init__(self):
# self.storage = []
# self.size = len(self.storage)
# def __len__(self):
# return self.size
# def push(self, value):
# self.storage.append(value)
# def pop(self):
# if self.size == 0:
# return
# return self.storage.pop(-1)
class Stack:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def __len__(self):
return self.size
def push(self, value):
self.size += 1
self.storage.add_to_head(value)
def pop(self):
if self.size == 0:
return
self.size -= 1
return self.storage.remove_head()
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_to_head(self, value):
new_node = Node(value)
if self.head is None and self.tail is None:
self.head = new_node
self.tail = new_node
else:
new_node.next_node = self.head
self.head = new_node
def add_to_tail(self, value):
new_node = Node(value)
if self.head is None and self.tail is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next_node = new_node
self.tail = new_node
def remove_head(self):
if not self.head:
return None
if self.head.next_node is None:
head_value = self.head.value
self.head = None
self.tail = None
return head_value
head_value = self.head.value
self.head = self.head.next_node
return head_value
def contains(self, value):
if self.head is None:
return False
current_node = self.head
while current_node is not None:
if current_node.value == value:
return True
current_node = current_node.next_node
return False
def get_max(self):
if self.head is None:
return None
current_node = self.head
current_max = self.head
while current_node is not None:
if current_node.value > current_max.value:
current_max = current_node
current_node = current_node.next_node
return current_max.value
| true |
845576bf6602e7eadc1043aa70943988b678926e | Idreesqbal/PythonTutorial | /11AdvancedFileObjects.py | 1,036 | 4.3125 | 4 | with open('test.txt', 'r') as f: # it is always a good practice to open files like this
f = open('test.txt', 'r') # this also a way to work with files but the problem is
f.mode
f.close() # if u forget to put this at the end of file operation, the file may go to error
# to make sure our file handeling is in the safe hands, it is always recommended to do it with 'with'
with open('text.txt', 'r') as f:
f_contents = f.readlines() # reads the line of the file all
f_contents = f.readline() # will read only the first line of the text
f_contents = f.read() # this will read the entire text all at once
# read() take arguments, e.g. read(100) will paste the first 100 character of the text
f.seek(0) # it basically put the cursor back to position 0 everything we loop the text
print(f_contents)
import os
os.chdir('Location of the file')
for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
f_title, f_course, f_num = file_name.split('-')
print('{}-{}-{}{}'.format((file_name, f_title))) | true |
ea553280d829cd5012a391919780cce2d10bf4ba | cs50nestm/create | /grade.py | 1,348 | 4.1875 | 4 | from cs50 import get_int
import time
def main():
# Instructions for user
print("\nCONVERT YOUR NUMBER GRADES TO A LETTER AVERAGE!\n")
# Check for valid input
while True:
n = get_int("Number of Grades: ")
if 0 < n < 10:
break
print("Please enter number between 1 and 9.")
# Create grades list and add numeric grades
grades = []
for i in range(n):
grades.append(get_int(f"Number Grade {i + 1}: "))
# A fun device to humanize computer
print("\nCalculating...\n")
time.sleep(1)
# Call to letter function and assign return value
letter_average = letter(grades)
# Final output is letter grade
print("Letter Grade:", letter_average)
# Calculate letter grade
def letter(grades):
# Initialize sum to zero
sum = 0
# Iterate through grades list and add each to sum
for grade in grades:
sum += grade
# Computer average numeric grade
average = sum / len(grades)
# Assign appropriate letter grade, depending on average
if average >= 90:
letter_avg = 'A'
elif average >= 80:
letter_avg = 'B'
elif average >= 70:
letter_avg = 'C'
elif average >= 65:
letter_avg = 'D'
else:
letter_avg = 'F'
# Return the letter grade
return letter_avg
main()
| true |
1dfe4e835db1711dcc7e27de9cb3b79c2c6b1f38 | nitin989/pythonic | /src/python/exercise22.py | 285 | 4.5625 | 5 | # define a function that takes list of strings
# list containing reverse of each strings
# use list comprehension
# l = ['abc','xyz','pqr']
# reverse_string(l) --- ['cba','zyx','rqp']
def reverse_list(l):
return [s[::-1] for s in l]
l = ['abc','xyz','pqr']
print(reverse_list(l)) | true |
b699c9e8c32aeaf18502d3dd340435e7c42b49d9 | nitin989/pythonic | /src/python/70_decorators_into.py | 966 | 4.5625 | 5 | # first class functions/ closures
# then we finally learn about decorators
def square(a):
return a**2
s = square # u assign square to a variable , not calling square
print(s(7))
print(s.__name__)
print(s) ## <function square at 0x000002B6919D2F28>
print(square) ## <function square at 0x000002B6919D2F28>
## decorators : enhance the functionality of another function
# @ used for decorators
def decorator_func(any_func):
def wrapper_func():
print("This is awesome function")
any_func()
return wrapper_func
@decorator_func ## syntactic sugar
def func1():
print ("This is function 1 ")
@decorator_func
def func2():
print ("This is function 2 ")
func1()
func2()
# call function 1 or func2 and print another line " this is awesome function" without
# changing code of func1 or func2
# this can be done using decorators
decorator_func(func1)
func1 = decorator_func(func1)
func1()
func2 = decorator_func(func2)
func2() | true |
5edd0e3df179f9a99164f13faa97ab62c9dc6884 | nitin989/pythonic | /src/python/exercise15.py | 496 | 4.375 | 4 | # Ask user for number of elements he wants to print in a fibonacci series and print the elements
def fibonacci_seq(n):
a = 0
b = 1
if n == 1:
print (a)
elif n == 2:
print(a , b) # 1,2
else:
print (a,b, end = " ")
for i in range(n-2):
c = a + b
a = b
b = c
print(b , end = " ")
input_num = int(input("Please enter number of elements of fibonacci series :- ").strip())
fibonacci_seq(input_num) | true |
9636089ddab859f340ad4e72045019f32e7821a1 | nitin989/pythonic | /src/python/63_iterator_vs_iterable.py | 591 | 4.375 | 4 | # iterator vs iterable
numbers = [1,2,3,4] #iterables
squares = map(lambda a:a**2,numbers) # iterators
for i in squares:
print(i)
for i in numbers:
print(i)
# step 1 : call iter function
# iter(numbers) ---> iterator
# next(iter(numbers))
number_iter =iter(numbers)
print(number_iter) #<list_iterator object at 0x000002887BDA44E0>
print(next(number_iter)) ## this will give 1
print(next(number_iter)) ## this will give 2
print(next(number_iter)) ## this will give 3
print(next(number_iter)) ## this will give 4
#print(next(number_iter)) ## this will give StopIteration
| false |
4f13444b294a887da0f7ec3d8722b29ddd270cde | nitin989/pythonic | /src/python/14_string_methods.py | 889 | 4.40625 | 4 | name = "NiTiN cHoUdHaRy"
# 1. len() function
print(len(name))
# 2. lower() method
print(name.lower())
# 3. upper() method
print(name.upper())
# 4. title() method
print(name.title())
# 5. count() method
print(name.count("i"))
# 6. understanding strip methods
name = " Nitin "
dots = "............."
print (name + dots)
print (name.lstrip() + dots)
print (name.rstrip() + dots)
print (name.strip() + dots)
# 7. understand replace methods
name = " Nit in "
print (name.replace(" ","")+dots)
string = "she is beautiful and she is good dancer"
print(string.replace("she","Nidhi"))
print(string.replace("she","Nidhi",1))
# 8. find() method
print(string.find("is"))
print(string.find("is",14))
print(string.find("is",string.find("is")+1))
# 9. understand center method
name = "Nitin"
print(name.center(11,"*"))
name = input("Enter your name : ")
print(name.center(len(name)+8,"*")) | false |
13bfb17b6daa3230bbc709e07a1e6d17d4afd338 | nitin989/pythonic | /src/python/56_args_with_normal_parameter.py | 481 | 4.125 | 4 | # *args with normal parameter
def multiply_nums(num , *args):
multiply = 1
print(num)
print(args)
for i in args:
multiply *= i
return multiply
print(multiply_nums(2,2,3))
def multiply_nums1(*args):
multiply = 1
print(args)
for i in args:
multiply *= i
return multiply
l = [1,2,3,4,5,6,7,8,9,10]
print(multiply_nums1(l)) # this will not consider elements of list nstead will treat list as whole
print(multiply_nums1(*l)) | true |
972651ed4f70e863a1b8736a78f6e474a1221b7c | courtneyholcomb/lazy-lemmings | /lemmings.py | 1,689 | 4.25 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
>>> furthest_optimized(7, [0, 6])
3
>>> furthest_optimized(3, [0, 1, 2])
0
>>> furthest_optimized(3, [2])
2
>>> furthest_optimized(3, [0])
2
>>> furthest_optimized(6, [2, 4])
2
"""
def furthest(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
farthest = 0
for hole in range(num_holes):
lowest_dist = num_holes - 1
for cafe in cafes:
dist = abs(hole - cafe)
if dist < lowest_dist:
lowest_dist = dist
if lowest_dist > farthest:
farthest = lowest_dist
return farthest
def furthest_optimized(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
end = num_holes - 1
farthest = 0
for i in range(len(cafes)):
# if first cafe, get distance to start
if i == 0:
dist = cafes[i] - 0
# else get distance to last cafe, halved
else:
dist = (cafes[i] - cafes[i - 1]) // 2
# if last cafe, get distance to end
if i == len(cafes) - 1:
end_dist = end - cafes[-1]
if end_dist > dist:
dist = end_dist
if dist > farthest:
farthest = dist
return farthest
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED; GREAT JOB!\n")
| true |
c59b5db0c8fff44f578537481ee12dc58b565596 | JohnsonLi/graphics_engine_work | /02 -- mks66-matrix/matrix.py | 1,445 | 4.40625 | 4 | """
A matrix will be an N sized list of 4 element lists.
Each individual list will represent an [x, y, z, 1] point.
For multiplication purposes, consider the lists like so:
x0 x1 xn
y0 y1 yn
z0 z1 ... zn
1 1 1
"""
import math
#print the matrix such that it looks like
#the template in the top comment
def print_matrix( matrix ):
output = ''
for i in range(4):
for j in range(len(matrix)):
output += str(matrix[j][i]) + ' '
output += '\n' if i != 3 else ''
print(output)
#turn the parameter matrix into an identity matrix
#you may assume matrix is square
def ident( matrix ):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if(i == j):
matrix[i][j] = 1
else:
matrix[i][j] = 0
#multiply m1 by m2, modifying m2 to be the product
#m1 * m2 -> m2
def matrix_mult( m1, m2 ):
res = []
for row in m1:
new = []
for i in range(len(m2[0])):
sum = 0
for j in range(len(row)):
sum += row[j] * m2[j][i]
new.append(sum)
res.append(new)
for i in range(len(m2)):
for j in range(len(m2[0])):
m2[i][j] = res[i][j]
# print(m2)
def new_matrix(rows = 4, cols = 4):
m = []
for c in range( cols ):
m.append( [] )
for r in range( rows ):
m[c].append( 0 )
return m
| true |
437b8db7edb512d4c5779084e20a5b6db46c6820 | Artarin/Python-Trashbox | /equal_numbers.py | 458 | 4.3125 | 4 | #Даны три целых числа. Определите, сколько среди них совпадающих.
# Программа должна вывести одно из чисел: 3 (если все совпадают),
# 2 (если два совпадает) или 0 (если все числа различны).
a= int(input())
b= int(input())
c= int(input())
if a==b==c:
print (3)
elif a==b or b==c or a==c:
print (2)
else:
print (0)
| false |
a9c376a2a370b5e0642af6f8832c26f9f88185db | IamKuldeep/RailwaySeatpositioning | /Railway.py | 1,067 | 4.15625 | 4 | print ("welcome to Railway enquiry System._/\_")
name = input("What's your name?:-")
x = int(input("Please enter seat number:-"))
if x>72:
print (name," Invalid Seat Number!! Try Again..")
elif x%8==0:
print (name," your seat no.",x," is Side Upper Berth. in front of ",(x-1))
elif (x+1)%8==0:
print (name," your seat no.",x," is Side Lower Berth. in front of ",(x+1))
elif (x+2)%8==0:
print (name," your seat no.",x," is Upper Berth facing towards engine. in front of ",(x-3))
elif (x+3)%8==0:
print (name," your seat no.",x," is Middle Berth facing towards engine. in front of ",(x-3))
elif (x+4)%8==0:
print (name," your seat no.",x," is Lower Berth facing towards engine. in front of ",(x-3))
elif (x+5)%8==0:
print (name," your seat no.",x," is Lower Berth facing opposite engine. in front of ",(x+3))
elif (x+6)%8==0:
print (name," your seat no.",x," is Middle Berth facing opposite engine. in front of ",(x+3))
else:
print (name," your seat no.",x," is Upper Berth facing opposite engine. in front of ",(x+3))
| false |
f1f4baf81d20fd4912b53ef6c472231d76b97f70 | JEU18/CryptographyExercises | /Exercise3_4_Elgamal.py | 2,732 | 4.375 | 4 | # Jenna Uba February 25, 2019
# This program uses Elgamal's Encryption method to take a message that is inputted by a user and encrypt it.
# The program also uses Elgamal's Decryption method to take a message and decrypt it.
# Function One: This is a function that calculates that converts the power value into a binary (represented as a string
# for comparison purposes. It then uses this binary value to help efficiently compute the moded exponent expression
def fast_powering(b, p, m):
power_bin = str(bin(p)[:1:-1])
multipliers = []
answer = 1
for digit in range(0, len(power_bin)):
if power_bin[digit] == '1':
calculation = (b**(2**digit)) % m
multipliers.append(calculation)
for value in range(0, len(multipliers)):
answer *= multipliers[value]
return answer % m
# Function Two: This is a function that finds the power by subtracting two from the inputted modulo value. This
# function then calls the fast powering algorithm function to compute the result.
def fast_inverse(a, m):
p = m - 2
return fast_powering(a, p, m)
# Function Three: Encrypts the inputted message. C1 and C2 are both computed and returned.
def encrypt(p, g, public_a, m):
k = 197
c_1 = fast_powering(g, k, p)
c_2 = (m * fast_powering(public_a, k, p)) % p
cipher_m = [c_1, c_2]
return cipher_m
# Function Four: Decrypts the inputted message. C1 and C2 are used to compute the decrypted message
def decrypt(p, g, a, c):
c_1 = int(c[0])
c_2 = int(c[1])
c_1_a = fast_powering(c_1, a, p)
inverse = fast_inverse(c_1_a, p)
cipher_c = (c_2 * inverse) % p
return cipher_c
# Function Five: Determines if the user would like to encrypt or decrypt a message. This is where inputs are taken
# from the user. Depending on the users inputs another function is called and its results are printed.
def run():
action = input("Choose option 1 or 2\n1. Encrypt\n2. Decrypt\n")
prime = int(input("Enter Prime: "))
element = int(input("Enter Element: "))
if action == "1":
action_2 = input("Choose option 1 or 2\n1. Enter Public Key\n2. Use Default Public Key: 224\n")
if action_2 == "1":
key_public = int(input("Enter Public Key: "))
else:
key_public = 224
message = int(input("Enter Message: "))
print("The Encrypted Message is: ", encrypt(prime, element, key_public, message))
else:
key_private = int(input("Enter Private Key: "))
cipher_str = input("Enter Cipher Text is form C1 C2: ")
cipher = [int(x) for x in cipher_str.split()]
print("The Decrypted Message is: ", decrypt(prime, element, key_private, cipher))
run()
| true |
92dbaa45aafe90962192996ce7bf747240a3ad59 | iamnst19/python-advanced | /Fundamentals_First/boolean_comp/and_or.py | 958 | 4.28125 | 4 | ## programming Age question
age = int(input("Enter your age:"))
can_learn_programming = age > 0 and age < 150
print(f"You can learn programming: {can_learn_programming}")
## Working problem
age = int(input("Enter your age:"))
#usually_not_working = age < 18 or age > 65
# not using a negative
usually_working = age >= 18 and age <= 65
print(f"At {age}, you are usually working: {usually_working}.")
## Print Bool
print(bool(35))
print(bool("Jose"))
## Print
print(bool(0))
print(bool(""))
x = True and False
print(x)
x = False or True
print(x)
x = 35 or 0
print(x)
## Program with or
name = input("Enter your name: ")
surname = input("Enter your surname: ")
greeting = name or f"Mr. {surname}"
print(greeting)
## Not
print(not bool(35))
print(not 35)
# If the value on the left of the `and` operator is truthy, we get the value on the right of the operator.
x = True
cmp = x and 18
print(cmp) | true |
68cb19fd474fe6bb4ac51a4f07a1a49ed90d82e1 | RakaChoudhury/Cerner_2-5-Coding-Competition | /Substring.py | 341 | 4.1875 | 4 | #cerner_2^5_2019
# function to check if substring is present in a string or not
def check(string, sub_str):
if (string.find(sub_str) == -1):
print("NO")
else:
print("YES")
# driver code
fullString =input("Enter full string:")
subString =input("Enter substring:")
check(fullString, subString)
| true |
e4652808def9da3fa9ce10fdc508b2d1e419be33 | HamzaBhatti125/Python-Programming | /CP-project/nthpower.py | 206 | 4.25 | 4 | nth_power=1
while nth_power:
integer=int(input('enter number '))
nth_power=int(input('enter power '))
answer=integer**nth_power
print("Answer of ",integer,"**",nth_power," is ",answer)
| true |
81ace0d367f3aef9debc0c0d8273b90e61216409 | yunliqing/java_python_go_share | /2020-03/2020-0327/test.py | 421 | 4.375 | 4 | # 三元运算符就是在赋值变量的时候,可以直接加判断,然后赋值
#
# 三元运算符的功能与'if....else'流程语句一致,它在一行中书写,代码非常精炼,执行效率更高
#
# 格式:[on_true] if [expression] else [on_false]
#
# res = 值1 if 条件 else 值2
a = 2
b = 5
val = a if a > b else b
print(val) # 5
val = a if a < 3 else b
print(val) # 2 | false |
355b8dfc1ded9c8f72b949cb9562b34c21bb2f36 | jiangha4/CambiaHealthSolutions | /Programming/CambiaAssignment.py | 1,355 | 4.1875 | 4 | #!/usr/local/bin/python
# -----------------------------------------------------------------------------
# Cambia Health Solutions Assignment
# Author: David Jiang
# Email: davidjiang.haohan@gmail.com
# -----------------------------------------------------------------------------
import argparse
import csv
# Command line argument parser
def argumentParser():
parser = argparse.ArgumentParser(description='Takes in CSV file and returns a CSV')
parser.add_argument('-f', '--file', type=str, default='input.csv',
help='The CSV file to sort')
return parser.parse_args()
# Open input CSV file and format
def getCsvInput(fileName):
'''
Input: String - Name of the CSV file to be opened
Output: List - list of all CSV elements
'''
with open(fileName, 'r') as inputFile:
reader = csv.reader(inputFile, skipinitialspace=True, delimiter=',')
return list(reader)[0]
def writeCsvOutput(data):
'''
Input: List[str] - Sorted list to be written
Output: None
'''
DATA = [data]
with open('output.csv', 'w') as outputFile:
writer = csv.writer(outputFile)
writer.writerows(DATA)
def main(args):
csvInput = getCsvInput(args.file)
csvInput.sort(key=str.lower)
writeCsvOutput(csvInput)
if __name__=='__main__':
args = argumentParser()
main(args)
| true |
1f19d6aacb2c0a916f3e867d6ff1c31c9926f282 | Askhitparihar/Python | /regex/match.py | 858 | 4.78125 | 5 | import re
str = "Cats are smarter than dogs"
matchObj = re.match(r'(.*) are (.*?) .*', str, re.M|re.I)
if matchObj:
print("matchObj.group():", matchObj.group())
print("matchObj.group(1):", matchObj.group(1))
print("matchObj.group(2):", matchObj.group(2))
else:
print("No match!")
"""
example - re.match(pattern, string, flags=0)
pattern - This is the regular expression to be matched.
string - This is the string, which would be searched to match the pattern at the beginning of string.
flags - Specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below.
group(num = 0) - This method returns entire match (or specific subgroup num)
groups() - This method returns all matching subgroups in a tuple ("None" if there weren't any matches).
""" | true |
da994d200023f86e42e5e6e173ca6089643755af | Askhitparihar/Python | /Calculator.py | 835 | 4.5 | 4 | import re
# Program to create a simple calculator using Regex and eval functionality #
print("===============Calculator===============")
print("Type 'quit' to stop program from running.\n")
previous = 0
run = True
def performMath():
global run
global previous
equation = ''
if previous == 0:
# for python2.7 use raw_input() - python3+ use input() #
equation = raw_input("Enter equation: ")
else:
equation = raw_input("Enter Equation: " + str(previous))
if equation == "quit":
print("Goodbye!")
run = False
else:
equation = re.sub('[a-zA-Z,.:()" "]', '', equation)
if previous == 0:
previous = eval(equation)
else:
previous = eval(str(previous) + equation)
while run:
performMath() | true |
ad1c243dba20d25b39995c5de63440c490dc860a | andrewcowannagora/Queens-MMA-Data-Science | /Python/Python Exercises/pythonFundamentals/12_lists.py | 1,563 | 4.3125 | 4 | # Create a list
myList = []
myOtherList = list()
# Create a list with values
myList = [1, 2, 3]
myOtherList = list([1, 2, 3])
# Values don't have to be homogeneous
myNumber = 2.89
myList = [1, None, {'this': 'dict'}, myNumber]
# Lists can be nested
myNestedList = [1, 2, 3, [4, 5, ['this', 'that'], 6], 9]
# Accessing items in a list
myList = ['first item', 'second item', 'third item', 'fourth item']
myList[0] # List index starts at 0
myList[2]
myList[-1] # Negative indexes can be used to start at the end of the list
myList[-2]
myList[5] # Error when index is greater than or equal to list length
myList[0:2] # Start position (inclusive), end position (exclusive)
myList[:3] # When either number is left blank, defaults are start and end of list
myList[1:]
myList[:]
myList[0:-2] # Negative numbers can be used
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
myList[1:9:2] # A third value can be added to indicate step size
# Items can be updated using the list index
myList[2] = 100012
# Common list methods and functions
myList = ['first item', 'second item', 'third item', 'fourth item']
myList.append('fifth item')
myList.insert(2, 'apples')
myList.extend(['some', 'other', 'list'])
[1, 2] + [3, 4, 5]
myVal = myList.pop(4)
myList.remove('second item')
del myList[0]
myNumericList = [2, 34, 1, 10, 5, 5, 6, 999]
myNumericList.sort()
myAlphabeticList = ['zebra', 'possum', 'wombat', 'cat', 'whale']
myNewList = sorted(myAlphabeticList)
len(myNewList)
# Check if an item is in a list
'zebra' in myNewList
if 'dog' in myNewList:
print('Woof') | true |
a11291d8e4a66707db7b84d4727bb04e548b95ca | huanfuzhexianshi/MIT_IAP2019 | /src/day_1/02_python102.py | 730 | 4.46875 | 4 | # class intro: making a point and line class
class Point(object):
"""Class Point
Attributes:
x (float): x coord.
y (float): y coord.
z (float): z coord.
"""
def __init__(self):
pass
@property
def x(self):
"""float: The X coordinate of the point."""
pass
@property
def y(self):
"""float: The Y coordinate of the point."""
pass
@property
def z(self):
"""float: The Z coordinate of the point."""
pass
def __repr__(self):
pass
# Create a Line class
if __name__ == '__main__':
pass
# create a line
# the type of start point
# show the start point
# calculate midpoint
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.