blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3568682e984a4a36186bdcc87ee4cd92bbe0677a | number8080/ppenv364 | /arithcmeti.py | 390 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
num1 = int(input("1:"))
num2 = int(input("2:"))
#
# num1 = input("1:").strip()
# num2 = input("2:").strip()
print("%s + %s = %s" %(num1,num2,num1 + num2))
print("%s - %s = %s" %(num1,num2,num1 - num2))
print("%s * %s = %s" %(num1,num2,num1 * num2))
print("%s / %s = %s" %(num1,num2,num1 / num2))
print("%s %% %s = %s" %(num1,num2,num1 % num2))
| false |
8ea553da0aa66c7cfda9f76ee1489d401fdcef2a | MomoeYoshida/cp1404lectures | /classes/self_and_instance_variables.py | 475 | 4.21875 | 4 | """self is used to create instance variables instead of local variables"""
def drive(self, distance):
"""Drive the car a given distance if it has enough fuel."""
if distance > self.fuel:
distance = self.fuel
self.fuel = 0
else:
self.fuel -= distance
self.odometer += distance
return distance
# distance is a local variable, so it only exists in this function
# self.fuel is an instance variable, available anywhere in the class
| true |
9e5dd7b6fa35fe4465e24149379737e42e1eccb2 | MomoeYoshida/cp1404lectures | /classes/math.py | 871 | 4.3125 | 4 | import math
class Point(object):
"""A Cartesian point (x, y) - all values are floats unless otherwise stated."""
def __init__(self, x=0.0, y=0.0):
"""Initialise a point with x and y coordinates."""
self.x = x
self.y = y
def distance(self, other):
"""Get the distance between self and another Point."""
x_diff = self.x - other.x
y_diff = self.y - other.y
return math.sqrt(x_diff ** 2 + y_diff ** 2)
def sum(self, other):
"""Get the vector sum of self and another Point, return a Point instance."""
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
"""Print a Point as a coordinate pair."""
return "({:.2f}, {:.2f})".format(self.x, self.y)
x = float(input("Enter x value: "))
y = float(input("Enter y value: "))
p1 = Point(x, y)
print(p1)
| true |
2e845e3287eafed7ff185529014b7d1d90db7852 | maximashuev/QA_Python_HW | /Week3/4.py | 528 | 4.71875 | 5 | """
4. Write a function that inverts the keys and values of a dictionary.
e.g. function_name({ 'a': 'b', 'c': 'd' }) => { 'b': 'a', 'd': 'c' }
e.g. function_name({ 'fruit': 'apple', 'meat': 'beef' }) => { 'apple': 'fruit', 'beef': 'meat' }
"""
def invert_dictionary(dictionary):
inverted_dic = {}
for i,j in dictionary.items():
inverted_dic.update({j:i})
print(inverted_dic)
invert_dictionary({ 'a': 'b', 'c': 'd' })
invert_dictionary({ 'fruit': 'apple', 'meat': 'beef' })
invert_dictionary({19:'Covid'})
| false |
2e5611fde929a2a23ca3aa63291903713e140e4c | binit92/nd256 | /P2/P3-rearrange-array-elements.py | 2,779 | 4.125 | 4 | #Rearrange Array Elements so as to form two number such that their sum is maximum. Return these two numbers. You can assume that all array elements are in the range [0, 9]. The number of digits in both the numbers cannot differ by more than 1. You're not allowed to use any sorting function that Python provides and the expected time complexity is O(nlog(n)).
#for e.g. [1, 2, 3, 4, 5]
#The expected answer would be [531, 42]. Another expected answer can be [542, 31]. In scenarios such as these when there are more than one possible answers, return any one.
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
length = len(input_list)
if length == 0:
return 0, 0
print(input_list)
merge_sort(input_list)
sorted_list = input_list
#sorted_list = sorted(input_list)
print(sorted_list)
even = 0
odd = 0
max_sum = [0,0]
for e, i in enumerate(range(0,length,2)):
if i == length -1 and length%2 == 1:
max_sum[0] += sorted_list[i] * 10 ** e
else:
max_sum[1] += sorted_list[i] * 10 ** e
max_sum[0] += sorted_list[i+1] * 10 ** e
print(max_sum)
return max_sum
def merge_sort(arr):
length = len(arr)
large_reversal_count = 0
if length > 1:
mid = length // 2
LEFT_ARR = arr[:mid]
length_LEFT_ARR = len(LEFT_ARR)
RIGHT_ARR = arr[mid:]
length_RIGHT_ARR = len(RIGHT_ARR)
# splitting starts from these recursive calls
merge_sort(LEFT_ARR)
merge_sort(RIGHT_ARR)
# merging starts from here
i = j = k = 0
while i < length_LEFT_ARR and j < length_RIGHT_ARR:
if LEFT_ARR[i] < RIGHT_ARR[j]:
arr[k] = LEFT_ARR[i]
i+=1
else:
arr[k] = RIGHT_ARR[j]
j+=1
k+=1
# merge if any remaining items in left
while i <length_LEFT_ARR:
arr[k] = LEFT_ARR[i]
i+=1
k+=1
# merge if any remaining items in right
while j<length_RIGHT_ARR:
arr[k]= RIGHT_ARR[j]
j+=1
k+=1
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_case = [[4, 6, 2, 5, 9, 8], [964, 852]]
test_function([[], []])
test_function([[2,1], [2,1]])
#outputs
#[1, 2, 3, 4, 5]
#[1, 2, 3, 4, 5]
#[542, 31]
#Pass
#Pass
#[2, 1]
#[1, 2]
#[2, 1]
#Pass
| true |
9a4791b220eba4ca329e585a50c91f330fef9c4b | nahkh/algorithms | /bubblesort.py | 407 | 4.1875 | 4 | def bubblesort(arr):
def swap(i, j):
arr[i],arr[j] = arr[j], arr[i]
swap_occurred = True
while swap_occurred:
swap_occurred = False
for i in range(1, len(arr)):
if arr[i - 1] > arr[i]:
swap_occurred = True
swap(i, i - 1)
return arr
if __name__=='__main__':
print(''.join(bubblesort(list('BUBBLESORT'))))
| false |
f91f9d341ec8585828c8439c816b8acbbbc39999 | giacomofm/Test_Python_GiacomoM | /language_exercises/excercise2.py | 537 | 4.3125 | 4 | #2. Write a function named `add_dict(dict_1, dict_2)` that joins the two dictionaries provided as arguments and returns
# a single dictionary with all the items of `dict_1` and `dict_2`
dic_1 = {'giulio': 'desk 2', 'marco': 'desk 1', 'mike': 'room 3'}
dic_2 = {'patate': 'patatine', 'cipolle': 'soffritto', 'pomodori': 'passata'}
def add_dict(dict_1, dict_2):
dict_blue={}
for word in dict_1:
dict_blue[word]=dict_1[word]
for word in dict_2:
dict_blue[word]=dict_2[word]
print dict_blue
add_dict(dic_1, dic_2) | false |
24feff07ba90ecb68678f555fbc653f907eedbe5 | PravinSelva5/100-Days-of-Code | /Day 12/guess_the_number.py | 1,545 | 4.40625 | 4 | # Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player.
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).
from art import logo
import random
GAME_ON = True
def attempts(difficulty):
"""Defines the number of attempts the user has to guess"""
if difficulty == 'easy':
attempts = 5
else:
attempts = 10
return attempts
def game_play(chances):
number = random.randint(1,100)
for _ in range(chances):
print(f"You have {chances} attempts remaining to guess the number.")
guess = int(input("Make a guess:")
)
if guess == number:
print("You win!")
elif guess > number:
print("Too high.\nGuess again.")
else:
print("Too low.\nGuess again.")
chances -= 1
if chances == 0:
print("You lose.")
while GAME_ON:
print(logo)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
chances = attempts(difficulty)
game_play(chances)
GAME_ON = False
| true |
a48d185150e46b02e1fc9571d201445a0f152aee | AndreyIh/Solved_from_chekio | /Blizzard/short_string_conversion.py | 1,016 | 4.40625 | 4 | #!/usr/bin/env checkio --domain=py run short-string-conversion
# You are given two strings, line1 and line2. Answer, what is the smallest number of operations you need to do in order to transform line1 into the line2?
#
# Possible operations:
#
# Delete one letter from one of the strings.Insert one letter into one of the strings.Replace one of the letters in one of the strings with another letter.
#
# Input:Two arguments - two strings.
#
# Output:An int, the minimum number of operations.
#
#
# Precondition:0<= len(line)<100
#
#
# END_DESC
def steps_to_convert(line1, line2):
ns = abs(len(line2)-len(line1))
maxl = ''
for i in range(0, len(line2)-1):
if line2[i] in line1:
for j in range(i+1, len(line2)+1):
if line2[i: j] in line1:
if len(line2[i: j]) > len(maxl):
maxl = line2[i: j]
else:
break
return (max([len(line2), len(line1)]) - len(maxl)) | true |
3ba57179ce18a7e0d2c48ff93a886985462dd4f9 | yehonadav/learn_git | /eyalle/lvl1/palindrome.py | 334 | 4.125 | 4 | def is_palindrome(str, length):
is_pali = True
length -= 1
for i in range (0, length//2):
if (str[i] != str[length - i]):
is_pali = False
break
return is_pali
str = input('please enter a string\n')
message = "Palindrome!" if is_palindrome(str, len(str)) else "not pali"
print (message) | true |
fb5660dd99dc451d690d4abd9073d8d4eaf937e8 | Grazopper/pyth_ans | /week1/ex8_confparse.py | 1,048 | 4.125 | 4 | #!/usr/bin/env python
'''
Write a Python program using ciscoconfparse that parses the 'cisco_ipsec.txt'
config file. Note, this config file is not fully valid (i.e. parts of the
configuration are missing).
The script should find all of the crypto map entries in the file (lines that
begin with 'crypto map CRYPTO') and print out the children of each crypto map.
'''
from ciscoconfparse import CiscoConfParse
def main():
'''
Find all of the crypto map entries in the file (lines that begin with
'crypto map CRYPTO') and print out the children of each crypto map.
'''
# Create a new CiscoConfParse object using our sample config file
cisco_cfg = CiscoConfParse("cisco_ipsec.txt")
# Find all entries beginning with crypto map CRYPTO
crypto = cisco_cfg.find_objects(r"^crypto map CRYPTO")
# Loop over the list, printing each object, and it's associated children
for i in crypto:
print i.text
for child in i.children:
print child.text
if __name__ == "__main__":
main()
| true |
9fb5d03d449ab1fcafb94b5f8f9c72022ec175a3 | yuhanliu0121/learnDataStructure | /Chapter6_Linked_Structure/1_ListNode.py | 1,391 | 4.15625 | 4 | class ListNode(object):
def __init__(self,data):
self.data = data
self.next = None
def traverse(head):
current_node = head
while current_node != None:
print(current_node.data)
current_node = current_node.next
def unsorted_search(head, target):
current_node = head
while current_node != None and current_node.data != target:
current_node = current_node.next
return current_node != None
def remove(head, target):
pred_node = None
current_node = head
while current_node != None and current_node.data != target:
pred_node = current_node
current_node = current_node.next
if current_node != None:
if current_node == head:
head = current_node.next
else:
pred_node.next = current_node.next
return head
def main():
node1 = ListNode(1)
node2 = ListNode(12)
node3 = ListNode(144)
node4 = ListNode(123)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node2 = None
node3 = None
node4 = None
node5 = None
print("the linked list: ")
traverse(node1)
print()
print("search 2,1 and 5: ")
print(unsorted_search(node1, 2))
print(unsorted_search(node1, 1))
print(unsorted_search(node1, 5))
print()
print("remove 1")
node1 = remove(node1, 1)
traverse(node1)
print()
print("remove 144")
node1 = remove(node1, 144)
traverse(node1)
if __name__ == "__main__":
main() | false |
d20dd782f761e605558be1918404206a4a0a21c9 | yuhanliu0121/learnDataStructure | /Chapter5_SearchingAndSorting/1_binarysearch.py | 497 | 4.125 | 4 | def binary_search(search_list, value):
# the list should be in ascending order
assert isinstance(search_list, list), "must input a list"
pointer_low =0
pointer_high=len(search_list) - 1
while pointer_high >= pointer_low:
pointer_mid = (pointer_low + pointer_high) // 2
if search_list[pointer_mid] == value:
return pointer_mid
if search_list[pointer_mid] > value:
pointer_high = pointer_mid - 1
if search_list[pointer_mid] < value:
pointer_low = pointer_mid + 1
return None | true |
eeaefbf9d73bd82aea02653870c01a6b05969e1d | amatiych/python-util | /powers2.py | 322 | 4.1875 | 4 | import math
def powers(X):
###
decompose a number into powers of 2
returns list of powers of 2
e.g. for 15 the result will 0, 1,2,3 so 2^0 + 2^1+2^2+2^3 = 1+2+4+8=15
###
power = 0
res = []
while X!= 0:
if X & 1 != 0:
res.append(math.log(1 << power,2))
power += 1
X >>= 1
return res
print (powers(15))
| true |
a759dfbdc30cfe2b80913adbf36c359fd5291fd1 | kemago/CodeOfTheFuture | /18_ Quiz_with_Answers.py | 1,615 | 4.40625 | 4 | # Test yourself quiz!
# Question 1 - Assigning Variables
x = 10
y = 3
print(x * y) # Multiplication
print(x + y) # Addition
print(x - y) # Substraction
print(x / y) # Division
# Question 2 - Lists
my_list = list(range(0, 101, 2))
print(my_list)
print(my_list[0:10]) # Printing the first ten elements
print(len(my_list)) # Finding the length of the list
my_list.append(True) # Appending a value to this list - can be any type
print(my_list)
# Question 3 - If statement
number = 835
if number % 5 == 0:
print("number is divisible by 5")
else:
print("number is not devisible by 5")
# Question 4 - For loop
for i in range(6):
print(i)
# Question 5 - Turtle
import turtle
for i in range(5): # A pentagon has five sides
turtle.right(72) # 360 / 5 = 72
turtle.forward(180)
turtle.done()
# Question 6 - Functions
def pythagorean_triple(a, b, c):
if a**2 + b**2 == c**2:
return True
else:
return False
print(pythagorean_triple(3, 4, 5)) # This is True
print(pythagorean_triple(3, 9, 15)) # This is False
# Question 7 - Spot the Error!
# n = 5
# while n > 0
# n = n + 1
# print(n)
n = 5
while n < 20:
n = n + 1
print(n)
# Question 8 - Plotting!
import matplotlib.pyplot as plt
list1 = [1, 6, 13, 16, 24]
list2 = [3, 7, 17, 28, 30]
plt.plot(list1, list2, c = "blue", linewidth=1, label="A Line!", linestyle="dashed",
marker="s", markerfacecolor="purple", markersize=2)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("Python Plot of a Line")
plt.legend()
plt.show() | true |
230b237b1a6ca540b9ec2a7325d8544423edf04a | madikarthik/Algorithms | /incertion sort/2.1-2.py | 430 | 4.125 | 4 | def insertionsort(n):
for index in range (len(n)-2, -1, -1):
currentvalue = n[index]
position = index
print position
while position < len(n)-1 and n[position+1] > currentvalue:
n[position] = n[position+1]
position += 1
n[position] = currentvalue
n = [31, 41, 59, 26, 41, 58]
insertionsort(n)
print(n)
| true |
cd564b925113a62cdfbad47ff2b81ba3ad92ba24 | JenMai/Python-training | /Coder's Apprentice's exercises/Grades.py | 2,269 | 4.28125 | 4 | total = 0
x = 1
grade = 0
#-------------------------------------------------------
# function used to get a floating number from user; from The Coder's Apprentice: http://www.spronck.net/pythonbook/
#-------------------------------------------------------
def getFloat( prompt ):
while True:
try:
num = float( input( prompt ) )
except ValueError:
print( "That is not a gradeber -- please try again" )
continue
return num
print( "Enter your grades, out of 20." )
print( "Please type '-1' once you're done." )
#-------------------------------------------------------
# loop-and-a-half to get every grade user wants to input:
#-------------------------------------------------------
while True :
grade = getFloat( "Please enter grade num. {}: ".format( x ) ) # x indicates how many grades entered so far
if (grade < -1) or (grade > 20) :
print( "Grade must be between 0 and 20" ) # -1 still need to be off that if-statement as it's used to end the loop
continue # doesn't consider input if one condition is True, loop starts over
if grade == -1 :
break # break when user is done.
total += grade # accumulating inputs to the total if other if-statements are False
x+=1
average = total / (x-1) # average score once loop is broken, minus change in x when input is -1
print( "Total is", total )
print( "average is", average )
#-------------------------------------------------------
# conversion to the American score (kind of, not GPA though) :
#-------------------------------------------------------
if average >= 17 :
print( "In America, your score would be an A! Congratulations!")
elif (average >= 15) and (average < 17) :
print( "In America, your score would be a B!")
elif (average >= 13) and (average < 15) :
print( "In America, your score would be a C!" )
elif (average >= 11) and (average < 13) :
print( "In America, your score would be a D!" )
else:
print( "In America, your score would be an F!" ) | true |
eefc620ceae181e06337d9e13ebd96de741e8e21 | JenMai/Python-training | /Coder's Apprentice's exercises/0603 It's Owl Stretching Time.py | 1,084 | 4.21875 | 4 | '''Ask the user to supply a string. Print how many different vowels there
are in the string. The capital version of a lower case vowel is considered to be the same
vowel. y is not considered a vowel. Try to print nice output (e.g., printing “There are 1
different vowels in the string” is ugly). Example: When the user enters the string “It’s Owl
Stretching Time,” the program should say that there are 3 different vowels in the string.'''
from pcinput import getString
sentence = getString( "Please type something: " ).lower() # lowering everything makes the process easier.
v = 0
#-------------
# Unless if-statements were in a loop, they return true (or v+1) once that char is met for the first time, and do not iterate.
#-------------
if "a" in sentence :
v += 1
if "e" in sentence :
v += 1
if "i" in sentence :
v += 1
if "o" in sentence :
v += 1
if "u" in sentence :
v += 1
if v == 1 :
print( "There is only one vowel in the string." )
elif v > 1 :
print( "There are", v, "different vowels in the string." )
else :
print( "This string has no vowel." )
| true |
710ffbc5dac7810b249aa2981b483bfc800fe085 | Shaely-jz/pre-course | /lesson03/Task3.py | 442 | 4.21875 | 4 | """
3. Реализовать функцию my_func(), которая принимает три позиционных
аргумента, и возвращает сумму наибольших двух аргументов.
"""
def my_func1(x, y, z):
my_list = [x, y, z]
my_list.pop(my_list.index(min(my_list)))
return sum(my_list)
print('Сумма наибольших двух аргументов: ', my_func1(3, 8, -2))
| false |
35c6cad5f49b5aecebc6b88d95e161d66aec40e0 | Shaely-jz/pre-course | /lesson03/Task1.py | 830 | 4.15625 | 4 | """
Реализовать функцию, принимающую два числа (позиционные аргументы) и
выполняющую их деление. Числа запрашивать у пользователя, предусмотреть
обработку ситуации деления на ноль.
"""
while True:
x = input('Введите целое число для x: ')
y = input('Введите целое число для y: ')
if x.isdigit() and y.isdigit:
x = int(x)
y = int(y)
break
else:
print('Ошибка ввода, попробуйте снова!')
def my_func(x, y):
try:
my_division = x / y
return my_division
except ZeroDivisionError:
return 'Деление на ноль'
print(my_func(x, y))
| false |
b1e8d4939d1719ef8822769f5cded2c6d88224a0 | NaychukAnastasiya/goiteens-python3-naychuk | /Home_Work_2_B_Naychuk_Anastasiya/Task7.py | 697 | 4.15625 | 4 | # Створити Функцію яка знаходить площу та периметр прямокутника .
# Функція приймає два аргумента
# ( (a,b, де a - довжина,b - ширина). Результат надрукувати на екран
# ( P = ... , S = ... )
print("Введіть довжину прямокутника")
a = float(input())
print("Введіть ширину прямокутника")
b = float(input())
P = 2*(a+b)
S = a*b
print ("Для прямокутника зі сторонами a =",a," і b =",b, " периметр становить: P = ",P, " і площа становить: S = ",S) | false |
8283db527f87322d48db74a63dd587af9e34defc | aliumujib/DSandAlgorithmNanoDegree | /project3/problem_2.py | 2,284 | 4.125 | 4 | def binary_search(input_list, target, start, end):
mid = (start + end) // 2
if input_list[mid] == target:
return mid
elif start == end:
return - 1
else:
if input_list[mid] > target:
end = mid - 1
elif input_list[mid] < target:
start = mid + 1
return binary_search(input_list, target, start, end)
def find_pivot_item(input_list, mid_point, iterations):
if input_list[mid_point + 1] < input_list[mid_point]:
return mid_point
else:
mid_point = mid_point - 1
iterations = iterations + 1
return find_pivot_item(input_list, mid_point, iterations)
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
Algorithm:
find pivot
pivot is the item whose element to the left is > than it's value.
if item is pivot, return pivot index
split array in two based on pivot. if the element at index 0 < target, using binary search, search left array
otherwise search the right array
"""
pivot = find_pivot_item(input_list, (0 + len(input_list) - 1) // 2, 0)
if input_list[pivot] == number:
return pivot
else:
if number >= input_list[0]:
return binary_search(input_list, number, 0, pivot - 1)
else:
return binary_search(input_list, number, pivot + 1, len(input_list) - 1)
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
assert find_pivot_item([6, 7, 8, 9, 10, 1, 2, 3, 4], 4, 0) == 4
assert find_pivot_item([6, 7, 8, 1, 2, 3, 4], 4, 0) == 2
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
| true |
a36e6f405b0509897caec84a916db8dfb2656343 | aliumujib/DSandAlgorithmNanoDegree | /project3/problem_4.py | 1,317 | 4.15625 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
result = __sort_012__(input_list, 0, 0, len(input_list) - 1)
return result
def swap(array, first_index, second_index):
temp = array[first_index]
array[first_index] = array[second_index]
array[second_index] = temp
def __sort_012__(input_list, low, mid, high):
if mid > high:
return input_list
else:
element = input_list[mid]
if element == 0:
swap(input_list, mid, low)
mid = mid + 1
low = low + 1
elif element == 1:
mid = mid + 1
elif element == 2:
swap(input_list, mid, high)
high = high - 1
return __sort_012__(input_list, low, mid, high)
def test_function(test_case):
sorted_array = sort_012(test_case)
assert len(sorted_array) == len(test_case)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
| true |
49a6d482431788649130bbe7e7782902042448f2 | xtinaushakova/ITMO_programming | /homework01/caesar.py | 941 | 4.28125 | 4 | '''
Реализация шифра Цезаря с произвольным сдвигом
'''
import string
LETTERS = string.ascii_letters
def encrypt_caesar(plaintext, step):
"""
>>> encrypt_caesar("PYTHON", 3)
'SBWKRQ'
>>> encrypt_caesar("python", 3)
'sbwkrq'
>>> encrypt_caesar("Python3.6", 3)
'Sbwkrq3.6'
>>> encrypt_caesar("", 6)
''
"""
ciphertext = [LETTERS[((LETTERS.find(x) + step) % 26) + 26 * x.isupper()] if x.isalpha() else x for x in plaintext]
return ''.join(ciphertext)
def decrypt_caesar(ciphertext, step):
"""
>>> decrypt_caesar("SBWKRQ", 3)
'PYTHON'
>>> decrypt_caesar("sbwkrq", 3)
'python'
>>> decrypt_caesar("Sbwkrq3.6", 3)
'Python3.6'
>>> decrypt_caesar("", 3)
''
"""
plaintext = [LETTERS[((LETTERS.find(x) - step) % 26) + 26 * x.isupper()] if x.isalpha() else x for x in ciphertext]
return ''.join(plaintext)
| false |
04748d90446261899d33499277f9dc1597610bc9 | junesvibes/getting-started | /listfunction.py | 1,476 | 4.40625 | 4 | space= "\n"
#Whenever you use square brackets python recognizes that you making a list of values
friends = ["Myles", "Jasmine", "Asher", "Meghan", "Morgan", "Bobby"]
print("As for the index of names"
"Myles = 0 \n"
"Jasmine = 1 \n"
"Asher = 2 \n"
"Meghan = 3 \n"
"Morgan = 4 \n"
"Bobby = 5 \n"
#(Negative numbers start with the number 1 when indexing negative numbers also start from the back of the list "Myles = -6" "Jasmine = -5" "Asher = -4" "Meghan = -3" "Morgan = -2" "Bobby = -1"
print(friends [0])
print (friends[-1])
print(space)
#Using a colon following the number you want to start with allows you to only display the list that you want and whatever is after that.
print(friends [3:])
print(space)
#Using the number, colon =, \n " "then another number would then create a range of the numbers from the list
print (friends [3:5])
print(space)
#Even with this you can change your variables without changing the entire list
friends[3] = "Rumay"
print(friends [3:5])
print(space)
lucky_numbers = [4, 8, 15, 16, 23, 42]
friends = ["Myles", "Jasmine", "Asher", "Meghan", "Morgan", "Bobby"]
friends.extend(lucky_numbers)
print(friends)
print(space)
friends.append("Creed")
print(friends)
print(space)
friends.insert(1, "Rumay")
print(friends)
print(space)
friends.remove ("Bobby")
print(friends)
print(space)
friends.clear
print(friends)
print(space)
friends.pop()
print(friends)
print(space)
print(friends.index ("Meghan"))
| true |
cb767688bab82c5f3ae6e06f6cb8e4b92b4e5436 | arosenberg01/toy-problems | /solutions/python/is-anagram.py | 367 | 4.15625 | 4 | def is_anagram(string_one, string_two):
sorted_string_one = sorted(string_one)
sorted_string_two = sorted(string_two)
for char_one, char_two in zip(sorted_string_one, sorted_string_two):
if char_one != char_two:
return False
return True
print(is_anagram('abcd', 'dbca')) # --> True
print(is_anagram('abcd', 'aabb')) # --> False
| false |
50f75fa1082c88916dc4e79f596fe45a37ecf712 | rjcrter11/leetChallenges | /arrays/longest_peak.py | 932 | 4.25 | 4 | '''
Write a function that takes in an array of integers and returns
the length of the longest peak in the array.
A peak is defined as adjacent integers in the array that are strictly
increasing until they reach a tip(the highest value in the peak), at which point
they become strictly decreasing. At least 3 int are required to form a peak.
array=[1,2,3,3,4,0,10,6,5,-1,-3,2,3]
ouput = 6 // 0, 10, 6, 5, -1, -3
'''
def longestPeak(arr):
i = 0
count = 0
while i < len(arr)-1:
base = i
while i+1 < len(arr) and arr[i] < arr[i+1]:
i += 1
if base == i:
i += 1
continue
peak = i
while i+1 < len(arr) and arr[i] > arr[i+1]:
i += 1
if peak == i:
i += 1
continue
count = max(count, i-base+1)
return count
peakArr = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
print(longestPeak(peakArr))
| true |
d414080fb52553e606275022946e6cc9a5af0363 | rjcrter11/leetChallenges | /strings/longest_digits_prefix.py | 431 | 4.34375 | 4 | '''
Given a string, output its longest prefix which contains only digits.
Example
For inputString = "123aa1", the output should be
longestDigitsPrefix(inputString) = "123".
'''
def longest_digits_prefix(input):
prefix = ""
for x in input:
if x.isdigit():
prefix += x
if not x.isdigit():
break
return prefix
inputString = "123aa1"
print(longest_digits_prefix(inputString))
| true |
ed33bc3916a5067ac5211b768fae4fa08ec4d051 | rjcrter11/leetChallenges | /hash_tables/group_shifted_strings.py | 816 | 4.375 | 4 | '''Given a string, we can "shift" each of its letter to its successive letter,
for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of non-empty strings which contains only lowercase alphabets,
group all strings that belong to the same shifting sequence.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
'''
from collections import defaultdict
def groupStrings(strings):
def diff(s): return tuple((ord(a) - ord(b)) % 26 for a, b in zip(s, s[1:]))
d = defaultdict(list)
for s in strings:
d[diff(s)].append(s)
return d.values()
strings = ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
print(groupStrings(strings))
| true |
f5b9d9abdb23e7ab4c22fabac48fe0ac20bd8c19 | rjcrter11/leetChallenges | /arrays/sort_by_height.py | 623 | 4.34375 | 4 | '''
Some people are standing in a row in a park. There are trees between them
which cannot be moved. Your task is to rearrange the people by their heights
in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]
'''
arr = [-1, 150, 190, 170, -1, -1, 160, 180]
def sortByHeight(a):
heights = [n for n in a if n != -1]
heights.sort()
for i in range(len(a)):
a[i] = heights.pop(0) if a[i] != -1 else a[i]
return a
print(sortByHeight(arr))
| true |
160876649cbc003bd2df9078da989e2857d87832 | rjcrter11/leetChallenges | /arrays/sort_array_by_parity.py | 652 | 4.28125 | 4 | '''
https://leetcode.com/problems/sort-array-by-parity/
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
'''
def sortArrayByParity(arr):
i = 0
j = 0
while j < len(arr):
if arr[j] % 2 == 0:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j += 1
return arr
nums_array = [3, 1, 2, 4]
print(sortArrayByParity(nums_array))
| true |
8181849e1ee15383f6e313c61257a1bd2cdff5a5 | rjcrter11/leetChallenges | /arrays/class_photos.py | 1,692 | 4.15625 | 4 | '''
It's photo day at the school, and you're the photographer assigned to take class photos.
The class that you'll be photographing has an even number of students, and all these
students are wearing red or blue shirts. You're responsible for arranging the students
in two rows before taking the photo. Each row should contain the same number of students and
should adhere to the following guidlines:
- All students wearing red shirts must be in the same row.
- All students wearing blue shirts must be in the same row.
- Each student in the back row must be strictly taller than the student directly
in front of them in the front row.
You're given 2 input arrays: one containing the heights of all the students with red shirts and another one
containing the heights of all the students with blue shirts. These arrays will always have the same length,
and eazch height will be a positive integer. Write a function that returns whether or not a class photo
that follows the stated guidelines can be taken.
redShirts = [5,8,1,3,4]
blueShirts = [6,9,2,4,5]
output = True // Place all students with blue shirts in the back row
'''
def classPhotos(redShirtHeights, blueShirtHeights):
redShirtHeights.sort(reverse=True)
blueShirtHeights.sort(reverse=True)
backrow = redShirtHeights if redShirtHeights[0] > blueShirtHeights[0] else blueShirtHeights
frontrow = redShirtHeights if redShirtHeights[0] < blueShirtHeights[0] else blueShirtHeights
for i in range(len(backrow)):
if backrow[i] <= frontrow[i]:
return False
return True
redShirts = [5, 8, 1, 3, 4]
blueShirts = [6, 9, 2, 4, 5]
print(classPhotos(redShirts, blueShirts))
| true |
ceb9ad72c151a23bbb4d4561b42327277cd83e3b | rjcrter11/leetChallenges | /strings/run_length_encoding.py | 1,304 | 4.125 | 4 | '''
Write a function that takes in a non-empty string and returns its run-length encoding.
From Wikipedia, "run-length encoding is a form of lossless data compression in which runs
of data are stored as a single data characters. So the run "AAA" would be encoded as "3A".
To make things more complicated, however, the input string can contain all sorts of
special characters, including numbers. And since encoded data must be decodable,
this means that we can't naively run-length-encode long runs. For example,
the run "AAAAAAAAAAAA" (12 A), can't be encoded as "12A", since this string can be
decoded as either "AAAAAAAAAAAA" OR "1AA". Thus, long runs(runs of 10 or more characters)
should be encoded in a split fashion; the aforementioned run should be encoded as
"9A3A"
stirng = "AAAAAAAAAAAAABBCCCCDD"
output = "9A4A2B4C2D"
'''
def runLengthEncoding(string):
output = []
count = 1
for i in range(1, len(string)):
curr = string[i]
prev = string[i-1]
if curr != prev or count == 9:
output.append(str(count))
output.append(prev)
count = 0
count += 1
output.append(str(count))
output.append(string[len(string)-1])
return "".join(output)
input = "AAAAAAAAAAAAABBCCCCDD"
print(runLengthEncoding(input))
| true |
f80bc70024f36d7eccca7bd0034fa86bb0116731 | rjcrter11/leetChallenges | /arrays/find_numbers_with_even_number_of_digits.py | 834 | 4.375 | 4 | '''
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
'''
def findNumbers(nums):
result = []
count = 0
for x in nums:
x = len(str(x))
print(x)
result.append(int(x))
print(result)
result = [result.count(i) for i in result if i % 2 == 0]
print(result)
for i in result:
count += 1
return count
input_nums = [12, 345, 2, 6, 7896]
print(findNumbers(input_nums))
| true |
16b437b217edad42a2592fba8827c8fec34e9892 | rjcrter11/leetChallenges | /arrays/minimum_waiting_time.py | 1,316 | 4.125 | 4 | '''
You're given a non-empty array of positive integers representing the amounts of time that specific
queries take to execute. Only one query can be executed at a time, but the queries can
be executed in any order.
A query's waiting time is defined as the amount of time that it must wait before its execution starts.
In other words, then its waiting time is the sum of the durations of th first two queries.
Write a function that returns the minimum amount of total waiting time for all of the queries.
For example if you're given the queries of durations [1,4,5], then the total waiting time if the
queries were executed in the order of [5,1,4] would be (0) + (5) + (5+1) = 11. The first query
duration of 5 would be executed immediately, so its waiting time would be 0, the second query of
duration 1 would have to wait 5 seconds (the duration of the first query) to be executed, and
the last query would have to wait the duration of the first two queries before being executed.
queries = [3,2,1,2,6]
output = 17
'''
def minWaitingTime(queries):
queries.sort()
totalWaitingTime = 0
for i, duration in enumerate(queries):
remaining = len(queries) - (i + 1)
totalWaitingTime += remaining * duration
return totalWaitingTime
qs = [3, 2, 1, 2, 6]
print(minWaitingTime(qs))
| true |
ad4ab0863e26319ed9f227ef71f5196968d08a6f | Bumskee/PythonClassAssignment | /Class Monday Assignment/Demon Difficulty Challenge.py | 2,891 | 4.125 | 4 | class Person:
'''Contain the constructor for the name and address attributes'''
def __init__(self, name, address):
'''Constructor'''
self.__name = name
self.__address = address
def getName(self):
'''returns the object's name'''
return self.__name
def getAddress(self):
'''returns the object's address'''
return self.__address
def setAddress(self, address):
'''change the attributes value of the object address'''
self.__address = address
def __str__(self):
return ("{}({})".format(str(self.__name), str(self.__address)))
class Student(Person):
'''Contain the constructor for the name, address, numCourses, and courses attributes with the numCourses and courses has the default value of 0 and an empty dictionary respectively'''
def __init__(self, name, address, numCourses = 0, courses = {}):
super().__init__(name, address)
self.__numCourses = numCourses
self.__courses = courses
def addCourseGrade(self, course, grade):
'''add a key value of course name and value pair of grade to the courses attributes'''
if course not in self.__courses:
self.__courses[course] = grade
self.__numCourses = len(self.__courses)
else :
print("Course already existed")
def printGrades(self):
'''Print the grades that the student have'''
grades = []
for k in self.__courses:
grades.append(self.__courses[k])
print(grades)
def getAverageGrade(self):
'''returns the average of the students grades'''
grades = []
for k in self.__courses:
grades.append(self.__courses[k])
return sum(grades) / len(grades)
def __str__(self):
return ("Student : {}({})".format(str(self.__name), str(self.__address)))
class Teacher(Person):
'''Contain the constructor for the name, address, numCourses, and courses attributes with the numCourses and courses has the default value of 0 and an empty list respectively'''
def __init__(self, name, address, numCourses = 0, courses = []):
super().__init__(name, address)
self.__numCourses = numCourses
self.__courses = courses
def addCourse(self, course):
'''Adds a course to the courses attributes if it is not in the courses attributes'''
if course not in self.__courses:
self.__courses.append(course)
self.__numCourses = len(self.__courses)
else:
print("Course already existed")
def removeCourse(self, course):
'''Removes a coursefrom the courses attributes if it is in the courses attributes'''
if course in self.__courses:
self.__courses.remove(course)
else:
print("Course doesn't exist") | true |
d2b424e4a451f38810cad45e87f3736a92adf924 | varian97/BPCS-Steganography | /vigenere_cipher.py | 788 | 4.21875 | 4 | #!/usr/bin/python
import sys
import re
import string
def encrypt(plaintext, key):
"""Encrypt a plaintext using key.
This method will return the ciphertext as a list of bytes.
"""
ciphertext = []
key_length = len(key)
for i in range(len(plaintext)):
p = plaintext[i]
k = ord(key[i % key_length])
c = (p + k) % 256
ciphertext.append(c)
return bytes(ciphertext)
def decrypt(ciphertext, key):
"""Dccrypt a ciphertext using key.
This method will return the plaintext as a list of bytes.
"""
plaintext = []
key_length = len(key)
for i in range(len(ciphertext)):
p = ciphertext[i]
k = ord(key[i % key_length])
c = (p - k) % 256
plaintext.append(c)
return bytes(plaintext)
| true |
6ca314781175327420bb75f7d59ac35b1f330305 | yoferzhang/learnPythonBase | /list.py | 2,228 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
>>> classmates = ['Michael', 'Bob', 'Tracy'] #
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> len(classmates)
3
>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> classmates[-1] #直接获取最后一个位置的元素
'Tracy'
>>> classmates[-1]
'Tracy'
>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> classmates.append('Adam') # 插入到尾部
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']
>>> classmates.insert(1, 'Jack') # 插入到指定位置,1
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
>>> classmates.pop() # 删除list末尾的元素
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']
>>> classmates.pop(1) # 删除指定位置的元素
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> classmates[1] = 'Sarach' # 替换
>>> classmates
['Michael', 'Sarach', 'Tracy']
>>> L = ['Apple', 123, True] # list元素的数据类型可以不同
>>> L
['Apple', 123, True]
>>> s = ['python', 'java', ['asp', 'php'], 'scheme'] # list可以包含list
>>> s
['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s) # 可以将s看成二维数组
4
>>> L = [] #空list
>>> len(L)
0
>>> classmates = ('Michael', 'Bob', 'Tracy')
>>> classmates
('Michael', 'Bob', 'Tracy')
>>> classmates[0] = 'Se'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t = (1, 2)
>>> t
(1, 2)
>>> t = ()
>>> t
()
>>> t = (1)
>>> t
1
>>> t = (1,)
>>> t
(1,)
>>>
>>> t = ('a', 'b', ['A', 'B'])
>>> t
('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])
>>> L = [
... ['Apple', 'Google', 'Microsoft'],
... ['Java', 'Python', 'Ruby', 'Php'],
... ['Adam', 'Bart', 'Lisa']
... ]
>>> L
[['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'Php'], ['Adam', 'Bart', 'Lisa']]
>>> print(L[0][0])
Apple
>>> print(L[1][1])
Python
>>> print(L[2][2])
Lisa | false |
30760d1f546bfd05a26061bd619b87e3a78368c1 | yoferzhang/learnPythonBase | /dataType.py | 1,287 | 4.375 | 4 | #Python的语法比较简单,采用缩进方式,比如:
a = 100
if a >= 0:
print(a)
else:
print(-a)
#当语句以冒号:结尾时,缩进的语句视为代码快
#Python程序也是大小写敏感的
print('I\'m \"OK\"!')
#I'm "OK"!
print('I\' ok.')
#I' ok.
print('I\'m learning\nPython.')
#I'm learning
#Python.
print('\\\n\\')
#\
#\
print('\\\t\\')
#\ \
print(r'\\\t\\')
#\\\t\\
#>>> print('''line1
#... line2
#... line3''')
#line1
#line2
#line3
print('''line1
line2
line3''')
print(3 > 2)
print(3 > 5)
#注意大小写
#or或运算
print(True or True)
print(True or False)
print(False or False)
print(5 > 3 or 1 > 3)
'''
True
True
False
True
'''
#not非运算
print(not True)
print(not False)
print(not 1 > 2)
'''
False
True
True
'''
age = 23
if age > 18:
print('adult')
else:
print('teenager')
a = 123 # a是整数
print(a)
a = 'ABC' # a变为字符串
print(a)
a = 'ABC'
b = a
a = 'XYZ'
print(b)
PI = 3.14159265359
# 练习
n = 123
print('n =', n)
f = 456.789
print(f)
print('f =', f)
s1 = 'Hello, world'
print('s1 =', s1)
s2 = 'Hello, \'Adam\''
print('s2 =', s2)
s3 = r'Hello, "Bart"'
print('s3 =', s3)
s4 = r'''Hello,
Lisa!'''
print('s4 =', s4)
'''
n = 123
456.789
f = 456.789
s1 = Hello, world
s2 = Hello, 'Adam'
s3 = Hello, "Bart"
s4 = Hello,
Lisa!
''' | false |
e38e81ae7641d684564ac648684120b66468d4fa | hejeffery/Python-Basic-Demo | /String.py | 1,492 | 4.25 | 4 | # coding=utf-8
# String 字符串
str = "abc"
# capitalize() 把字符串的第一个字符转为大写
print str.capitalize()
# 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串
print str.center(20)
string = u"字符串"
print len(string)
# count(),计算str中某个字符出现的次数,参数1:需要计算的字符;参数2:起始位置;参数3:结束位置
str1 = "aabbccddaa"
print str1.count("a" , 0, len(str1))
print str1.count("a")
# endswith(),判断字符串是否以某个字符串结尾
print str1.endswith("aa")
# isalnum(),如果字符串中至少有一个字符并且所有字符都是字母或数字则返回True, 否则返回False
str2 = "abcd1234"
print str2.isalnum()
# isalpha(),如果字符串中至少有一个字符并且所有字符都是字母则返回True, 否则返回False
print str2.isalpha()
str3 = "123456"
# isdigit(),如果字符串中只包含数字则返回True, 否则返回False
print str3.isdigit()
# islower(),如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False
print str1.islower()
# isupper(),如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False
print str3.isupper()
# split(),以分割字符串,第二个参数是仅分割的个数。第二参数可选
str4 = "abc,def,ghi,jlk"
print str4.split(",", 1)
| false |
0e1b6906983589ac496957cbb3009e73759c8eab | pythontype/python | /python_test/lian5.py | 893 | 4.375 | 4 | ################################
# 练习5:更多的变量和打印
################################
#
# f是“格式化”(format)的意思
# 格式为 f、引号、{},例如f“Hello {somevar}”
#
# 格式化字符串主要作用是:
#
# %d 输出数字
# %s 输出字符串
my_name = "XiaoMing"
my_age =10
my_height = 170
my_weight = 60
my_eyes = "Black"
my_teeth = "White"
my_hair = "Black"
print(f" let't talk about { my_name }.")
print(f" He's { my_height } inches tall.")
print(f" He's { my_weight } pounds heavy.")
print(" Actually that's not too heavy.")
print(f" He's got { my_eyes } eyes and { my_hair} hair. ")
print(f" His teeth are ususlly { my_teeth } depending on the coffee.")
#this line is tricky,try to get it exactly right
total = my_age + my_height + my_weight
print (f" If i add { my_age } , { my_weight } i get { total }.") | true |
b64abc12c9a76c4dcd40e9c4ae6bbe8a3c6f6463 | shankarkalmade/learnPython | /src/dictionary/sample_dict_search.py | 603 | 4.1875 | 4 |
# sample code to search through dict
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
},'Cecil': {
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
# printing lables
labels ={
'phone': 'Phone Number',
'addr' : 'Address'
}
name = raw_input("Enter name")
request_info = raw_input("Are you looking for phone Number (p) or Address (a): ")
if request_info=='p' : key = 'phone'
if request_info=='a' : key = 'addr'
if name in people : print "%s's %s is %s" % \
(name , labels[key], people[name][key])
| false |
2d170b60d1a094bf1c65dd84bd73ed84b9c7d89c | shankarkalmade/learnPython | /src/assignments/leap_year.py | 497 | 4.28125 | 4 |
''' sample code to check entered year is leap or not'''
input_year = input("Enter year to validate leap year: ")
if (input_year % 4) == 0 :
if (input_year%100) == 0:
if(input_year % 400) == 0:
print 'Entered Year : %s is leap year' % input_year
else:
print 'Entered Year : %s is not leap year' % input_year
else:
print 'Entered Year : %s is leap year' % input_year
else:
print 'Entered Year : %s is not leap year' % input_year
| false |
7c6a2742203ad118805fba0b9afc1dc1eddad873 | SaistaShaikh/Python | /list.py | 947 | 4.5625 | 5 | #introduction to list
topics= ["physics","maths","chemistry"]
print(topics)
print(type(topics))
#print 1st element
print(topics[0])
print(topics[2])
print(type(topics[2]))
#print last element using -1, second last by -2
print(topics[-1])
colors=["red","blue","green"]
print(colors)
print(colors[2])
#changing value of element of list
colors[2]="yellow"
print(colors)
#build dynamically list by default adds at the end of the list we can create new list
colors.append("black")
print(colors)
#insert used to inser at specified index
colors.insert(1,"brown")
print(colors)
#for removing elemnts we use remove, it removes only one instance
colors.remove("red")
print(colors)
#stores and pop lassst element
removed=colors.pop()
print(removed)
removed1=colors.pop(1)
print(removed1)
print(colors)app
del colors[0]
print(colors)
fruit=[]
fruit.append(input("Enter a fruit"))
fruit.append(input("Enter a fruit"))
print(fruit)
| true |
6afcb18f23b4f6ca99e1c693cd314e61614dea76 | SaistaShaikh/Python | /forLoops.py | 507 | 4.34375 | 4 | #Looping through a list elements with a for loop
names=["pistu","oreo","hello","world"]
print(names)
print(type(names))
print(names[0].title())
for i in names:
print(i.title())
print("You r going to win this...\n")
print("Go football")
values=[1,2,3,4,5,9]
sum=0
for value in values:
sum=sum+value
print(sum)
triples=[["a","b","c"],["1","2","3"],["do","re","me"]]
for triple in triples:
print(triple)
for triple in triples:
for element in triple:
print(element,end=' ')
| true |
0bc38de3303440814d95f73d1143b3a164b1c174 | Damowerko/PennAppsXV | /python/coordinate.py | 1,032 | 4.375 | 4 |
import math
class coordinate:
"""
The coordinate class is used to place the microphones in a coordinate system. The class can calculate the angle difference between any two coordinates.
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.magnitude = math.sqrt(x * x + y * y)
if x == 0:
if y > 0:
self.angle = 3.14159265358797323 / 2
elif y < 0:
self.angle = -3.14159265358797323 / 2
else:
self.angle = 0
else:
self.angle = math.atan(y / float(x))
# angle is in radians
def findAngle(self, coord):
# param: coord is another coordinate.
# return: The angle between the microphones.
return math.abs(self.angle - coord.get_angle)
def get_angle(self):
# return: The angle of the coordinate
return self.angle
def get_magnitude(self):
# return: The magnitude of the coordinate
return self.magnitude
| true |
9e0053b8d9a925cd28623ebdd457ba59ee40a74f | LucasEdu10/Coursera | /Exercicios/semana_#5/Lista2/exercicio1.py | 727 | 4.1875 | 4 | # Escreva a função fizzbuzz que recebe como parâmetro um número inteiro e devolve
# 'Fizz' se o número for divisível por 3 e não for divisível por 5;
# 'Buzz' se o número for divisível por 5 e não for divisível por 3;
# 'FizzBuzz' se o número for divisível por 3 e por 5;
# Caso o número não seja divisível 3 e também não seja divisível por 5, ela deve devolver o número recebido como parâmetro.
#x = int(input('Digite um numero: '))
FizzBuzz = 'FizzBuzz'
Fizz = 'Fizz'
Buzz = 'Buzz'
def fizzbuzz(x):
if ((x % 3) == 0) and ((x % 5) == 0):
return FizzBuzz
elif (x % 3) == 0:
if (x % 5) != 0:
return Fizz
elif (x % 5) == 0:
if (x % 3) !=0:
return Buzz
else:
return x
#fizzBuzz(x) | false |
6db38a86d5832c428f703e277ea7c3388393e944 | prtk07/Programming | /Python/vivek_wesley_move_common_elements_leftSide_algorithm.py | 705 | 4.15625 | 4 | # Algorithm:
# Move common elements of the array to left side
# We are moving '0' to <--left which occurs 4 times in the given example.
# though we are moving '0' without changing the the order of the array.
# With little bit of changes you can move elements from left to right.
def move_common_leftside(arr):
if len(arr) < 1:
print ("lngth issues")
R = len (arr) - 1
W = len (arr) - 1
while(R >= 0):
if(arr[R]!=0):
arr[W] = arr[R]
W -= 1
R -= 1
while(W >= 0):
arr[W] = 0
W -= 1
print("Moved Array: ", arr)
arr = [ 0, 2, 5, 0, 11, 0, 6, 8, 0, 15 ]
print ("original array: ", arr)
move_common_leftside(arr) | true |
219926f72ae46f1839c3b261dd002a1859e2dbb3 | prtk07/Programming | /Python/samarthdad_intro_to_recursion.py | 567 | 4.40625 | 4 | # This below method uses while loop for the execution of function:
def count_down_from(number):
start = number
if start <= 100:
while start >0:
print (start)
start -= 1
else :
print("Please Enter Correct Value")
number = int(input("Enter the number: "))
count_down_from(number)
#This below method uses recursion function for the execution of the process:
def count_down_from(number):
if number <= 0:
return
print(number)
count_down_from(number - 1)
count_down_from(10)
| true |
84f563a5b6de77234645f9af89b0eaf15a42d5fd | wyz33/dsp | /python/advanced_python_dict.py | 1,500 | 4.125 | 4 | import csv
# use the csv module to read the csv file
f = open('faculty.csv')
reader = csv.reader(f)
#setting up to separate the csv files into different columns
#also read the headline so we can skip right to the data part of the csv file.
header = next(reader)
#Use the header file to find the index of the columns
name_index = header.index('name')
faculty_dict = dict()
#answer to Q6, first dictionsary organized only by last name
for row in reader:
name = row[name_index]
separate = name.split()
last = separate[-1]
if last in faculty_dict.keys():
faculty_dict[last].append(row[name_index+1:])
else:
faculty_dict[last] = [row[name_index +1:]]
for x in sorted(faculty_dict)[0:3]:
print x, faculty_dict[x]
f.close()
#answr to Q7, better dictionary with (first name, last name) tuple as dictionary keys
f = open('faculty.csv')
reader = csv.reader(f)
header = next(reader)
name_index = header.index('name')
professor_dict = dict()
for row in reader:
name = row[name_index]
separate = name.split()
if len(separate)<3:
better_name = (separate[0], separate[-1])
else:
better_name = (' '.join(separate[0:-1]), separate[-1])
professor_dict[better_name] = row[name_index+1:]
##answer for Q7, sorted by first name
for x in sorted(professor_dict)[0:3]:
print x, professor_dict[x]
#answer for Q8, sorted by last name:
for x in sorted(professor_dict.keys(), key =lambda x: x[1]):
print x, professor_dict[x]
| true |
ad03c5d979de642805b8b1597b138d6d2051f704 | martinezga/jetbrains-academy-simple-banking-system | /Problems/Yoda style/main.py | 773 | 4.3125 | 4 | import random
# your sentence is assigned to the variable
sentence = input().split()
# write your python code below
random.seed(43)
random.shuffle(sentence)
# shows the message
print(' '.join(sentence))
"""
Yoda style
Everybody wants to speak like master Yoda sometimes. Let's try to implement a program that
will help us with it.
First, we turn the string of words into a list using the string.split() method.
Then use the function random.seed(43) and rearrange the obtained sequence.
To turn the list back into a string, use ' '.join(list).
Print the message in the end.
Note: you have to use random.seed(43) in this task!
Sample Input:
Luke, I'm your father
Sample Output:
your father I'm Luke,
Sample Input:
I will be back
Sample Output:
be back will I
""" | true |
2fad0b4d6df8c095a7b27a65101a5f6086c8de12 | martinezga/jetbrains-academy-simple-banking-system | /Problems/Hexagon/main.py | 1,201 | 4.5625 | 5 | import math
class Hexagon:
def __init__(self, side_length):
self.side_length = side_length
def get_area(self):
return '{:.3f}'.format((1 / 2) * 3 * math.sqrt(3) * (self.side_length ** 2))
"""
Hexagon
The class Hexagon represents the regular hexagons
(all sides are equal in length and all angles equal \(120 ^ \circ\)).
The only parameter needed to create a regular hexagon is the length of its side \(t\) .
Create a method get_areathat calculates the area of the hexagon according to the formula:
\(S = \frac{3\sqrt{3} * t^2}{2}\).
The name of the method has to be get_area!
The method doesn't receive any parameters and it doesn't print anything,
just returns the calculated area (rounded to 3 decimals).
You do NOT need to call the method in your program!
To calculate the square root use the math.sqrt(x) method. (The math module has already been imported.)
Nothing else is required (you do NOT need to work with the input).
Sample Input:
1
Sample Output:
2.598
Sample Input:
5.4
Sample Output:
75.760
Caution
You may see errors in your code or execution results due to missing context.
Don’t worry about it, just write the solution and press Check.
""" | true |
cd71f44cb2317f4a2e7efff3b475ca56f2c13c5b | mattmagnotta/Bootcamp-Code | /code/python/calculator.py | 775 | 4.1875 | 4 | # addition function
def add (x, y):
return x + y
# subtraction function
def subtract(x, y):
return x - y
# multiplication function
def multiply (x, y):
return x * y
# division function
def division (x, y):
return x / y
print("Select operation")
print("1.Add")
print("2.Subtract")
print("3.Division")
print("4.Multiplication")
choice = input("Enter choice (1/2/3/4:)")
num1 = int(input("What is the first number?: "))
num2 = int(input("what is the second number?: "))
if choice == "1":
print(num1, '+',num2,"=", add(num1,num2))
elif choice == "2":
print(num1, "+",num2, "=", subtract(num1,num2))
elif choice == "3":
print(num1, "+", num2, "=", division(num1,num2))
elif choice == "3":
print(num1, "+", num2, "=", multiply(num1,num2))
| false |
08231bcc40840c7a927c507df624207928a17b39 | mattmagnotta/Bootcamp-Code | /code/python/unitconv.py | 889 | 4.59375 | 5 | # # Ask the user for the number of feet, and print out the equivalent distance in meters. Hint: 1 ft is 0.3048 m. So we can get the output in meters by multiplying the input distance by 0.3048. Below is some sample input/output.
# feet_conversion = 0.3048
# miles_conversion = 1609.34
# unit_type = input("What is the unit type:(feet, miles, meters, and kilometers.)")
# if unit_type == "feet" or "ft":
# number_of_feet = float(input("Enter the amount of feet: "))
# feet_to_meters = feet_conversion * number_of_feet
# print(f"There are: {feet_to_meters} meters in {number_of_feet} miles!")
# elif unit_type == "miles":
# number_of_miles = float(input("How many total miles: "))
# miles_to_meters = miles_conversion * number_of_miles
# print(f"There are:{miles_to_meters} meters in {number_of_miles} miles!")
# elif unit_type = "meter" or "meters" or "m"
# num
| true |
a5b66aad8360d4a3ad8c783ca6c2282a22864dbd | mattmagnotta/Bootcamp-Code | /code/python/silly_strings.py | 1,960 | 4.125 | 4 | # user_string = input("Enter some text: ")
# list = user_string.split()
# def double_letter(list):
# new_string = ''
# for char in (user_string):
# double = char * 2
# new_string = double
# return new_string
# print new_string
from random import choice
# Write a function that takes a string and returns a list of strings, each missing a different character.
# user_input = input('type a word: ')
# list = user_input.split()
# return seq.pop(random.randrange(len(seq
# # def character_remover():
# # my_list = []
# # user_input = input('type a word: ')
# # print(user_input)
# # my_list = list(user_input)
# # # for char in range(len(my_list)):
# # my_list.pop(choice(range(len(my_list))))
# # new_string = ""
# # for i in range(len(my_list)):
# # new_string += my_list[i]
# # print(new_string)
# character_remover()
# def sorter(word_list):
# word_list.sort()
# return word_list[-1]
# # print(word_list)
#
# user_input = print(sorter(list(input('Whats your word?: '))))
# Write a function that returns the number of occurances of 'hi' in a given string.
# def hi_return(a_string):
# count = 0
# hi_string = 'hihihihi'
# for i in hi_string:
# if i == 'hi':
# count =+ 1
#
# print(hi_return)
# def catdog_counter(a_string):
# cat_list = string.count('cat')
# dog_list = string.count('dog')
# if cat_list == dog_list:
# return True
# else:
# return False
#
# string = ('catdogcatdog')
# print(catdog_counter(string))
#
# def char_counter(letter, word):
#
# string = ('aabbcc')
# print(word.count(letter))
# char_counter('a', 'maatt')
# Convert input strings to lowercase without any surrounding whitespace.
# def white_space_removal(user_input):
# user_input.lower()
# # user_input.strip()
# print(user_input)
# print(input('type something: ').lower().strip())
# print(help(str.lower))
| true |
b53692aa687a65aa852fbb297e54814480ae7d9a | andrei-chirilov/ICS3U-4-05-Python | /add.py | 720 | 4.125 | 4 | #!/usr/bin/env python3
# Created by: Andrei Chirilov
# Created on: Oct 2019
# This program adds positive integers
import random
def main():
counter = 0
integer = 0
answer = 0
exception = False
try:
number = int(input("How many numbers are you going to add?: "))
for counter in range(number):
integer = int(input("Enter number you are going to add: "))
if integer < 0:
continue
else:
answer = answer + integer
except ValueError:
exception = True
print("Not a valid input")
if exception is False:
print("Sum of positive integers is " + str(answer))
if __name__ == "__main__":
main()
| true |
3032f7b5ae4d234f58a98f503e36ee70737b9e0e | chaithra-s/321810304038-Assignment-11 | /unit 4 assignment 3.py | 2,028 | 4.21875 | 4 | #1.to sum all elements in list
sum = 0
list = [5,6,7,72,89]
for ele in list:
sum = sum+ ele
print("Sum of all elements in given list: ", sum)
##2.tomultiply all elements
product=1
list=[3,5,4,6]
for i in list:
product=product*i
print("multiplication of items in a list:",product)
##3.max and min from list
list=[34,5,6,12,78]
a=max(list)
b=min(list)
print("max number in a list:",a)
print("min number in a list:",b)
##4.remove duplicates from list
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)
##5.to check list is empty or not
list=input("enter elements of a list:")
for i in list:
if i==0:
print("list is empty")
else:
print("list is not empty")
##6.to copy a list
oldlist=[1,2,3,4,5]
newlist=oldlist
print("oldlist:",oldlist)
print("newlist:",newlist)
##7.to remove 0th and 4thelement
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color = [x for (i,x) in enumerate(color) if i not in (0,4)]
print(color)
##8to remove elments in even
list = [4,5,6,7,8,1,2,3]
print("Original list:",list)
for i in list:
if(i%2 == 0):
list.remove(i)
print ("list after removing EVEN numbers:",list)
##9program to shuffle and print specified list:
import random
list= [1, 4, 5, 6, 3]
print ("The original list is : ",list)
random.shuffle(list)
print ("The shuffled list is : " ,list)
##10
##8to remove elments in even
list = [4,5,6,7,8,1,2,3]
print("Original list:",list)
for i in list:
if(i%2 == 0):
list.remove(i)
print ("list after removing EVEN numbers:",list)
##program to shuffle and print specified list:
import random
list= [1, 4, 5, 6, 3]
print ("The original list is : ",list)
random.shuffle(list)
print ("The shuffled list is : " ,list)
##difference in elements in a list
list1 = [10, 20, 30, 40, 50]
list2 = [10, 20, 30, 60, 70]
print ("List1:", list1)
print("List2:", list2)
print("Difference elements:")
print ((set(list1) - set (list2)) ) | true |
f60242d736135bbad59239ee74bfb0a688f7de0c | 921kiyo/neural-networks-scratch | /src/classifiers.py | 1,952 | 4.125 | 4 | import numpy as np
def softmax(logits, y):
"""
Computes the loss and gradient for softmax classification.
Args:
- logits: A numpy array of shape (N, C)
- y: A numpy array of shape (N,). y represents the labels corresponding to
logits, where y[i] is the label of logits[i], and the value of y have a
range of 0 <= y[i] < C
Returns (as a tuple):
- loss: Loss scalar
- dlogits: Loss gradient with respect to logits
"""
loss, dlogits = None, None
"""
TODO: Compute the softmax loss and its gradient using no explicit loops
Store the loss in loss and the gradient in dW. If you are not careful
here, it is easy to run into numeric instability. Don't forget the
regularization!
"""
###########################################################################
# BEGIN OF YOUR CODE #
###########################################################################
# # Convert scores to probabilities
# # Softmax Layer
# Add normalisation factor C for numerical stability
C = - np.max(logits, axis=1, keepdims=True)
P = np.exp(logits + C)
# Calculate probabilities
probs = P / np.sum(P, axis=1, keepdims=True)
K = logits.shape[0]
# # Backward pass: compute gradients
dlogits = np.array(probs, copy = True)
# Subtract one for the attribute that matches the label
dlogits[np.arange(K), y] -= 1
# Normalise by the number of classes
dlogits /= K
# Add epsilon to avoid divide by zero error in loss
epsilon = np.finfo(np.float64).eps
loss = -np.sum(np.log(probs[np.arange(K), y] + epsilon)) / K
###########################################################################
# END OF YOUR CODE #
###########################################################################
return loss, dlogits
| true |
4f2dadb0ec1eefa04ab2bb5ea60b673020aa2856 | KuGaurav80/BasicPythonPrograms | /35_Recursion Convert Decimal to Binary.py | 224 | 4.125 | 4 | # python_decimal number into binary number using recursive function.py
#
# Created by Shashank Shukla:
__author__ = 'Shashank Shukla'
def binary(n):
if n >1:
binary(n/2)
print n%2,
dec= int(input('enter digit: '))
binary(dec) | false |
aaed57a6975e901e69777cd66f68fa774297e52f | Asana-sama/Learn | /Task1.py | 603 | 4.375 | 4 | # Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные,
# выведите на экран.
name = 'Annah'
age = 27
print('Hello World, my name is', name, 'and I am', age, 'years old')
print('And what about you?')
name2 = input('What is your name?')
age2 = input('And how old are you?')
print('Nice yo meet you,', name2, '. I think,', age2, 'is an excellent age! You are lucky!')
| false |
248c47ea37df749efe52af350f421874de5f2569 | Theodora17/PROG-2019 | /Assignment 3 - While Loops/nOddNumbers.py | 205 | 4.15625 | 4 | num = int(input("Input an int: ")) # Do not change this line
# Fill in the missing code below
odd_numbers = 1
counter = 0
while num > counter:
print(odd_numbers)
odd_numbers += 2
counter += 1 | true |
98f9bdd6f1f05e725c22b9308af6b06b548979f9 | kcmao/leetcode_exercise | /CodingInterviewChinese2-master_python/CodingInterviewChinese2-master/56_数组中数字出现的次数.py | 1,395 | 4.21875 | 4 | """
题目一: 数组中之出现一次的两个数字
"""
def find_nums_appear_once(array):
if not isinstance(array, list) or len(array) == 0:
return
temp = 0
for x in array:
temp ^= x
index_of_1 = find_first_bit_is_1(temp)
temp = 1 << index_of_1
res1 = 0
res2 = 0
for x in array:
if x & temp:
res1 ^= x
else:
res2 ^= x
return res1, res2
def find_first_bit_is_1(num):
if not isinstance(num, int):
return
index_of_bit = 0
while num != 0 and num & 1 == 0:
num = num >> 1
index_of_bit += 1
return index_of_bit
"""
题目二: 数组中唯一只出现一次的数字
"""
def find_num_appear_once(array):
if not isinstance(array, list) or len(array) == 0:
return
max_length = max([len(bin(x)) for x in array]) - 2
bits_count = [0] * max_length
for x in array:
bit_mask = 1
for bit_index in range(max_length - 1, -1, -1):
if x & bit_mask != 0:
bits_count[bit_index] += 1
bit_mask = bit_mask << 1
result = 0
for count in bits_count:
result = result << 1
result += count % 3
return result
if __name__ == "__main__":
print(find_nums_appear_once([-8, -4, 3, 6, 3, -8, 5, 5]))
print(find_num_appear_once([2, 18, 3, 7, 3, 3, 2, 7, 2, 7]))
| false |
2dc023ea2a259a3d475de3e09976eae85945ac91 | kbock/Calculators | /CalculatorTest.py | 2,829 | 4.5 | 4 | #Program to make a simple calculator for conversions to metric from imperial
#where user only has to input the imperial measurement
#This function adds two imperial numbers and yields a metric answer
def add(x, y):
return round((x+y)*25.4,3)
#This function subtracts two imperial numbers and yields a metric answer
def subtract(x, y):
return round((x-y)*25.4,3)
#This function multiples two imperial numbers and yields a metric answer
def multiply(x, y):
return round((x*y)*25.4,3)
#This function divides two imperial numbers and yields a metric answer
def divide(x, y):
return round((x/y)*25.4,3)
def main():
print(".......................................................")
print("Welcome to the basic inches to millimeters conversion tool")
print(".......................................................")
print("Please, Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
#Take input from the user
choice = input("Enter option(1/2/3/4):")
if choice == "1":
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(num1, "+",num2,"=", add(num1,num2))
except ValueError:
print("You must input a number. Try again...")
elif choice == "2":
try:
num1 = float(input("Enter number to subtract from: "))
num2 = float(input("Enter number to subtract: "))
print(num1,"-",num2,"=", subtract(num1,num2))
except ValueError:
print("You must input a number. Try again...")
elif choice == "3":
try:
num1 = float(input("Enter number to multiply: "))
num2 = float(input("Enter number to multiply by: "))
print(num1,"x",num2,'=',multiply(num1,num2))
except ValueError:
print("You must input a number. Try again...")
elif choice=="4":
try:
num1 = float(input("Enter number to divide: "))
num2 = float(input("Enter number to divide by: "))
print(num1,"/",num2,"=", divide(num1,num2))
except ValueError:
print("You must input a number. Try again...")
else:
print(" ----------Invalid input peasant----------")
print(".......................................................")
restart=input("Do you wish to start again? \"y\" for yes, anything else to exit: ").lower()
if restart == "y":
main()
else:
print("Untile we meet again...")
print(".......................................................")
print(".......................................................")
exit()
main() | true |
3f5116cc8483437a9badea968eb2a5e5c14838b1 | Hackman9912/05-Python-Programming | /Additional Stuff/Basic Stuff/FunctionExercise/3.py | 626 | 4.125 | 4 | # 3. How Much Insurance?Many financial experts advise that property owners should insure their homes or buildings for at least
# 80 percent of the amount it would cost to replace the structure. Write aprogram that asks the user to enter the replacement
# cost of a building and then displays the minimum amount of insurance he or she should buy for the property.
value = 1
def main():
global value
value = float(input("Enter the replacement cost of your building: "))
insurance = min_insurance()
print("The minimum insurance you would want is $", insurance)
def min_insurance():
return value*.8
main() | true |
c4ff8805a3a074b88ea320c75b2975dc3f4628f0 | Hackman9912/05-Python-Programming | /Additional Stuff/Hard Stuff/More advance things/generator expression.py | 304 | 4.21875 | 4 | # Generator Expressions
# I want to yield 'n*n' for each 'n' in nums
nums = [1,2,3,4,5,6,7,8,9,10]
def gen_func(nums):
for n in nums:
yield n*n
my_gen = gen_func(nums)
print(next(my_gen))
print(next(my_gen))
print(next(my_gen))
my_gen2 = (n*n for n in nums)
for i in my_gen2:
print(i) | false |
241942e6a972222361ae59f7bf2babea1bfa1245 | Hackman9912/05-Python-Programming | /Additional Stuff/Basic Stuff/Lists/list.py | 779 | 4.28125 | 4 | # list syntax of even numbers
#even_numbers = [2, 4, 6, 8, 10]
# Lists can hold different types
#different_types_list = ['Chunn', 100, False, 3.14]
# show items in list
#print(different_types_list)
# using range in a list
#range_list = list(range(5))
#print(range_list)
# repetition operator
# list * n
names = ['Hydrick', 'George', 'Ali', 'Howard']
names = names[0] * 5
print(names)
# print numbers list multiple times
numbers = [1, 2, 3]*3
print(numbers)
# loop over list and display
large_numbers = [99, 100, 101, 2000000]
for n in large_numbers:
print(n)
# indexing with lists
my_list = [10, 20, 30, 40, 50]
print(my_list[2])
# find length of list
len_list = len(my_list)
print(len_list)
# lists are mutable
large_numbers[1] = 1337
print(large_numbers)
| true |
035f509e6c000002671b42c02bea258f2ea8cf0e | Hackman9912/05-Python-Programming | /Additional Stuff/Medium Stuff/regex/Practice/11.py | 460 | 4.40625 | 4 | """
11. Processing Dates. In Section 1.2, we gave you the regex pattern
that matched the single or double-digit string representations of
the months January to September (0?[1-9]). Create the regex
that represents the remaining three months in the standard
calendar.
"""
import re
months = '''01
2
03
04
05
06
07
08
09
10
11
12
'''
pattern = re.compile(r'(\b(0?[1-9])\b|\b(1[1-2])\b)')
matches = pattern.finditer(months)
for match in matches:
print(match) | true |
171a619cacc55a9c256da2767afbfb0039c70ca0 | jfranck99/Python-Projects | /Rectangle Areas.py | 898 | 4.25 | 4 | #Ask for length of the first rectangle.
lengthOne = int( input('What is the length of the first rectangle? '))
#Ask for width of the first rectangle.
widthOne = int( input('What is the width of the first rectangle? '))
print (' ')
#Ask for length of the second rectangle.
lengthTwo = int( input('What is the length of the second rectangle? '))
#Ask for width of the second rectangle.
widthTwo = int( input('What is the width of the second rectangle? '))
print (' ')
#Calculate the area for both rectangles.
rectOne = lengthOne * widthOne
rectTwo = lengthTwo * widthTwo
#Determine which is larger.
if ( rectOne > rectTwo) :
print ('The area of the first rectangle is larger than the second.')
elif (rectOne < rectTwo ) :
print ('The area of the second rectangle is larger than the first.')
else:
print ('The areas of the two rectangles are equal.')
| true |
55af2f2901181a2ab78984ebb272563b27527295 | jfranck99/Python-Projects | /Kilometer Converter.py | 457 | 4.1875 | 4 | #Variable for converting from kilometers to miles
conversion = 0.6214
def main():
#Prompt User
km = float( input('How many kilometers do you need converted to miles? '))
#Calls conversion function
kilometer_converter(km)
def kilometer_converter(km):
#Calculate Mi --> Km
miles = km * conversion
#Display result
print('That equals', format(miles, '.2'), 'miles.')
#Calls the main function
main()
| true |
519323a5af9ad5f23360e54cbf7c08dc6e1b971f | jfranck99/Python-Projects | /Pet Class.py | 1,299 | 4.5 | 4 | class Pet:
# Initialize the 3 attributes
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
# Sets the name of the pet
def set_name(self, name):
self.__name = name
# Sets the animal_type of the pet
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
# Sets the age of the pet
def set_age(self, age):
self.__age = age
# Returns the name of the pet
def get_name(self):
return self.__name
# Returns the animal_type of the pet
def get_type(self):
return self.__animal_type
# Returns the age of the pet
def get_age(self):
return self.__age
def main():
# Get pet info from user
name = input("What is the name of your pet? ")
animal_type = input("What kind of animal is your pet? ")
age = input("How old is your pet? ")
# Create an instance of the Pet class
my_pet = Pet(name, animal_type, age)
# Re-display information
print("------- Pet Info -------")
print("Name:", my_pet.get_name())
print("Animal type:", my_pet.get_type())
print("Age:", my_pet.get_age())
main()
| true |
bdceacc163d10efac3e6398b6adbef3c5d34ca84 | ShuklaG1608/HackerRank-Python | /Introduction/IF_Else.py | 994 | 4.1875 | 4 | """Python If-Else
Task
Given an integer, , perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range of to , print Not Weird
If is even and in the inclusive range of to , print Weird
If is even and greater than , print Not Weird
Input Format
A single line containing a positive integer, .
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird .
Sample Input 0
3
Sample Output 0
Weird
Explanation 0
3 is odd and odd numbers are weird, so print Weird .
Sample Input 1
24
Sample Output 1
Not Weird
Explanation 1
n = 24
n > 20 and n is even, so it is not weird.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n%2 != 0:
print("Weird")
elif n%2 == 0 and n >=2 and n<=5:
print("Not Weird")
elif n%2 == 0 and n >=5 and n<=20:
print("Weird")
elif n%2 == 0 and n>20:
print("Not Weird")
| true |
b60e9902009703f85d4502cc002f45a63147d259 | lyon1066/hello-world | /Variability.py | 441 | 4.375 | 4 | #Variables shows how to take input and modify info
#Variable are both for text and number
#Assign variable within the program
name = "John"
print(name)
#Error of printing text rather than variable
print("name")
#Ask for input
name_asked = input("Hello, What is your Name? ")
print("Hi ", name_asked)
#Use input to allow user to choose end of program
#\n is a special command to create a new line
input("\nPress the enter key to exit.")
| true |
c03179099ecac7d3e2eec14afeee34e9f95df253 | toxicRooster/DealMax | /DealMax/robot/Robot.py | 2,820 | 4.21875 | 4 | import config
class Robot(object):
def __init__(self):
self.x = 0
self.y = 0
self.facing = "North"
# PLACE will put the toy robot on the table in position X,Y and facing NORTH,
# SOUTH, EAST or WEST
def place(self, X, Y, Facing):
if Facing.lower() not in config.direction:
print("Not Valid Direction: {0}, please use {1}".format(Facing, config.direction))
return 0
if not self._in_range(X):
return 0
if not self._in_range(Y):
return 0
self.x = X
self.y = Y
self.facing = Facing
return 1
# MOVE will move the toy robot one unit forward in the direction it is
# currently facing.
def move(self):
# 0,4 1,4 2,4 3,4 4,4
# 0,3 1,3 2,3 3,3 4,3
# 0,2 1,2 2,2 3,2 4,2
# 0,1 1,1 2,1 3,1 4,1
# 0,0 1,0 2,0 3,0 4,0
if self.facing.lower() == 'north':
if self._in_range(self.y + 1):
self.y += 1
if self.facing.lower() == 'east':
if self._in_range(self.x + 1):
self.x += 1
if self.facing.lower() == 'south':
if self._in_range(self.y - 1):
self.y -= 1
if self.facing.lower() == 'west':
if self._in_range(self.x - 1):
self.x -= 1
return 1
# LEFT and RIGHT will rotate the robot 90 degrees in the
# specified direction without changing the position of the robot
# Turn 90 degrees left
def left(self):
# direction = ["north", "east", "south", "west"]
compass_direction = config.direction.index(self.facing.lower())
if compass_direction > 0:
self.facing = config.direction[compass_direction-1]
elif compass_direction == 0:
self.facing = config.direction[-1]
else:
print("Some Error")
return 1
# Turn 90 degrees right
def right(self):
# direction = ["north", "east", "south", "west"]
compass_direction = config.direction.index(self.facing.lower())
if compass_direction == len(config.direction)-1:
self.facing = config.direction[0]
elif 0 <= compass_direction <= len(config.direction)-1:
self.facing = config.direction[compass_direction+1]
else:
print("Some Error")
return 1
# REPORT will announce the X,Y and F of the robot
def report(self):
print("Output: {0}, {1}, {2}".format(self.x, self.y, self.facing))
# Test if robot will fall if moved there
def _in_range(self, coordinate):
if coordinate in range(0,5):
return 1
return 0
| true |
fb7020fadeefc97d379db29348843974be912109 | sahil5800/Python-Projects | /Turtle Race Game/main.py | 1,167 | 4.1875 | 4 | from turtle import Turtle, Screen
from random import randint
race_is_on = False
screen=Screen()
screen.screensize(canvwidth=500, canvheight=400)
color = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
n = -100
for i in range(6):
max1 = Turtle("turtle")
max1.penup()
max1.color(color[i])
max1.goto(x=-370,y=n)
turtles.append(max1)
n += 50
line = Turtle()
line.ht()
line.speed("fast")
line.penup()
line.goto(x=-340, y=-150)
line.left(90)
line.pendown()
line.forward(350)
line.penup()
line.goto(x=340, y=-150)
line.pendown()
line.forward(350)
user_bet = screen.textinput(title="Make a bet", prompt="Which turtle will win the race, Enter a Color: ")
if user_bet:
race_is_on = True
while race_is_on:
for turtle in turtles:
if turtle.xcor()> 340:
race_is_on = False
win_color = turtle.pencolor()
if win_color==user_bet:
print(f"You Won!!! the {win_color} turtle wins")
else:
print(f"You lose!!! the {win_color} turtle wins")
turtle.forward(randint(0,10))
| true |
c7ef475ad6253d7f99b4c0a41f9faa58f4740d8f | Omupadh/python3 | /Desafios/desafio080 - Lista ordenada sem repetições.py | 1,583 | 4.125 | 4 | lista = list()
n1 = int(input('Digite o 1º número: '))
lista.append(n1)
print('Adicionado ao final da lista...')
n2 = int(input('Digite o 2º número: '))
if n2 < lista[0]:
lista.insert(0, n2)
print('Adicionado na posição 0 da lista...')
else:
lista.append(n2)
print('Adicionado ao final da lista...')
n3 = int(input('Digite o 3º número: '))
if n3 < lista[0]:
lista.insert(0, n3)
print('Adicionado na posição 0 da lista...')
elif n3 < lista[1]:
lista.insert(1, n3)
print('Adicionado na posição 1 da lista...')
else:
lista.append(n3)
print('Adicionado ao final da lista...')
n4 = int(input('Digite o 4º número: '))
if n4 < lista[0]:
lista.insert(0, n4)
print('Adicionado na posição 0 da lista...')
elif n4 < lista[1]:
lista.insert(1, n4)
print('Adicionado na posição 1 da lista...')
elif n4 < lista[2]:
lista.insert(2, n4)
print('Adicionado na posição 2 da lista...')
else:
lista.append(n4)
print('Adicionado ao final da lista...')
n5 = int(input('Digite o 5º número: '))
if n5 < lista[0]:
lista.insert(0, n5)
print('Adicionado na posição 0 da lista...')
elif n5 < lista[1]:
lista.insert(1, n5)
print('Adicionado na posição 1 da lista...')
elif n5 < lista[2]:
lista.insert(2, n5)
print('Adicionado na posição 2 da lista...')
elif n5 < lista[3]:
lista.insert(3, n5)
print('Adicionado na posição 3 da lista...')
else:
lista.append(n5)
print('Adicionado ao final da lista...')
print('=' * 52)
print('Os valores digitados em ordem foram:', lista)
| false |
5c0df5f2fc3cb0aa064ccfaaea21418908377991 | Omupadh/python3 | /Exercicios/ex073.py | 688 | 4.125 | 4 | times = ('Palmeiras', 'Santos', 'São Paulo', 'Atlético-MG', 'Botafogo', 'Athlético-PR',
'Flamengo', 'Bahia', 'Goiás', 'Internacional', 'Cruzeiro', 'Corinthians',
'Chapecoense', 'Ceará', 'Fluminense', 'Fortaleza', 'CSA', 'Grêmio', 'Avaí', 'Vasco')
c = 1
print('=' * 63)
print(f'Os 5 primeiros colocados são: \n{times[:5]}')
print('=' * 63)
print(f'Os 4 últimos colocados da tabela são: \n{times[-4:]}')
print('=' * 63)
print(f'Veja o nome dos times em ordem alfabética: \n{sorted(times)}')
print('=' * 63)
print(f'O time da Chapecoense está na {times.index("Chapecoense") + 1}ª posição.')
print('=' * 63)
for t in times:
print(f'{c}º {t}')
c += 1
| false |
8a5a58501419fcf093bc7aab25665e0f63fb07ea | Omupadh/python3 | /Testes/aula19.py | 453 | 4.15625 | 4 | pessoas = {'nome': 'Wellington', 'sexo': 'M', 'idade': 27}
print(pessoas["nome"])
print(pessoas["sexo"])
print(pessoas["idade"])
print(pessoas.keys()) # Mostra o identificador no dicionário
print(pessoas.values()) # Mostra o conteúdo no dicionário
print(pessoas.items()) # Mostra identificadores e conteúdos no dicionário
pessoas['cor'] = 'Pardo'
for k, v in pessoas.items(): # Nesse caso o .items substitui o enumerate
print(f'{k} = {v}')
| false |
81570588faf26cb6311350000f43f414ae30485d | rohansatapathy/tutor-getter | /session.py | 2,225 | 4.125 | 4 | from datetime import datetime
class Session():
"""A class to handle tutoring sessions
This class is created when a student
decides to book a session with a tutor.
It stores all the relevant information
about the session, including the student,
tutor, and timeslot.
Attributes:
student (Student) - the student of the 1-on-1 session
tutor (Tutor) - the tutor of the session
timeslot (TimeSlot) - when the session takes place
subject (str) - subject to focus on
"""
def __init__(self, tutor, timeslot):
"""Create the session"""
self.tutor = tutor
self.timeslot = timeslot
# Add these later
self.student = None
self.subject = None
def __repr__(self):
"""Return string representation of the session"""
return f"<Session on {repr(self.timeslot)} with Tutor {self.tutor} and Student {self.student}>"
def __str__(self):
"""Return pretty-printed session description"""
return f"{self.timeslot} with {self.tutor}{f' and {self.student} on {self.subject}' if self.student and self.subject else ''}"
def set_subject(self, subject):
"""Set the subject of the tutoring session"""
if subject in self.tutor.subjects:
self.subject = subject
else:
print("Sorry, this subject is not valid.")
def remove_subject(self):
"""Remove the subject attribute and set it to None"""
if not self.is_complete():
self.subject = None
def set_student(self, student):
"""Sets the student of the session"""
if self.is_booked():
print("Sorry, this session is already booked.")
elif self.is_complete():
print("Sorry, this session is over.")
else:
self.student = student
def remove_student(self):
"""Remove the student attribute and set to None"""
if not self.is_complete():
self.student = None
def is_booked(self):
return self.student is not None
def is_complete(self):
"""Return True if the session is in the past"""
return self.timeslot.end_time < datetime.today()
| true |
55eb1dd05310aaf91d36d01585d19ed35c15a973 | Manish-Thakur/Programming | /factorial.py | 366 | 4.375 | 4 | #program to print the factorial of a number
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
def Main():
num=int(input("Enter the number: "))
result=factorial(num)
print("Factorial: ",result)
if __name__ == "__main__":
Main()
# #Output:
#------------------#
# Enter the number: 5
# Factorial = 120
| true |
5651ccf241fa1ea69c7dfa07aaf729166ec5cd74 | shivsingh-git/Python_for_everyone | /Camel Case.py | 1,203 | 4.59375 | 5 | #Developers write function and variable names in Camel Case . You are given a string, S, written in Camel Case.
#FindAllTheWordsContainedInIt.
#Sample input: IAmACompetitiveProgrammer
#Sample output: I
#Am
#A
#Competitive
#Programmer
s=input("Enter The Camel String: ") #taking the String as a Input
l='' #initializing the new string
l=s[0] #assigning the frst letter of the string to list l
for i in range(1,len(s)):
if (s[i].isupper()==True) : #if the parser incounters the capital letter print the list
print(l)
l='' #making the list empty again
l=s[i] #assigning the capital letter to the new string
else:
l=l+s[i] #putting all the lower case strings in the list
print(l) #to print the last string after the last capital letter according to my program
| true |
6717836950569be1e84a6648d0a1af983811fec0 | gswyhq/hello-world | /excel用python使用实例/python3使用csv模块读写csv文件.py | 738 | 4.21875 | 4 |
读取csv文件:
import csv
#打开文件,用with打开可以不用去特意关闭file了,python3不支持file()打开文件,只能用open()
with open("XXX.csv","r",encoding="utf-8") as csvfile:
#读取csv文件,返回的是迭代类型
read = csv.reader(csvfile)
for i in read:
print(i)
存为csv文件:
import csv
with open("XXX.csv","w",newline="") as datacsv:
#dialect为打开csv文件的方式,默认是excel,delimiter="\t"参数指写入的时候的分隔符
csvwriter = csv.writer(datacsv,dialect = ("excel"))
#csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行)
csvwriter.writerow(["A","B","C","D"])
| false |
84b1f31bad8f5c6dc0771081efae9a6f2ac081ac | gswyhq/hello-world | /python相关/关于Python中Inf与Nan的判断问题.py | 2,431 | 4.40625 | 4 | #!/usr/bin/python3
# coding: utf-8
import math
# 在Python 中可以用如下方式表示正负无穷:
float("inf") # 正无穷
float("-inf") # 负无穷
float("nan") # 不是一个数;
# 利用 inf(infinite) 乘以 0 会得到 not-a-number(NaN) 。如果一个数超出 infinite,那就是一个 NaN(not a number)数。
>>> inf = float("inf")
>>> ninf = float("-inf")
>>> nan = float("nan")
>>> inf is inf
True
>>> ninf is ninf
True
>>> nan is nan
True
>>> inf == inf
True
>>> ninf == ninf
True
>>> nan == nan
False
>>> inf is float("inf")
False
>>> ninf is float("-inf")
False
>>> nan is float("nan")
False
>>> inf == float("inf")
True
>>> ninf == float("-inf")
True
>>> nan == float("nan")
False
对于正负无穷和 NaN 自身与自身用 is 操作,结果都是 True,这里好像没有什么问题;但是如果用 == 操作,结果却不一样了, NaN 这时变成了 False。
如果分别用 float 重新定义一个变量来与它们再用 is 和 == 比较,结果仍然出人意料。
如果你希望正确的判断 Inf 和 Nan 值,那么你应该使用 math 模块的 math.isinf 和 math.isnan 函数:
>>> import math
>>> math.isinf(inf)
True
>>> math.isinf(ninf)
True
>>> math.isnan(nan)
True
>>> math.isinf(float("inf"))
True
>>> math.isinf(float("-inf"))
True
>>> math.isnan(float("nan"))
True
不要在 Python 中试图用 is 和 == 来判断一个对象是否是正负无穷或者 NaN。你就乖乖的用 math 模块吧,否则就是引火烧身。
当然也有别的方法来作判断,以下用 NaN 来举例,但仍然推荐用 math 模块,免得把自己弄糊涂。
用对象自身判断自己
>>> def isnan(num):
... return num != num
...
>>> isnan(float("nan"))
True
用 numpy 模块的函数
>>> import numpy as np
>>>
>>> np.isnan(np.nan)
True
>>> np.isnan(float("nan"))
True
>>> np.isnan(float("inf"))
False
Numpy 的 isnan 函数还可以对整个 list 进行判断:
>>> lst = [1, float("nan"), 2, 3, np.nan, float("-inf"), 4, np.nan]
>>> lst
[1, nan, 2, 3, nan, -inf, 4, nan]
>>> np.isnan(lst)
array([False, True, False, False, True, False, False, True], dtype=bool)
这里的 np.isnan 返回布尔值数组,如果对应位置为 NaN,返回 True,否则返回 False。
参考资料:
https://blog.csdn.net/davidguoguo/article/details/85261172
def main():
pass
if __name__ == '__main__':
main() | false |
aa5330b6e3647556660a1780c39b6e050b771398 | Hajaraabibi/task1 | /task1.py | 416 | 4.15625 | 4 | import random
myName = input("Hi there! What is your name? ")
number = random.randint(1,10)
print("hello again," + myName + " i am thinking of a number... the number is between 1 and ten")
guess = int(input("can you take a guess:"))
if guess == number:
print("well done," + myName + "!! You guessed the number i was thinking of")
else:
print("that is not the number i was thinking of, try again next time")
| true |
8dbcfa577d68e7acd79a239626be02d9c5d6c1aa | lohit2007/guessingGame | /guessingGame.py | 428 | 4.15625 | 4 | import random
number = (random.randint(0,9))
print("Number Guessing Game")
print("Guess a Number (between 1 and 9):")
count = 0
while count < 5:
guess = int(input("Enter your guess: "))
if (guess < number):
print("Too Low")
count=count+1
elif(guess > number):
print("Too High")
count=count+1
else:
print("You're Right")
count = count+5
| true |
0755e912da6fd98cd8dc6dd29fbd94416ba6dc82 | ishmi/PyAcademy | /General/factorial.py | 346 | 4.15625 | 4 | '''
print("enter a number to find the factorial of")
num = int(input())
answer = 1
for x in range (num, 0, -1):
print(x)
answer = answer * x
print (answer)
print(answer)
'''
print("type in 0")
a = int(input())
print("now type in 1")
b = int(input())
for j in range (0, 11):
print (j)
j = j + a + b
| true |
8cfe06408cee2f57f94bd4249191896c4e992591 | YskSt030/LeetCode_Problems | /PushDominoes.py | 1,945 | 4.25 | 4 | '''
There are n dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides,
it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends
no additional force to a falling or already fallen domino.
You are given a string dominoes representing the initial state where:
dominoes[i] = 'L', if the ith domino has been pushed to the left,
dominoes[i] = 'R', if the ith domino has been pushed to the right, and
dominoes[i] = '.', if the ith domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: dominoes = "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Example 2:
Input: dominoes = ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Constraints:
n == dominoes.length
1 <= n <= 105
dominoes[i] is either 'L', 'R', or '.'.
'''
class Solution:
def pushDominoes(self, dominoes: str) -> str:
symbols = [(i, x) for i, x in enumerate(dominoes) if x != '.']
symbols = [(-1, 'L')] + symbols + [(len(dominoes), 'R')]
def cmp(a, b):
return (a > b) - (a < b)
ans = list(dominoes)
for (i, x), (j, y) in zip(symbols, symbols[1:]):
if x == y:
for k in range(i+1, j):
ans[k] = x
elif x > y: #RL
for k in range(i+1, j):
ans[k] = '.LR'[cmp(k-i, j-k)]
return "".join(ans)
if __name__=='__main__':
sol = Solution()
s = ".L.R...LR..L.."
print(sol.pushDominoes(s)) | true |
b3f05a309cd6e7a8f6e85280b2401924bb72e81e | YskSt030/LeetCode_Problems | /766.ToeplitzMatrix.py | 1,872 | 4.46875 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
Example 2:
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] will be integers in range [0, 99].
Follow up:
What if the matrix is stored on disk, and the memory is limited such that
you can only load at most one row of the matrix into the memory at once?
What if the matrix is so large that you can only load up a partial
row into the memory at once?
"""
class Solution:
#def isToeplitzMatrix(self, matrix: list[list[int]]) -> bool:
def isToeplitzMatrix(self, matrix):
ret = True
m = len(matrix[0])
n = len(matrix)
for i in range(-n, m):
templist = []
if ret == True:
for j in range(n):
if i + j >= 0 and i + j < m:
# print('j;'+str(j)+',j+i:'+str(j+i)+',matrix val is;'+str(matrix[j][j+i]))
templist.append(matrix[j][j + i])
if len(templist) >= 2 and templist[-1] != templist[-2]:
ret = False
break
return ret
if __name__ == '__main__':
sol = Solution()
matrix = [[1,2,1],[1,1,1],[1,1,1]]
ret = sol.isToeplitzMatrix(matrix)
print(ret) | true |
24da7b596580b81ae5ef9740e31620a90debaa77 | YskSt030/LeetCode_Problems | /104.MaximumDepthofBinaryTree.py | 971 | 4.15625 | 4 | """
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the
longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
else:
return self.findchildren(root,1)
def findchildren(self,node, num):
ret_l = num
ret_r = num
if node.left !=None:
ret_l = self.findchildren(node.left, num + 1)
if node.right !=None:
ret_r = self.findchildren(node.right, num + 1)
return max(num, ret_l, ret_r) | true |
1157c2cf26792a5d191b167b0e9da310744f1903 | Maldonam8074/CTI110 | /M6LAB_Maldonado.py | 1,249 | 4.3125 | 4 | # CTI 110-0002
# M6LAB
# Manuel Maldonado
# 30 October 2017
def main():
# Ask user name, then ask age.
# Then greet user by name and tell them their age. (infant, child, teenager, adult)
# Use functions main(), greet(name), ageCategory(age).
# Ask for name.
name = input("Hello what is your name? ")
# Run greet function
greet(name)
# Ask for age
age = int(input("Now Please enter your age: "))
# Final result for age.
print("Seeing as you are", age,"this makes you", ageCategory(age))
# Function to greet user
def greet(name):
# Result
print("Hello", name)
# Function to tell user age category.
def ageCategory(age):
# list of age values.
adultAge = 20
teenagerAge = 13
childAge = 1
infantAge = 0
# Boolean expression using above data.
if age >= adultAge:
return "an Adult."
else:
if age >= teenagerAge:
return 'a Teenager.'
else:
if age >= childAge:
return 'a Child.'
else:
if age == infantAge:
return 'an Infant, should you be using a computer?'
# Start Program
main()
| true |
19e42e6812dedaa1ddf411be3e99cbc0fd630b7c | Maldonam8074/CTI110 | /M5HW2_RunningTotal_Maldonado.py | 646 | 4.125 | 4 | # CTI-110
# M5HW2: Running Total
# Manuel Maldonado
# 10-11-2017
def main():
# A program that asks user a number until user enters a negative number.
# then ends loop and adds all numbers except negative entry.
runningTotal = 0
keepGoing = True
# Loop
while keepGoing:
# Ask user for a number
print("PLease enter a number? ")
number = int(input())
if number < 0:
keepGoing = False
# Closing the loop
else:
runningTotal = runningTotal + number
print("Total is: ", runningTotal)
# Start Program
main()
| true |
2cdca698c6c0fc336f024439e53e91be7445c248 | pororing12/python | /05 Section2.py | 1,422 | 4.125 | 4 | #짝수 홀수
'''
a = int(input("정수를 입력하세요"))
if a % 2 == 0 :
print("짝수입니다")
else :
print("홀수입니다")
'''
#학점계산
'''
score = int(input("점수를 입력하세요"))
if score >= 95 :
print('A')
elif score >= 90 :
print('A0')
elif score >= 85 :
print('B+')
elif score >= 80 :
print('B0')
elif score >= 75 :
print('C+')
elif score >= 70 :
print('C0')
elif score >= 65 :
print('D+')
elif score >= 60 :
print('D0')
else :
print('F')
print("학점입니다.")
'''
#삼항연산자
'''
jumsu = 55
res = ''
res = '합격' if jumsu >= 60 else '불합격'
print(res)
'''
import turtle
swidth, sheight = 500, 500
turtle.title('무지개색 원그리기')
turtle.shape('turtle')
turtle.setup(width = swidth + 50, height = sheight + 50)
turtle.screensize(swidth, sheight)
turtle.penup()
turtle.goto(0, -sheight / 2)
turtle.pendown()
turtle.speed(20)
for radius in range(1, 250) :
if radius % 6 == 0 :
turtle.pencolor('#faf9f7')
elif radius % 5 == 0 :
turtle.pencolor('#db9ae5')
elif radius % 4 == 0 :
turtle.pencolor('#6492d3')
elif radius % 3 == 0 :
turtle.pencolor('#71bfeb')
elif radius % 2 == 0 :
turtle.pencolor('#956edb')
elif radius % 1 == 0 :
turtle.pencolor('navyblue')
else :
turtle.pencolor('purple')
turtle.circle(radius)
turtle.done()
| false |
8fd645fc6877d49ec7c92084776aa5009666c234 | htlimbo/learn_python | /9_6.py | 1,692 | 4.21875 | 4 | class Restaurant():
"""one simple test"""
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def set_number_served(self,numbers):
if numbers >= self.number_served:
self.number_served = numbers
else:
print("You can not roll back numbers.")
def increment_number_served(self,upnumber):
self.number_served += upnumber
def print_number_served(self):
print("The number of served people are : " \
+ str(self.number_served) +'.')
def describe_restaurant(self):
print("The restaurant name is: " + self.restaurant_name.title() +'.')
print("The cuisine type is: " + self.cuisine_type.title() + '.')
def open_restaurant(self):
print("The restaurant is opening.")
class IceCreamStand(Restaurant):
"""one simple test"""
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors = []
def taste_list(self):
prompt = "\nPlease input your taste: "
prompt += "\nEnter 'q' to end.\n"
active = True
while active:
message = input(prompt)
if message == 'q' :
active = False
else:
self.flavors.append(message.title())
def print_taste_list(self):
print(self.flavors)
my_icecream = IceCreamStand('luck','newland')
print(my_icecream.restaurant_name.title())
print(my_icecream.cuisine_type.title())
my_icecream.describe_restaurant()
my_icecream.open_restaurant()
my_icecream.set_number_served(10)
my_icecream.print_number_served()
my_icecream.increment_number_served(6)
my_icecream.print_number_served()
my_icecream.taste_list()
my_icecream.print_taste_list()
| true |
463df82281e363402dd6e481cf92b6a0fe6dc91e | LCLY/Udemy | /pythondjango/python_sandbox/files.py | 762 | 4.3125 | 4 | # Python has functions for creating, reading, updating, and deleting files.
# Open a file
myFile = open('myfile.txt', 'w') # w is to write the file
# get info
print('Name: ', myFile.name)
print('is Closed: ', myFile.closed)
print('Opening mode: ', myFile.mode)
# Write to file
myFile.write('I love Python')
myFile.write(' and Javascript')
myFile.close()
# Append to file
# a = append, if we do w, it will just overwrite what is existing
myFile = open('myFile.txt', 'a')
# although we are using write function but since we open the file as append mode, we will just append strings
myFile.write(' I also like PHP')
myFile.close()
# Read from a file
myFile = open('myFile.txt', 'r+')
text = myFile.read(10) # read first 10 characters of the file
print(text)
| true |
5c343880caacaa3ed2173500dbb6c2439b0204a6 | GreatRaksin/6A_Lessons | /IV_term/05_lesson_1705/02_turtle_and_functions.py | 1,826 | 4.21875 | 4 | from turtle import *
def x_angle(turtle, x, y, color, length, num_of_sides):
'''Параметры:
turtle: черепашка, которая будет рисовать фигуру
x, y: координаты, в которых буду рисовать фигуру
color: цвет фигуры
length: длина стороны
num_of_sides: количество сторон фигуры
'''
turtle.up() # сначала поднимаем перо
turtle.goto(x, y) # переходим в координаты, которые нам передали
turtle.color(color) # подставляем цвет
turtle.down() # начинаем рисовать
for i in range(num_of_sides):
turtle.fd(length)
turtle.lt(360 / num_of_sides)
turtle.up() # поднимаем перо
'''
360 / 4 = 90
360 / 3 = 120
360 / 18 = 20
360 / 6 = 60
'''
def rectangle(turtle, x, y, color, length):
turtle.up() # сначала поднимаем перо
turtle.goto(x, y) # переходим в координаты, которые нам передали
turtle.color(color) # подставляем цвет
turtle.down() # начинаем рисовать
for i in range(2):
turtle.fd(length) # длинная сторона
turtle.lt(90)
turtle.fd(length / 2) # короткая сторона
turtle.lt(90)
turtle.up() # поднимаем перо
tina = Turtle() # новая черепашка
tommy = Turtle() # еще одна черепашка
x_angle(tina, -100, 100, 'green', 50, 6)
x_angle(tommy, 50, -90, 'pink', 100, 4)
x_angle(tina, -40, 40, 'yellow', 30, 18)
x_angle(tommy, 40, 120, 'purple', 30, 5)
rectangle(tina, 0, 110, 'purple', 223)
done() | false |
c8266d9a98c0c76c10e9652aca201330780bba12 | GreatRaksin/6A_Lessons | /IV_term/01_lesson_1204/01_strings_slicing.py | 770 | 4.90625 | 5 | ''' чтобы разрезать строку, необходимо написать
название переменной, которая содержит строку,
поставить рядом квадратную скобку и указать,
с какого символа и до какого необходимо вырезать
текст. Между точками ставим знак :
'''
my_string = 'Hello, world!'
print(my_string[:4]) # вырезать сначала до 4 символа
print(my_string[7:]) # вырезать с 7 символа до конца
print(my_string[3:6]) # вырезать с 3 по 6 символ
print(my_string[-6:-1]) # получить слово world отрицательными индексами
| false |
44dd9eb129131506be9e1f5b06a71445a5608b45 | GreatRaksin/6A_Lessons | /IV_term/04_otrabotka_1005/task_08_number_to_string.py | 288 | 4.3125 | 4 | numbers = {
0: 'zero', 1: 'one', 2: 'two', 3: 'three',
4: 'four', 5: 'five', 6: 'six', 7: 'seven',
8: 'eight', 9: 'nine',
}
number = int(input('Введите цифру:'))
if number not in numbers:
print('Такой цифры нет!')
else:
print(numbers[number]) | false |
6e60c01e5d9997c438af89bb05b5c633e947373d | GreatRaksin/6A_Lessons | /lesson_2202/00_homework.py | 596 | 4.5625 | 5 | '''1. Создать список, вывести приглашения'''
guests = ['Alice', 'Dan', 'Julia']
for name in guests:
print('Welcome to the party,', name)
'''2. Один гость не придет. Заменить его и вывести новые приглашения'''
print(guests[2], 'can not come!')
guests[2] = 'Zodiac'
for name in guests:
print('Welcome to the party,', name)
'''3. Добавить трех гостей '''
print()
print('#### NEW GUESTS ####')
print()
guests.insert(0, 'Alex')
guests.insert(1, 'Jack')
guests.append('Anny')
print(guests) | false |
7610b1727ae842dceb27bc4d053123304ceb0ba3 | zihuan-yan/Something | /Others/MultidimensionalVector/__init__.py | 1,226 | 4.1875 | 4 | class Vector(object):
def __init__(self, dimensions):
"""
构造函数, 初始化n维向量
:param dimensions: int 维度
"""
self.__coords = [0] * dimensions
def __len__(self):
return len(self.__coords)
def __getitem__(self, j):
return self.__coords[j]
def __setitem__(self, j, val):
self.__coords[j] = val
def __add__(self, other):
if len(self) != len(other):
raise ValueError('dimensions not match!')
result = Vector(len(self))
for j in range(len(self)):
result[j] = self[j] + other[j]
return result
def __eq__(self, other):
return self.__coords == other.value
def __ne__(self, other):
return not self.__coords == other.value
def __str__(self):
return f'<{str(self.__coords)[1:-1]}>'
@property
def value(self):
"""
向量的坐标
:return:
"""
return self.__coords
if __name__ == '__main__':
vector1 = Vector(3)
vector1[0] = 0
vector1[1] = 1
vector1[2] = 2
vector2 = Vector(3)
vector2[0] = 0
vector2[1] = 1
vector2[2] = 2
print(vector1 + vector2)
| false |
63146d1c811cc0438b7f286c09ecbc6a0e015eab | ndurumo254/python-basic | /basis.py | 1,526 | 4.53125 | 5 | #python strings
#they are used to represent alphabetical statements
#strings should be enclosed in quatation marks
name='erick'
#print (name)
#checking length of string
print(len(name))
#indexing starts at 0
#printing inex 0 output will be the first letter
print(name[0])
print(name[1:3])#Print letters btn index 1 and 3
n=name.upper()#this will change name to uper case
print(n)
#list is group of related items
#order of list cn be changed and can have duplicate of items
fruits=['banana','oranges','tomatoes','ovacado','apple']
print(fruits)
fruits[3]='kiwi' #this updates the values in the list
print(fruits)
fruits.append('sas')#adds item at the end of the list
print(fruits)
fruits.insert(3,'orange') #adding oranges at index 3
print(fruits)
fruits.reverse()#reversing the order of list items
print(fruits)
#dictionary
#contain unordered items that can be changed but dont have duplicate of items
#have key and value
course={1:'python',
2:'machine_learning',
3:'ai',
4:'java'}
print(course)
course[3]='django'#this updates key 3 into django
print(course)
#tuple
#they are orded and can not be changed they can contain duplicate entities
animals=('dog','cat','cow','goat')
print(animals)
#set
#they contain unordered itms and no duplicate items are present
#sets donot support indexing
students={'mark','john','peter'}
print(students)
#data type conversion
#helps to use different data types together
x=10
name='erick'
age=name + ' is ' + str(x) +' years of age'
print(age) | true |
130f3f1c83bd6ba3fad6aae450e626e3e28057fd | Lilieyen/alx-interview | /0x07-rotate_2d_matrix/0-rotate_2d_matrix.py | 330 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given an n x n matrix, rotate it 90 degrees clockwise
The matrix must be edited in-place
"""
def rotate_2d_matrix(matrix):
"""
rotate the matrix clockwise (90 degrees)
"""
ziped = zip(*reversed(matrix))
for column1, column2 in enumerate(ziped):
matrix[column1] = list(column2)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.