blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5acd5ec2f2049e1b60e92fdfbdbad9afb18a86bc | brlala/Educative-Grokking-Coding-Exercise | /04. Fast Slow pointers/5 Palindrome LinkedList (medium).py | 2,691 | 4.34375 | 4 | # Problem Statement
# Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not.
#
# Your algorithm should use constant space and the input LinkedList should be in the original form once the algorithm
# is finished. The algorithm should have O(N)O(N) time complexity where ‘N’ is the number of nodes in the LinkedList.
from __future__ import annotations
class Node:
def __init__(self, value, next: Node = None):
self.value = value
self.next = next
def is_palindromic_linked_list(head: Node):
"""
Time: O(N)
Space: O(1)
"""
x = head
print(f"Initial: {print_linked_list(x)}")
if head is None or head.next is None:
return True
slow = fast = head
# find middle of the linkedlist
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
# reverse list
head_second_half = reverse(slow)
print(f"Second half head + reversed: {print_linked_list(head_second_half)}")
print(f"Head: {print_linked_list(x)}")
copy_head_second_half = head_second_half
while head is not None and head_second_half is not None:
if head.value != head_second_half.value:
break # not palindrome
head = head.next
head_second_half = head_second_half.next
reverse(copy_head_second_half)
print(f"Reversing back: {print_linked_list(x)}")
if head is None or head_second_half is None:
return True
return False
def reverse(current: Node) -> Node:
# stash the next pointer first, because we need to know where to go
# previous node become the node we're sitting on
# advance current pointer
prev = None
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
return prev
def print_linked_list(current: Node):
# stash the next pointer first, because we need to know where to go
# previous node become the node we're sitting on
# advance current pointer
res = []
while current is not None:
res.append(str(current.value))
current = current.next
return '-'.join(res)
if __name__ == '__main__':
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(3)
head.next.next.next.next.next = Node(2)
head.next.next.next.next.next.next = Node(1)
print(f"LinkedList is palindromic: {is_palindromic_linked_list(head)}")
head.next.next.next.next.next.next.next = Node(2)
print(f"LinkedList is palindromic: {is_palindromic_linked_list(head)}")
| true |
f61446620ae9390b2a49a31edd991f59a44fd4b0 | brlala/Educative-Grokking-Coding-Exercise | /11. Pattern Subsets/2. Subsets With Duplicates (easy).py | 856 | 4.125 | 4 | # Problem Statement
# Given a set with distinct elements, find all of its distinct subsets.
def find_subsets(nums):
"""
Time:
Space:
"""
list.sort(nums)
subsets = [[]]
start = end = 0
for i in range(len(nums)):
start = 0
# if current element and previous element is same, create new subsets only from the subsets added in the previous
# step
if i > 0 and nums[i] == nums[i-1]:
start = end + 1
end = len(subsets) - 1
for j in range(start, end + 1):
subsets.append(subsets[j] + [nums[i]]) # create a new subset from the existing subset and insert the current
return subsets
def main():
print("Here is the list of subsets: " + str(find_subsets([1, 3, 3])))
print("Here is the list of subsets: " + str(find_subsets([1, 5, 3, 3])))
main()
| true |
506c4f0512af2dc99bfb707c5007be07fb74c28f | Avani22/Sorting-Algorithms | /mergesort.py | 2,974 | 4.15625 | 4 | '''
Name: Avani Chandorkar
'''
from datetime import datetime #package for calculating execution time of mergesort
import random #package for generating random numbers
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mid of the array
left = arr[:mid] # Dividing the array elements into 2 halves (left subarray)
right = arr[mid:] # (right subarray)
mergeSort(left) # MergeSort on the first half
mergeSort(right) # MergeSort on the second half
i = j = k = 0
# Copy data to temp arrays left[] and right[]
while i < len(left) and j < len(right):
if left[i] < right[j]: #condition to check smaller number
arr[k] = left[i] #copying the number to final sorted array
i += 1 #incrementing value of i by 1
else:
arr[k] = right[j] #copying the number to final sorted array
j += 1 #incrementing value of j by 1
k += 1 #incrementing value of k by 1
while i < len(left): # condition to check if any element was left
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
def printList(arr): #function to print the list of numbers
for i in range(len(arr)):
print(arr[i])
print()
if __name__ == '__main__':
arr = []
size = int(input("Enter size of the list: ")) #entering the size of array
for i in range(size): #loop for entering the numbers in the given range
elements = int(input("Enter an element:"))
arr.append(elements)
n = len(arr) #calculating the length of array
print("Array to be sorted is:")
print(arr)
t1 = datetime.now() #calculating current time
mergeSort(arr) #calling mergesort function
print("Sorted array is:")
print(arr)
t2 = datetime.now() #calculating current time
print("Sorted list of size {} in {}".format(len(arr), t2 - t1)) #calculating total time elapsed for mergesort
'''
arr = [random.randrange(1000) for _ in range(1000)] # Randomly generate 1000 numbers
#arr=list(range(100))
n = len(arr) # calculating the length of array
print("Array to be sorted:")
printList(arr)
t1 = datetime.now() # calculating current time
mergeSort(arr) # calling mergesort function
print("Sorted array is:")
printList(arr)
t2 = datetime.now() # calculating current time
print("Sorted list of size {} in {}".format(len(arr), t2 - t1)) # calculating total time elapsed for mergesort
''' | true |
6a47a7197217100ca17e9e7639f453f8c1cb9cbd | Sahoju/old-course-material-and-assignments | /python/a14.py | 838 | 4.28125 | 4 | # Write a function called symbols that takes a string
# containing +, = and letters. The function should
# return True if all of the letters in the string
# are surrounded by a + symbol.
def IsSurroundedBy(stuff):
plusopen = False
for i in stuff:
if i == '+' and plusopen == False:
plusopen = True
elif i == '+' and plusopen == True:
plusopen = False
if i.isalpha():
if plusopen == False:
print(i, "is missing a + from its left side!")
return False
if plusopen == True:
print(i, "is missing a + from its right side!")
return False
else:
print("Everything is alright!")
IsSurroundedBy("+a+")
IsSurroundedBy("+a")
IsSurroundedBy("a+")
IsSurroundedBy("+a+a+")
IsSurroundedBy("+=========a===========+")
| true |
c599d72d60ecb050e89cc651dd25d3834174b44b | Sahoju/old-course-material-and-assignments | /python/a10.py | 443 | 4.34375 | 4 | # Write a function, called largest, that is given a list of numbers
# and the function returns the largest number in the list.
def Largest(nums):
count = 0
largest = 0
for i in nums:
if largest < nums[count]: # i = the number in the table, not the index
largest = i
count += 1
print(largest)
nums = [5,2,3,7,1]
print(nums)
Largest(nums)
print(max(nums)) # an easier way, for reference purposes
| true |
9ca5347804ef5bf66e9f0c62fea61b435929ac5f | lyndewright/codeguildlabs | /grading.py | 982 | 4.21875 | 4 | # version 2
score = input("What is your score?: ")
grade = int(score)
if grade >= 97:
print("You got an A+!")
elif grade >= 93:
print("You got an A!")
elif grade >= 90:
print("You got an A-!")
elif grade >= 87:
print("You got a B+!")
elif grade >= 83:
print("You got a B!")
elif grade >= 80:
print("You got a B-!")
elif grade >= 77:
print("You got a C+!")
elif grade >= 73:
print("You got a C!")
elif grade >= 70:
print("You got a C-!")
elif grade >= 67:
print("You got a D+!")
elif grade >= 63:
print("You got a D!")
elif grade >= 60:
print("You got a D-!")
else:
print("You got an F!")
satisfaction = input("Are you happy with your grade? Type '1' for 'Yes.' Type '2' for 'No.' 1 or 2?: ")
happy = int(satisfaction)
if happy == 1:
print("I'm happy for you!")
elif happy == 2:
print("That's too bad. There's always next time.")
else:
print("Maybe your grade would be different if you followed directions better!")
| true |
c4d3d1aee6d92aeb738e5b9ff8c93a33cfc63066 | mmacedom/various_exercises | /String Exercises.py | 2,964 | 4.1875 | 4 | def check_password(passwd):
""" (str) -> bool
A strong password has a length greater than or equal to 6, contains at
least one lowercase letter, at least one uppercase letter, and at least
one digit. Return True iff passwd is considered strong.
>>> check_password('I<3csc108')
True
"""
lower = False
upper = False
digit = False
if len(passwd) < 6:
return False
for char in passwd:
if char.islower() and not lower:
lower = True
if char.isupper() and not upper:
upper = True
if char.isdigit() and not digit:
digit = True
if lower and upper and digit:
return True
else:
return False
def contains_no_lowercase_vowels(phrase):
""" (str) -> bool
Return True iff (if and only if) phrase does not contain any lowercase vowels.
>>> contains_no_lowercase_vowels('syzygy')
True
>>> contains_no_lowercase_vowels('e')
False
>>> contains_no_lowercase_vowels('abc')
False
"""
for char in phrase:
if char in 'aeiou':
return False
return True
'''check if the length is less than 6
go through each letter:
check if its upper
check if its lower
check if its a digit
if it fufils all the conditions return ture'''
def every_nth_character(s, n):
result = ''
i = 0
while i < len(s):
result = result + s[i]
i = i + n
return result
def find_letter_n_times(s, letter, n):
i = 0
count = 0
while i < len(s):
if letter in s:
count = count + 1
i = i + 1
return count
def not_digit(s):
i = 0
while i < len(s) and s[i] not in '0123456789':
i = i + 1
return i
def count_collatz_steps(n):
steps = 0
while n > 1:
if n % 2 == 0:
n = n/2
steps = steps + 1
if n % 2 != 0:
n = (n * 3) + 1
steps = steps + 1
return steps
def count_uppercase(s):
upper = 0
for char in s:
if char.isupper():
upper = upper + 1
return upper
def all_fluffy(s):
if len(s) == len('fluffy'):
for char in s:
if char in 'fluffy':
return True
else:
return False
else:
return False
def add_underscore(s):
underscore = ''
i = 0
for char in s:
if i <= len(s):
underscore = underscore + char + '_'
i = i + 1
else:
underscore = underscore + char
i = i
return underscore
def different_types(obj1, obj2):
if type(obj1) != type(obj2):
return True
else:
return False
def is_right_triangle(side1, side2, hypotenuse):
if hypotenuse ** 2 == side1 ** 2 + side2 ** 2:
return True
else:
return False | true |
c1b2b09570e093f8293046bc5fa8366cdf84fcb1 | cMinzel-Z/Python3-review | /Py3_basic_exercises/dict_prac_b.py | 374 | 4.1875 | 4 | d = {"Tom" : 500, "Stuart" : 1000, "Bob" : 55, "Dave" : 21274}
'''
When using a dictionary it is possible to add and delete items from it.
Provide code to delete the entry for "Bob" and add an entry for "Phil".
'''
print('修改前: ', d)
# delete the entry for "Bob"
del d['Bob']
print('删除后: ', d)
# add an entry for "Phil"
d['Phil'] = 2222
print('添加后: ', d)
| true |
eec695623763eef57194f2e77a861817dcb69263 | oketafred/python-sandbox | /backup.py | 2,185 | 4.34375 | 4 | # Author: Oketa Fred
# Laboremus Uganda Home Assignment
# Object Definition
class Account:
# Declaring a constructor Method
def __init__(self, balance = 0):
# self.owner = owner
self.balance = balance
self.pin = 1234
# A Method for Depositing Money in their account
def deposit(self, deposit_amount):
self.balance = self.balance + deposit_amount
print(f"You have deposited {deposit_amount} in your account")
print(f"You new account balance is {self.balance}")
# A Method for Withdrawing Money from their account
def withdrawal(self, withdrawal_amount):
if self.balance >= withdrawal_amount:
self.balance = self.balance - withdrawal_amount
print(f"You have withdrawn {withdrawal_amount}")
else:
print("Insufficient Fund")
# A Method for checking account balance
def check_account_balance(self):
print(f"Your account balance is {self.balance}")
# Object Creation or Instance of a class
a = Account()
# The Main Menu Function
def main_menu():
print("--------------------------------")
print("Welcome to HW MicroFinance Bank")
print("--------------------------------")
user_input = input("Enter d to deposit, w to withdraw and q to exit: ")
while user_input != "q":
if user_input == "d":
deposit_amount = int(input("Enter amount to deposit: "))
a.deposit(deposit_amount)
elif user_input == "b":
a.check_account_balance()
elif user_input == "w":
withdrawal_amount = int(input("Enter amount to withdraw: "))
a.withdrawal(withdrawal_amount)
else:
print("\nPlease check your input and try again")
user_input = input("\n Enter d to deposit, w to withdraw and q to exit: ")
def login():
user_pin = int(input("Please enter your pin: "))
if user_pin == a.pin:
main_menu()
else:
print("Please check your PIN number: ")
# main_menu()
login()
# account_owner_name = input("Enter your Full Name: ")
# deposit_amount = int(input("Enter amount to deposit: "))
# a = Account("Oketa", 500)
# a.deposit(deposit_amount)
# print("Welcome to HW MicroFinance Bank") | true |
54da815f590c4a179c4cbb62370363e4b3712594 | oketafred/python-sandbox | /data_structures.py | 458 | 4.40625 | 4 | """ List, Tuples, and Sets
"""
my_list_variable = ["Hello", "World", "Hi"]
my_tuple_variable = ("Hello", "World", "Hi")
my_set_variable = {"Hello", "World", "Hi"}
print(my_list_variable)
print(my_tuple_variable)
print(my_set_variable)
my_list_variable.append("Jeni")
print(my_list_variable)
my_list_variable.pop()
my_list_variable.reverse
print(my_list_variable)
reverse_list = my_list_variable.reverse()
print(reverse_list) | false |
9f68a1d5e77682aa4b7247f8c0cca60ecf620244 | BAFurtado/Python4ABMIpea2020 | /classes/class_da_turma.py | 1,479 | 4.4375 | 4 | """ Exemplo de uma class construída coletivamente
"""
class Aluno:
def __init__(self, name):
self.name = name
self.disciplinas = list()
self.email = ''
class Turma:
def __init__(self, name='Python4ABMIpea'):
self.name = name
self.students = list()
def add_student(self, name):
self.students.append(name)
def remove_student(self, name):
self.students.remove(name)
def count_std(self):
return len(self.students)
def list_std(self):
for each in self.students:
print(each)
def __repr__(self):
return '{} tem {} alunos'.format(self.name, self.count_std())
if __name__ == '__main__':
t1 = Turma()
print(type(t1))
print(t1)
t1.add_student('Sirley')
t1.add_student('Paulo Sávio')
t1.add_student('Paulo Martins')
t1.add_student('Godoy')
t1.add_student('William')
t1.add_student('Alan')
t1.add_student('Diego')
t1.add_student('Bruno')
t1.add_student('Douglas')
t1.add_student('Kadidja')
t1.add_student('Marcio')
print(t1)
t1.list_std()
t1.add_student('Bernardo')
t1.remove_student('Bernardo')
t2 = Turma('Econometria')
for aluno in t1.students:
t2.add_student(aluno)
t2.remove_student('Sirley')
t2.remove_student('William')
t2.remove_student('Alan')
print(t2)
t2.list_std()
b = Aluno('Bernardo')
t3 = Turma('100daysofwebPython')
t3.add_student(b)
| false |
214f1f00e9ca825fdeb45226775989917a4a65e3 | HEKA313/Labs_Elya | /lab_2/Task_4.py | 427 | 4.21875 | 4 | # .Составить программу, которая по номеру семестра печатает курс, к которому
# относится введенный семестр (1 и 2 семестр - 1 курс, 3 и 4 семестр - 2 курс и т.
# д.).
a = int(input())
if a == 1 or a == 2:
b = 1
elif a == 3 or a == 4:
b = 2
elif a == 5 or a == 6:
b = 3
elif a == 7 or a == 8:
b = 4
print(b)
| false |
b5c8e669df6a0070a27898b9cdb353782c7b7ce1 | Max143/python-strings | /use of replace().py | 283 | 4.53125 | 5 | '''
Python Program to Replace all Occurrences of ‘a’ with $ in a String
'''
# string_name.replace(2 parameter)
# 1st - replacing element
#2nd - replacing with element
string = input("Enter a sentence(Including character a): ")
final = string.replace('a', '$')
print(final)
| true |
f24cdc28b2e7712258e855be357471e17dbe6d0f | Max143/python-strings | /largest word string comparison.py | 1,132 | 4.3125 | 4 | '''
Python Program to Take in Two Strings and Display the Larger String without Using Built-in Functions
''''
# using built in functions
str1 = input("Enter a word: ")
str2 = input("Enter another word: ")
char1 = 0
char2 = 0
for char in str1:
char1 += 1
for char in str2:
char2 += 1
print("First word character count: ",char1)
print("Second word character count: ",char2)
if char1 > char2:
print("Bigger string: ", str1)
else:
print("Bigger string: ", str2)
print("Modified Program - write a program above program and exclude whitespace and only count characters")
# Without using built in function to find the solution
# Removing whitespace from both string
str1 = input("Enter the first string: ")
new1 = str1.replace(" ", "")
str2 = input("Enter the second string : ")
new2 = str2.replace(" ", "")
char1 = 0
char2 = 0
for i in new1:
char1 += 1
for i in new2:
char2 += 1
print("The largest character word is: ")
if char1 > char2:
print(str1)
else:
print(str2)
print("---------------------------------")
print("Without Using Built-in function")
| true |
da4ead78d29cce9ec0529a70c503b78f9317d6dc | mugambi-victor/functions | /dict/dict.py | 381 | 4.25 | 4 | #syntax for py dictionaries
thisdict={"brand":"ford","model":"mustang","year":2010 }
print(thisdict)
#accessing a dictionary element
x=thisdict["model"]
#prints the value of the model key(i.e mustang)
print(x)
#merging two dictionaries
dict2={"name":"victor", "age":20, "gender":"male"}
def merge(thisdict,dict2):
return(dict2.update(thisdict))
merge(thisdict,dict2)
print(dict2) | true |
a9bd69a258cc93c57bed93df715237bece32be45 | cypggs/HeadFirstPython | /python/guess.py | 540 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
def shuru():
num1 = input("give me a num:")
print "Please guess a num."
num2 = 50
#a = input("give me a num:")
#if a > ok:
# print "no,ok is under %s",ok
#else
def isEqual(num1, num2):
num2 = 50
shuru()
if num1<num2:
print "no too small!"
shuru()
if num1>num2:
print "no too big!"
shuru()
if num1==num2:
print "Contracture you are handsome"
print "gusee a num"
num1 = input("give me a num:")
isEqual(num1,num2)
| false |
5210b35e0d5346475e083ad1d77f1c3f4fe8df48 | keerthidl/python-assignment- | /concatenate.py | 266 | 4.375 | 4 | string1=input(" enter the first to concatenate: ");
string2=input("enter the second to concatenate: ");
string3= string1+string2;
print("string after concatenate is: ", string3);
print("string1=", string1);
print("string2=", string2);
print("string3=", string3);
| true |
5fd6759dfd04a6abc7fe53ca4cfb571bc481fcc1 | fabiocoutoaraujo/CursoVideoPython | /mundo-03/aula19-Dicionarios.py | 1,025 | 4.15625 | 4 | filme = {
'titulo': 'Star Wars',
'ano': 1977,
'diretor': 'George Lucas',
'produtora': 'Lucasfilm'
}
print(filme)
print(filme['diretor'])
del filme['produtora']
print(filme.values())
print(filme.keys())
print(filme.items())
filme['elenco'] = 'Natalie Portman'
for k, v in filme.items():
print(f'O {k} é {v}')
print('-' * 30)
print(f'{"CRIANDO ESTADOS":^30}')
print('-' * 30)
estado1 = {
'uf': 'São Paulo',
'sigla': 'SP'
}
estado2 = {
'uf': 'Rio de Janeiro',
'sigla': 'RJ'
}
brasil = []
brasil.append(estado1)
brasil.append(estado2)
print(brasil)
print(brasil[0]["sigla"])
print('-' * 30)
print(f'{"CRIANDO PAÍS":^30}')
print('-' * 30)
estados = dict()
brasil = list()
for c in range(0, 3):
estados['uf'] = str(input('Unidade Federativa: '))
estados['sigla'] = str(input('Sigla do Estado: '))
brasil.append(estados.copy()) # para dicionários ñ consigo utilizar [:], por isso utilizar .copy()
for c in brasil:
for u, s in c.items():
print(f'O campo {u} tem o valor {s}.')
| false |
94be280021b0af439cc6da9c46626b6075f439ad | ColeRichardson/CSC148 | /lectures/lecture 8/nary trees.py | 1,304 | 4.125 | 4 | def __len__(self) -> int:
"""
returns the number of items contained in this tree
>>> t1 = Tree(None, [])
>>> len(t1)
0
>>> t2 = Tree(3, )
"""
if self.Is_empty():
return 0
size = 1
for child in self.children:
size += len(child)
return size
def count(self, item: Any):
"""return the number of occurences
of item in this tree."""
if self.is_empty():
return 0
else:
num = 0
if self.key == item:
num += 1
for child in self.children:
num += child.count()
return num
# Mutating methods
def delete_item(self, item: Any) -> bool:
"""
Delete one occurnce o the given item from this tree.
return true if item was deleted and flse otherwise
do not modif this tree if it does not contain item.
:param self:
:param item:
:return:
"""
if self.is_empty():
#the item is not in the tree
return False
elif self.key == item:
#we've found the item: now delete it
self._delete_root()
return True
else:
#loop through each child and stop the dirst time
# the time
def to_nested_list(self) -> List:
"""
:param self:
:return:
"""
if self.is_empty():
return []
| true |
e2c031b04449d83bf9c0ab5eb8d4050df614d4f9 | sampadadalvi22/Design-Analysis-Of-Algorithms | /measure_time.py | 447 | 4.21875 | 4 | import time
def recursive(n):
if n==1:
return n
else:
return n*recursive(n-1)
def iterative(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
print "fact programs check time using time clock function..."
n=input()
st=time.clock()
d1=iterative(n)
print d1
print "Iterative measure time is::",time.clock()-st
st1=time.clock()
dd=recursive(n)
print dd
print "Recursive measure time is::",time.clock()-st1
| true |
2dace7a580833de8437c52d46618eb1b6bfaf359 | SeeMurphy/INFM340 | /netflixstock.py | 793 | 4.1875 | 4 | # This is a python script to display the first 10 rows of a csv file on Netflix stock value.
# Importing CSV Library
import csv
# file name
filename = "netflix.csv"
# Fields and Rows list
fields = []
rows = []
# reading csv
with open(filename, 'r') as csvfile:
# csv reader object
csvreader = csv.reader(csvfile)
# extracting field names
fields = next(csvreader)
# extracting data rows
for row in csvreader:
rows.append(row)
# total number of rows
print("Total no. of rows: %d"%(csvreader.line_num))
# printing the field names
print('Field names are: ' + ', '.join(field for field in fields))
# printing the first 10 rows
print('\nFirst 10 rows are:\n')
for row in rows[:10]:
#parsing
for col in row:
print("%10s"%col),
print('\n')
| true |
434ec4c04c3602b8520502b9a80a840d65aa7d18 | pombredanne/snuba | /snuba/utils/clock.py | 945 | 4.15625 | 4 | import time
from abc import ABC, abstractmethod
class Clock(ABC):
"""
An abstract clock interface.
"""
@abstractmethod
def time(self) -> float:
raise NotImplementedError
@abstractmethod
def sleep(self, duration: float) -> None:
raise NotImplementedError
class SystemClock(Clock):
"""
A clock implementation that uses the system clock for the current time.
"""
def time(self) -> float:
return time.time()
def sleep(self, duration: float) -> None:
time.sleep(duration)
class TestingClock(Clock):
"""
A clock implementation that uses a stable time for testing. To advance
the time, use the ``sleep`` method.
"""
def __init__(self, epoch: float = 0.0) -> None:
self.__time = epoch
def time(self) -> float:
return self.__time
def sleep(self, duration: float) -> None:
self.__time = self.__time + duration
| true |
036901234da128c965221d41a041a39ee75b6f06 | sankeerthankam/Big-Data | /1. Python Essentials/4. For Loop.py | 2,124 | 4.6875 | 5 | ## This file contains functions that implments the following tasks using a for loop.
# 1. Write a program to print 10 even numbers and 10 odd numbers.
# 2. Write a program to find factorial of a number.
# 3. Write a program to generate tables of 10.
# 4. Write a program to add the digits of a number.
# 5. Write a program to reverse the digits of a number.
# 6. Write a program to generate 10 Fibonacci numbers
def for_ten_even_odd():
'''This function prints first 10 even and odd number using a for loop'''
evens = [i for i in range(21) if i>0 and i%2 == 0]
odds = [i for i in range(20) if i%2 != 0]
print("First 10 even numbers:", evens)
print("First 10 odd numbers:", odds)
for_ten_even_odd()
def for_factorial(num):
'''This function prints the factorial of a number using a for loop'''
product = 1
for i in range(num+1):
if i == 0:
pass
else:
product = product*i
return product
for_factorial(4)
def for_tables(num):
'''This function prints multiplication tables of a number using a for loop'''
for i in range(11):
if i == 0:
pass
else:
print("{0} x {1} = {2}".format(num, i, num*i))
for_tables(10)
def for_sum_of_digits(num):
'''This function sum of digits using a for loop'''
sum = 0
str_num = str(num)
for i in str_num:
sum = sum + int(i)
return sum
for_sum_of_digits(654)
def for_reverse_int(num):
'''This function prints reverse of a integer using a for loop'''
rev_str = ''
str_num = str(num)
last = len(str_num) - 1
for i in range(len(str_num)):
rev_str = rev_str + str_num[last - i]
return int(rev_str)
#return int(str(num)[::-1])
for_reverse_int(987)
def for_fibonacci(num):
'''This function prints fibonacci series using a for loop'''
a = 0
b = 1
print(a)
print(b)
for i in range(3, num+1):
# assinging sum to a new variable
c = a + b
# swapping two numbers
a = b
b = c
print(c)
for_fibonacci(6)
| true |
2678e925bc5c084d9f07339234b5051440ce8e96 | nikkiredfern/learning_python | /LPTHW/ex7.py | 1,406 | 4.15625 | 4 | #A print statement for the first line of 'mary had a little Lamb'.
print("Mary had a little lamb.")
#A print statement for the second line of 'mary had a little Lamb'. This line uses the format() function.
print("It's fleece was whit as {}.".format('snow'))
#A print statement for the third line of 'mary had a little Lamb'.
print("And everywhere that Mary went.")
print("." * 10) #what'd that do? This line timed
# A variable declaring the letter 'c'.
end1 = "C"
# A variable declaring the letter 'h'.
end2 = "h"
# A variable declaring the letter 'e'.
end3 = "e"
# A variable declaring the letter 'e', again.
end4 = "e"
# A variable declaring the letter 's'.
end5 = "s"
# A variable declaring the letter 'e'.
end6 = "e"
# A variable declaring the letter 'b'.
end7 = "B"
# A variable declaring the letter 'u'.
end8 = "u"
# A variable declaring the letter 'r'.
end9 = "r"
# A variable declaring the letter 'g'.
end10 = "g"
# A variable declaring the letter 'e'.
end11 = "e"
# A variable declaring the letter 'r'.
end12 = "r"
#watch that comma at the end. try removing it to see what happens. WHAT COMMA???? That comma. My code kept throwing an error!
# A print statement using half of the variables that are declared above.
print(end1 + end2 + end3 + end4 + end5 + end6, end = " ")
# A print statment using the other half of the variables declared above.
print(end7 + end8 + end9 + end10 + end11 + end12)
| true |
fc7778c3c6f2d58256a9787bf6eb39fc83358c04 | jpablolima/python | /entrada_de_dados.py | 1,384 | 4.1875 | 4 | """ nome = input('Digite seu nome: ')
num = input('Digite um número: ')
print (nome, num)
print('você digitou %s' %nome)
print("olá, %s" %nome)
"""
# Conversão de Dados de Entrada
""" anos = int(input('Anos de serviço: '))
valor_por_ano = float(input('valor por ano: '))
bonus= anos * valor_por_ano
print('bonus de R$ %5.2f' %bonus) """
# soma de valores inteiros
""" print('Soma de Valore inteiros!')
num_int1 = int(input('Digite um valor inteiro: '))
num_int2 = int(input('Digite um segundo valor inteiro: '))
soma = num_int1 + num_int2
print('Total:', soma)
"""
# Conversão de Metros em Milimetros
""" print('Conversão de Metros em Milimertros! Com números Inteiros')
metros = int(input('Digite um em metros:'))
milimetros = (metros) * 1000
print(milimetros, 'mm') """
# Calculo de Segundos
dias = int(input('Digite o número de dias: '))
horas = int(input('Digite as horas: '))
minutos = int(input('Digite os minutos: '))
segundos=int(input('Digite os segundos:'))
total_dias_segundos = (dias) * 86400
total_horas = (horas) * 3600
total_minutos = (minutos) * 60
total_segundos = (segundos) * 1
print(total_dias_segundos,'em segundos')
print(total_horas,'em segundoss')
print(total_minutos,'em segundos')
print(total_segundos,'em segundos')
total = (total_dias_segundos + total_horas + total_minutos + total_segundos)
print('total em segundos:', total)
| false |
09a0a30f121e6db1d223664044e80ff910618cb5 | axat1/Online-Course | /Python/Programming For EveryBody/Week7/assignment5-2.py | 841 | 4.15625 | 4 | # 5.2 Write a program that repeatedly prompts a user
# for integer numbers until the user enters
# 'done'. Once 'done' is entered, print out
# the largest and smallest of the numbers.
# If the user enters anything other than a valid number
# catch it with a try/except and put out an appropriate
# message and ignore the number. Enter 7, 2, bob, 10, and 4
# and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : break
try:
val = int(num)
except:
print('Invalid input')
if largest == None or smallest == None:
largest = val
smallest = val
if largest < val:
largest = val
if smallest > val:
smallest = val
print("Maximum is", largest)
print("Minimum is", smallest)
| true |
82696c0d17a2f6d472532155e1c7c882f89b1423 | CommitHooks/LeetCode | /moveZeros.py | 548 | 4.25 | 4 | #! python
# Given an array nums, write a function to move all 0's to the end of it
# while maintaining the relative order of the non-zero elements.
"""
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].
"""
def shuffleZeros(aList):
for item in aList:
if item is 0:
item = float('inf')
aList.sort()
for item in aList:
if item is float('inf'):
item = 0
return aList
nums = [0, 1, 0, 3, 12]
newList = shuffleZeros(nums)
print(newList)
| true |
3772c81192628309ad1849fb19c43d7cffce125e | wufans/EverydayAlgorithms | /2018/binary/278. First Bad Version.py | 1,681 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#@author: WuFan
# You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
#
# Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
#
# You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
#
# Example:
#
# Given n = 5, and version = 4 is the first bad version.
#
# call isBadVersion(3) -> false
# call isBadVersion(5) -> true
# call isBadVersion(4) -> true
#
# Then 4 is the first bad version.
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
def isBadVersion(num):
return True
s = 1
e = n
while s + 1 < e:
m = s + (e - s) // 2##注意整除!!!
if isBadVersion(m):
e = m
else:
s = m
if isBadVersion(s):
return s
return e
# low = 1
# high = n
# while (low < high):
# mid = (low + high) / 2
# if isBadVersion(mid) == True:
# high = mid
# else:
# low = mid + 1
# return int(high)
| true |
e096f073d9c0b65e3f5482499a37e31660115584 | wufans/EverydayAlgorithms | /2018/binary/*342. Power of Four.py | 1,920 | 4.125 | 4 | # -*- coding: utf-8 -*-
#@author: WuFan
"""
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
"""
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
"""
Consider the valid numbers within 32 bit, and turn them into binary form, they are:
1
100
10000
1000000
100000000
10000000000
1000000000000
100000000000000
10000000000000000
1000000000000000000
100000000000000000000
10000000000000000000000
1000000000000000000000000
100000000000000000000000000
10000000000000000000000000000
1000000000000000000000000000000
Any other number not it the list should be considered as invalid.
So if you XOR them altogether, you will get a mask value, which is:
1010101010101010101010101010101 (1431655765)
Any number which is power of 4, it should be power of 2, I use num &(num-1) == 0 to make sure of that.
Obviously 0 is not power of 4, I have to check it.
and finally I need to check that if the number 'AND' the mask value is itself, to make sure it's in the list above.
here comes the final code:
return num != 0 and num &(num-1) == 0 and num & 1431655765== num
"""
return num != 0 and num & (num - 1) == 0 and num & 1431655765 == num
# if (num <= 0):
# return False
# a = math.log(num, 4)
#这里需要判断a是否是整数,方法一:采用int强转,方法2,采用取整的方法
# return True if int(a) == a else False
# return True if math.floor(math.log(num,4)) == math.log(num,4) else False
## python int() round() floor()
# int()函数直接截去小数部分
# floor() 得到最接近原数但是小于原数的部分
# round() 得到最接近原数的整数(返回为浮点类型)
| true |
8c7aefb70da7f8fea7ead752722b183949f69e8c | Grazziella/Python-for-Dummies | /exercise8_1.py | 660 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 8.1 Write a function called chop that takes a list and modifies it, removing
# the first and last elements, and returns None.
# Then write a function called middle that takes a list and returns a new list that
# contains all but the first and last elements.
def chop(list_name):
first = list_name.remove(list_name[0])
last = list_name.remove(list_name[-1])
return first, last, list_name
def middle(list_name):
return list_name[0:len(list_name)]
fruits = ['apple', 'banana', 'strawberry', 'blueberry', 'mango', 'pear']
if __name__ == '__main__':
print(chop(fruits))
print(middle(fruits))
| true |
abdeb4ea68da78ea46bb279101b586c2c3fe61ff | Grazziella/Python-for-Dummies | /exercise6_1.py | 429 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 6.1 Write a while loop that starts at the last character in the string and
# works its way backwards to the first character in the string, printing each letter on
# a separate line, except backwards.
def backwards(string):
index = 0
while index < len(string):
index = index + 1
print(string[len(string) - index])
if __name__ == '__main__':
backwards('Banana')
| true |
4bd8769e19547eedba06518f117d0ac875966ae7 | Grazziella/Python-for-Dummies | /exercise10_2.py | 897 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 10.2 This program counts the distribution of the hour of the day for
# each of the messages. You can pull the hour from the “From” line by finding the
# time string and then splitting that string into parts using the colon character. Once
# you have accumulated the counts for each hour, print out the counts, one per line,
# sorted by hour as shown below.
# Sample Execution:
# python timeofday.py
# Enter a file name: mbox-short.txt
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
def hours():
opf = open('mbox-short.txt')
list_hours = []
d_mail = {}
for line in opf:
if line.startswith('From '):
list_hours = line.split()
h = list_hours[5]
time = h[:h.find(':')]
d_mail[time] = d_mail.get(time, 0) + 1
t_mail = d_mail.items()
t_mail.sort()
for ht in t_mail:
print(ht)
if __name__ == '__main__':
hours()
| true |
818fef536b7f0c12df16c97815bc8ec3c866fff1 | mkcor/GDI-for-PyCon | /drinking_age.py | 756 | 4.25 | 4 | # Script returning whether you are allowed to drink alcohol or not, based on
# age and place, to illustrate conditional statements
age = raw_input('What is your age? ')
age = int(age)
place = raw_input('What is your place? (Capitalize) ')
legal18 = ['AB', 'MB', 'QC']
legal19 = ['BC', 'ON', 'SK']
legal21 = ['MA', 'NY', 'VT']
if place not in legal18 + legal19 + legal21:
print('This location is not supported')
else:
if age >= 21:
print('You are allowed to drink alcohol')
elif age >= 19 and place in legal19:
print 'You are allowed to drink alcohol in', place
elif age >= 18 and place in legal18:
print 'You are allowed to drink alcohol in', place
else:
print('You are not allowed to drink alcohol')
| true |
afb515883cd152b0f3d45e0acbcc6ca2551894a8 | Umotrus/python-lab2 | /Ex1.py | 833 | 4.125 | 4 |
# Exercise 1
task_list = []
while True:
print("\n\nTo do manager:\n\n 1.\tinsert a new task\n 2.\tremove a task\n")
print(" 3.\tshow all existing tasks\n 4.\tclose the program\n\n")
cmd = input("Command: ")
if cmd == "1":
# Insert a new task
task = input("New task: ")
task_list.append(task)
elif cmd == "2":
# remove a task
task = input("Task to be deleted: ")
if task_list.__contains__(task):
task_list.remove(task)
else:
print("Task %s is not in the list" % task)
elif cmd == "3":
# Show existing tasks in alphabetical order
print("To do list: %s" % sorted(task_list))
elif cmd == "4":
# Close
break
else:
# Default
print("\nUnknown command %s\n\n" % cmd)
| true |
7a92ffdb91f0be82f79f07367b2e79f0fbca621a | Vasudevatirupathinaidu/Python_Harshit-vashisth | /179_c15e1.py | 327 | 4.21875 | 4 | # define generator function
# take one number as argument
# generate a sequence of even numbers from 1 to that number
# ex: 9 --> 2,4,6,8
def even_numbers(n):
for num in range(1,n+1):
if (num%2==0):
yield num
for even_num in even_numbers(9):
print(even_num)
for even_num in even_numbers(9):
print(even_num) | true |
98e2523e4b56507b53d3c3f64cd427b390f601c6 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /143_c11e1.py | 381 | 4.125 | 4 | # example
# nums = [1,2,3]
# to_power(3, *nums)
# output
# list --> [1, 8, 27]
# if user didn't pass any args then given a user a message 'hey you didn't pass args'
# else return list
def to_power(num, *args):
if args:
return [i**num for i in args]
else:
return "You didn't pass any args"
nums = [1, 2, 3]
print(to_power(3, *nums))
print(to_power(3))
| true |
761d366c09b3f35a46917d42c16d13087f6193bd | Vasudevatirupathinaidu/Python_Harshit-vashisth | /82_intro_list.py | 500 | 4.46875 | 4 | # data structures
# list ---> this chapter
# ordered collection of items
# you can store anything in lists int, float, string and other data types
numbers = [1, 2, 3, 4, 5]
print(numbers)
print(numbers[1])
print()
words = ['word1', 'word2', 'word3']
print(words)
print(words[1:])
print()
mixed = [1, 2, 3, 4, "five", "six", 7.2, None, True]
print(mixed)
print(mixed[-1])
print()
a, b, c = "two"
print(a, b, c)
a, b, c, *d = "two123"
print(a, b, c, d)
a, b, c, *_ = "two234234"
print(a, b, c)
| true |
18fcf05ba238186d9ae399ffe119a86b8bb7a825 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /110_more_about_tuples.py | 896 | 4.46875 | 4 | # looping in tuples
# tuple with one element
# tuple without parenthesis
# tuple unpacking
# list inside tuple
# some functions that you can use with tuples
mixed = (1, 2, 3, 4, 0)
# looping in tuples
for i in mixed:
print(i)
print()
# tuple with one element
nums = (2,)
words = ('word1',)
print(type(nums))
print(type(words))
print()
# tuple without parenthesis
guitars = 'yamaha', 'baton rouge', 'taylor'
print(type(guitars))
print()
# tuple unpacking
guitarists = ('Maneli Jamal', 'Eddie Van Der Meer', 'Andrew Foy')
guitarist1, guitarist2, guitarist3 = (guitarists)
print(guitarist1)
print(guitarist2)
print(guitarist3)
print()
# list inside tuples
favorites = ('southern magnolia', ['Tokyo Ghoul Theme', 'landscape'])
favorites[1].pop()
print(favorites)
favorites[1].append("we made it")
print(favorites)
print()
# sum, min and max function
print(min(mixed))
print(max(mixed))
print(sum(mixed))
| true |
68eaca1696c5a1ac8869ffddc78d56b68f799967 | Vasudevatirupathinaidu/Python_Harshit-vashisth | /114_dict_intro.py | 1,073 | 4.5 | 4 | # dictionaries intro
# Q - Why we use dictionaries?
# A - Because of limitations of lists, lists are not enough to represent real data
# Example
user = ["vasudev", 26, ['tenet', 'inception'], ['awakening', 'fairy tale']]
# this list contains user name, age, fav movies, fav tunes
# you can do this but this is not a good way to do this
# Q - what are dictionaries
# A - unordered collection of data in key : value pair
# how to create dictionaries
user = {'name': 'vasudev', 'age': 26}
print(user)
print(type(user))
print()
# second method to create dictionary
user1 = dict(name='vasudev', age=26)
print(user1)
print()
# access data
print(user["name"])
print(user["age"])
print()
# dictionary can store numbers, strings, list, dictionary
user_info = {
'name': 'Vasudev',
'age': 24,
'fav_movies': ['Inception', 'Tenet'],
'fav_tunes': ['awakening', 'fairy tale']}
print(user_info)
print(user_info['fav_movies'])
print()
# add data to empty dictionary
user_info2 = {}
user_info2['name'] = 'deva'
user_info2['age'] = 25
print(user_info2)
print()
| true |
e7a91f0a2212f54a2fe76891a02f45dd057e1573 | sahuvivek083/INFYTQ-LEVEL-2-SOLUTIONS | /problem21_L2.py | 957 | 4.40625 | 4 | """
Tom is working in a shop where he labels items. Each item is labelled with a number between
num1 and num2 (both inclusive).
Since Tom is also a natural mathematician, he likes to observe patterns in numbers.
Tom could observe that some of these label numbers are divisible by other label numbers.
Write a Python function to find out those label numbers that are divisible by another label
number and display how many such label numbers are there totally.
Note:- Consider only the distinct label numbers. The list of those label numbers should be
considered as a set.
"""
def check_numbers(num1,num2):
num_set=set()
num_list=list(range(num2,num1-1,-1))
for i in range(len(num_list)):
for j in range(i+1,len(num_list)):
if num_list[i] % num_list[j]==0:
num_set.add(num_list[i])
count=len(num_set)
return [num_set,count]
num1=2
num2=20
print(check_numbers(num1,num2))
| true |
f3e50dd8085f37eb1125d2b1d013d1c0e308a5fd | SimonXu0811/Python_crash | /classes.py | 931 | 4.21875 | 4 | # A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object
class User:
# Constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
def greeting(self):
return f'My name is {self.name} and I am {self.age}'
def has_birthday(self):
self.age += 1
# Extend class
class Customer(User):
# Constructor
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
self.balance = 0
def set_balance(self, balance):
self.balance = balance
# Initial user object
brad = User('Brad', 'test@test.com', 37)
# Initial customer object
Jelly = Customer('Jelly', '123@qwe.com', 25)
Jelly.set_balance(500)
print(Jelly.greeting())
brad.has_birthday()
print(brad.greeting()) | true |
88ebd8f4f7a244949bdeafabaad1a8e22232c29e | ukhlivanov/python_learning | /assignments/variables.py | 2,599 | 4.21875 | 4 | # print("Hello world")
# print("Hello Liana")
# x=1
# x=2
# print(x)
# print(type(x))
name = "Hello World"
text = "test message"
n = 5
# STRINGS--------------------------
# print(name[5:])
# print(name[:5])
# print(name[1:7])
# print(name[1:6:2]) # start stop step
# print(name[::-1]) # reverse string
# print("tinker"[:3])
# print(name*2 + " " + text + str(n))
# print(text.split())
# print("This is a string {}".format("INSERTED"))
# print("One two {} {} {}".format('three', 'four', 'five'))
# print("One two {0} {1} {2}".format('three', 'four', 'five'))
# print("One two {2} {1} {1}".format('three', 'four', 'five'))
# print("One two {a} {b} {c}".format(a='three', b='four', c='five'))
# print(f'My string is {text}')
# result = 100/777
# print("The result was {r:1.3f}".format(r=result)) # format floating {value:width.precision f}
#LIST---------------------------------------
# my_list = [1,2,3,4]
# my_str = ['str1', 'str2', 'str3', 'str4']
# print(my_list[2:])
# print(my_list + my_str[2:])
# print((my_list + my_str)[2:])
# tmp = my_str[0]
# tmp = tmp[:3]+str(5)
# my_str[0] = tmp
# print(my_str)
# tmp = my_list.pop()
# print(my_list)
# print(tmp)
# my_list.append(5)
# my_list.append(5)
# print(my_list)
# my_list.insert(0, 6)
# print(my_list)
# my_list.remove(2)
# print(my_list)
# a = my_list.copy()
# b = a.sort()
# print(b)
# print(a)
# a.reverse()
# print(a)
# print(a.count(5))
# del a[1:]
# print(a)
# print(my_list)
# tmp = my_list.pop(1)
# print(my_list)
# print(tmp)
# c = [1,1,[1,2]]
# print(c[2][1])
# d = ['a','b', 'c']
# print(d[1:])
#Dictionaries------------------------------
# obj = {
# 'name' : 'Serg',
# 'age': 33,
# 'moto': {
# 'k': ['BMW', 'Audi'],
# 'm': 'Suzuki'
# }
# }
# print(obj.values())
# print(obj.keys())
# obj.update({'name': 'LLL'})
# print(obj.values())
# print(obj.get('age'))
# print(obj.items())
# print(obj['name'])
# # print(obj)
# # p = obj.pop('name')
# # print(p)
# # print(obj)
# print(obj['moto']['k'][0].lower())
# obj['loc'] = 'CA'
# print(obj)
# obj['age']= 30
# print(obj)
#TUPLES-------------------------------
# my_tuple = (1,2,3,'a','b','a')# immutable
# my_list = [1,2,3] #mutable
# print(type(my_tuple))
# print(type(my_list))
# print(my_tuple.count('a'))
# print(my_tuple.index('a'))
#SETS-----------------------------------
#unordere collections of unique elements
myset = set()
print(type(myset))
myset.add(1)
myset.add(2)
print(myset)
myset.add(1)
print(myset)
mylist = [1,1,1,'one','one','one']
print(mylist)
print(set(mylist))
s = 'aabbcc'
print(set(s))
| false |
9e1d61a7d89e200a4cab89240ac3f2058887268f | AnonymousAmalgrams/Berkeley-Pacman-Projects | /Berkeley-Pacman-Project-0/priorityQueue.py | 1,573 | 4.125 | 4 | #Priority Queue
import heapq
class PriorityQueue:
def __init__(pq):
pq.heap = []
pq.count = 0
def pop(pq):
# Check if the heap is empty before popping an element
if pq.isEmpty():
print("The heap is empty.")
return False
pq.count -= 1
return heapq.heappop(pq.heap)[-1]
def push(pq, item, priority):
# Check if item already exists in heap
for i in range(len(pq.heap)):
if (pq.heap[i])[1] == item:
# If Element already exists don't push it and return False
return False
heapq.heappush(pq.heap, (priority , item))
pq.count += 1
return True
def isEmpty(pq):
return not pq.heap
def update(pq,item,priority):
i = -1
for x in pq.heap:
i += 1
# x[0] is the element and x[1] is the priority
if x[1] == item:
if x[0] > priority:
pq.heap[i] = (priority , item)
heapq.heapify(pq.heap)
return True
else:
# If x[0]'s priority <= new priority don't make changes
return False
# If Element does not exist push it in heap
pq.push(item, priority)
return True
def PQSort(list):
q = PriorityQueue()
x = []
for i in range(len(list)):
q.push(list[i] , list[i])
for i in range(len(list)):
x.append(q.pop())
return x
| true |
ead6c12611f781265a525c09f45f90fd9678f091 | adityabads/cracking-coding-interview | /chapter2/8_loop_detection.py | 1,427 | 4.15625 | 4 | # Loop Detection
# Given a circular linked list, implement an algorithm that returns the node at the
# beginning of the loop.
#
# DEFINITION
# Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so
# as to make a loop in the linked list.
#
# EXAMPLE
# Input: A -> B -> C - > D -> E -> C [the same C as earlier]
# Output: C
from linkedlist import LinkedList
import unittest
def has_loop(lst: LinkedList) -> bool:
"""Returns true iff linked list has a loop"""
slow = lst.head
if slow:
fast = lst.head.next
else:
return False
while fast and fast.next:
if slow is fast:
return True
slow = slow.next
fast = fast.next.next
return False
class TestLoopDetection(unittest.TestCase):
def test_has_loop(self):
tests = ["abcdef", "abcabc", "aaaa"]
for test in tests:
with self.subTest(test=test):
lst = LinkedList(test)
self.assertFalse(has_loop(lst))
lst.append_node(lst.head)
self.assertTrue(has_loop(lst))
lst = LinkedList(test)
lst.append_node(lst.head.next)
self.assertTrue(has_loop(lst))
lst = LinkedList(test)
lst.append("a")
self.assertFalse(has_loop(lst))
if __name__ == "__main__":
unittest.main()
| true |
b74c20932a29c3e28caa3ce18cb499a3967b4612 | adityabads/cracking-coding-interview | /chapter5/8_draw_line.py | 1,556 | 4.375 | 4 | # Draw Line
# A monochrome screen is stored as a single array of bytes, allowing eight
# consecutive pixels to be stored in one byte. The screen has width w,
# where w is divisible by 8 (that is, no byte will be split across rows).
# The height of the screen, of course, can be derived from the length of the
# array and the width. Implement a function that draws a horizontal line from
# (x1, y) to (x2, y). The method signature should look something like:
# drawline(byte[] screen, int width, int x1, int x2, int y)
import unittest
def draw_line(screen: int, length: int, width: int, x1: int, x2: int, y: int) -> int:
"""Draw line from (x1, y) to (x2, y), 1-indexed starting from upper left"""
mask = 0
for _ in range(x1, x2 + 1):
mask |= (1 << (width - y))
mask <<= width
for _ in range(length - x2 - 1):
mask <<= width
return screen | mask
def visualize(screen: int, width: int) -> None:
n = bin(screen)[2:]
for i, val in enumerate(n):
print(val, end=" ")
if (i + 1) % width == 0:
print()
print()
class TestDrawLine(unittest.TestCase):
def test_draw_line(self):
screen = 1 << 127
length = 8
width = 16
tests = [
[3, 4, 5],
[2, 7, 9],
[2, 4, 1],
[4, 4, 1],
[1, 1, 8]
]
for x1, x2, y in tests:
newscreen = draw_line(screen, length, width, x1, x2, y)
visualize(newscreen, width)
if __name__ == "__main__":
unittest.main()
| true |
e58b65f0e51d929b75cca9d87e990bfa21622ef5 | 4ratkm88/COM404 | /1-Basics/5-Function/8-function-calls/bot.py | 1,133 | 4.40625 | 4 | #1) Display in a Box – display the word in an ascii art box
def ascii(asciiword):
print("#####################")
print("# #")
print("# #")
print("# " + word + " #")
print("# #")
print("# #")
print("# #")
print("#####################")
#2) Display Lower-case – display the word in lower-case e.g. hello
def lower(lowerword):
lowerword ==lower(word)
print(str(word))
#3) Display Upper-case – display the word in upper-case e.g. HELLO
def upper(upperword):
upperword == Upper(word)
print(str(upperword))
#4) Display Mirrored – display the word with its mirrored word e.g. Hello | olleH
#5) Repeat – ask the user how many times to display the word and then display the word that many times alternating between upper-case and lower-case.
def run():
print("Type a word")
word=str(input())
print("How many times should i display?")
times=int(input())
for count in range(0, times, 1):
lower(lowerword)
upper(upperword)
ascii()
run() | true |
e14c85cbf89f01060bd5ebbd251305c60a59f148 | josaphatsv/ejercicios_py | /Leccion5/main.py | 647 | 4.375 | 4 | """Declaracion de variables"""
x = "Hola Mundo"
y = 12
z = True
a = 1.5
b = 3.141615
print(x)
"""Funcion que nos permite sabe que tipo de variable es """
print(type(x))
print(type(y))
print(type(z))
print(type(a))
print(type(b))
# forma de concatenar variables
nombre = "Josaphat"
print("Hola " + nombre + ", como estas hoy " + nombre)
# segunda forma de concatenar
print("Hola ", nombre, ", como ests hoy ", nombre)
# error comun
numero1 = "1"
numero2 = "2"
print(numero1 + numero2)
# solucion
print(int(numero1) + int(numero2))
#variables bloeano
variable=3>2
print(variable)
if variable:
print("Es verdadero")
else:
print("Es falso") | false |
9258d7fc28ee32985fd73019d1e6952cdd5edd88 | baharaysel/python-pythonCrashCourseBookStudy | /working_with_lists/dimensions.py | 1,206 | 4.375 | 4 |
##Defining a Tuple ()
#tuples value doesnt change
dimensions = (200, 50)
print(dimensions[0])
#200
print(dimensions[1])
#50
# dimensions[0] = 20 ## we cant change dimensions/tuple it gives error
###Looping Through All Values in a Tuple
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
#200
#50
###Writin over a Tuple # see tuple as one variable and change together
dimensions = (400, 100)
print(dimensions)
#(400, 100)
for dimension in dimensions:
print(dimension)
#400
#100
###TRY IT YOURSELF Page71
##4.13 Buffet
buffet_food = ('pasta', 'pizza', 'carrot cake', 'noodles', 'drinks')
for food in buffet_food:
print(food.title())
# buffet_food[0] = 'cant change the tuple you need to change whole tuple'
####couldnt solve this one
buffet_food = ('pasta', 'pizza', 'carrot cake', 'noodles', 'drinks') ## try to add 2 more food to a tuple by writing a code
buffet_food_2 = []
for food in buffet_food:
buffet_food_2.append(food)
buffet_food_2.append('wine') ####i have created new list instead of tuple with 2more items. this is not what they are exactly asking
buffet_food_2.append('shrimps')
print(buffet_food_2)
| true |
f66567a8b0bc4e00b77bb1576d93323c4f412558 | Geordous-Huxwell/basic-scripts | /mathModule.py | 647 | 4.125 | 4 | PI = 3.14159
def add(num1, num2):
return num1+num2
#subtract
#divide
#multiply
def fib(n):
assert (n >= 0), "Fibonacci only works for positive integers"
num1 = 0;
num2 = 1;
for i in range(1,n):
if(i%2==0):
num1 = num1 + num2
else:
num2 = num1 + num2
if(n%2==0):
return num2
else:
return num1
def fact(n):
if n < 0:
raise ArithmeticError
if n==0:
return 1
else:
return n*fact(n-1)
if __name__ == '__main__':
try:
print(fact(-4))
except ArithmeticError:
print("Invalid input")
try:
print(fib(-8))
except AssertionError as e:
print("Invalid input")
print(e) | false |
91fe1b8f64858ec255702a98e8d7955f6bc55917 | wildlingjill/codingdojowork | /Python/Python_OOP/OOP work/bike.py | 825 | 4.34375 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
# display price, max speed and total miles
def displayInfo(self):
print self.price, self.max_speed, self.miles
# display "riding" and increase miles by 10
def ride(self):
self.miles += 10
print "Riding"
# display "reversing" and decrease miles by 5
def reverse(self):
if self.miles == 0:
print "Can't reverse any further!"
else:
self.miles -= 5
print "Reversing"
bike1 = Bike(200, "25mph")
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(150, "20mph")
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
bike3 = Bike(175, "15mph")
bike3.reverse()
bike3.reverse()
bike3.reverse()
bike3.displayInfo() | true |
8dab221d5f2f483f3238197e072ec8245683966a | 121910313025/lab-01-09 | /l4(assign)-multiply spase matrix.py | 1,966 | 4.28125 | 4 | #Program to multiply sparse matrix
def sparse_matrix(a):
sm = []
row = len(a)
# Number of Rows
# Number of columns
col = len(a[0])
# Finding the non zero elements
for i in range(row):
for j in range(col):
if a[i][j]!=0:
sm.append([i,j,a[i][j]])
return sm
#multiplication of two sparse matrices
def mul(a1,a2):
row1 = len(a1)
row2 = len(a2)
col2 = len(a2[0])
out= [[0 for _ in range(col2)] for __ in range(row1)]
for i in range(row1):
for j in range(col2):
for k in range(row2):
out[i][j] += a1[i][k]*a2[k][j]
X = sparse_matrix(out)
return X
# printing of martix
def display(a):
if a==[]: print('EMPTY MATRIX')
for i in a:
print(*i)
# Function to take array input
def input_matrix(row):
a = [] # Declaring the matrix
i = 0
while i<row:
dup = list(map(int,input().split()))
a.append(dup)
i += 1
return a
# Inputting arrays
row1 = int(input("Enter the number of rows in first matrix : "))
col1 = int(input("Enter the number of columns in first matrix : "))
row2 = int(input("Enter the number of rows in second matrix : "))
col2 = int(input("Enter the number of columns in second matrix : "))
if col1!=row2:
print('You cannot multiply these matrices')
exit()
print("Enter Martix 1")
a1 = input_matrix(row1)
print("Enter Martix 2")
a2 = input_matrix(row2)
# Printing Original Matrices
print("The Original Matrices are")
print("Matrix 1")
display(a1)
print("Matrix 2")
display(a2)
print()
# Printing Sparse Matrices
print("The Sparse Matrices are")
sm1 = sparse_matrix(a1)
sm2 = sparse_matrix(a2)
print("Sparse Matrix 1")
display(sm1)
print("Sparse Matrix 2")
display(sm2)
print()
# Printing the result
print("Multiplication of 2 Sparse Matrices")
result = mul(sm1,sm2)
display(result)
| false |
97bf493dc0d69aead48bbb06797d22df294e36af | NSYue/cpy5python | /practical03/q7_display_matrix.py | 424 | 4.40625 | 4 | # Filename: q7_display_matrix.py
# Author: Nie Shuyue
# Created: 20130221
# Modified: 20130221
# Description: Program to display a n by n matrix
# with random element of 0 or 1
# Function
def print_matrix(n):
import random
for i in range(0, n):
for j in range(0, n):
print(random.randint(0,1), end=" ")
print()
# main
n = int(input("Enter the number of lines in matrix: "))
print_matrix(n)
| true |
bef4cb4ec0ed43df16080920746692a341ab61fa | NSYue/cpy5python | /practical01/q4_sum_digits.py | 516 | 4.21875 | 4 | # Filename:q4_sum_digits.py
# Author: Nie Shuyue
# Date: 20130122
# Modified: 20130122
# Description: Program to get an integer between 0 and 1000
# and adds all the digits in the integer.
#main
#prompt and get the integer
integer = int(input("Enter the integer between 0 and 1000: "))
#get the sum of the last digit
sum=0
while (integer>0):
sum+=integer%10
# remove the extracted digit
integer//=10
# repeat the whole function until
# all the digits are added together
# display result
print (sum)
| true |
d5613dc4df322b5616137f1ef2ce62b5115ab2a1 | NSYue/cpy5python | /practical02/q08_top2_scores.py | 898 | 4.1875 | 4 | # Filename: q08_top2_scores.py
# Author: Nie Shuyue
# Created: 20130204
# Modified: 20130205
# Description: Program to get the top 2 scores of a group of students
# main
# prompt and get the number of students
num = int(input("Enter the number of students: "))
# define top, second score and the names
top = -10000
sec = -10000
ntop = ""
nsec = ""
# get the name and the score
for i in range (0, num):
name = input("Enter the name of the student: ")
score = int (input("Enter the score of the student: "))
# process and find out the top and second scores
if score > top:
sec = top
nsec = ntop
top = score
ntop = name
elif score > sec:
sec = score
nsec = name
# display the results
print("Highest scorer is: ", ntop)
print("Highest score is: ",top)
print("Second highest scorer is :", nsec)
print("Second highest score is: ",sec)
| true |
09b1b06da84eda85e5c3e6ff404513a7913aafeb | NSYue/cpy5python | /practical02/q02_triangle.py | 504 | 4.40625 | 4 | # Filename:q02_triangle.py
# Author: Nie Shuyue
# Date: 20130129
# Modified: 20130129
# Description: Program to identify a triangle
# and calculate its perimeter.
# main
# Prompt and get the length of each
# side of the triangle
a = int(input("Enter side 1:"))
b = int(input("Enter side 2:"))
c = int(input("Enter side 3:"))
# identify the triangle
if a + b > c and a + c > b and b + c > a:
d = a + b + c
# display the reslut
print("Perimeter = ", d)
else:
print("Invalid triangle!")
| true |
8c00568cbebfe8b2af4ac93318214e79e7114a5c | mayababuji/MyCodefights | /reverseParentheses.py | 920 | 4.25 | 4 | #!/usr/bin/env python
#-*- coding : utf-8 -*-
'''
You have a string s that consists of English letters, punctuation marks, whitespace characters, and brackets. It is guaranteed that the parentheses in s form a regular bracket sequence.
Your task is to reverse the strings contained in each pair of matching parentheses, starting from the innermost pair. The results string should not contain any parentheses.
Example
For string s = "a(bc)de", the output should be
reverseParentheses(s) = "acbde".
'''
def reverseParentheses(s):
for i in range(len(s)):
if s[i] == "(":
start = i
#print start
#print (s[:start])
if s[i] == ")":
end = i
#print (end)
print s[start+1:end:-1]
return reverseParentheses(s[:start] + s[start+1:end][::-1] + s[end+1:])
return s
s = "a(bcdefghijkl(mno)p)q"
print reverseParentheses(s)
| true |
c803e5741a091549edbc025bd3398b22ea6b3bd1 | KrushnaDike/My-Python-Practice | /TutorialsPy/tute29EX.py | 689 | 4.1875 | 4 | # Pattern Printing
# By using while loop
# n = int(input("Enter a Number :"))
# bool2 = int(input("Enter 1 for TRUE and 0 for FALSE :"))
# bool(bool2)
# if bool2 == False:
# i = 0
# while n>=i:
# print("*"*n)
# n -= 1
# elif bool2 == True:
# i = 0
# while i<=n:
# print("*"*i)
# i += 1
# else:
# print("Plz Enter Correct Input...!")
# By using for loop
n = int(input("Enter a Number :"))
bool2 = int(input("Enter 1 for TRUE and 0 for FALSE :"))
bool(bool2)
if bool2 == True:
for i in range(0, n+1):
print("❤"*i)
elif bool2 == False:
for i in range(n, 0, -1):
print("❤"*i)
| false |
b54d6a6018b9ad367195c0e90de0d13010a898ad | macjabeth/Lambda-Sorting | /src/iterative_sorting/iterative_sorting.py | 1,918 | 4.21875 | 4 | # TO-DO: Complete the selection_sort() function below
# def selection_sort(arr):
# count = len(arr)
# # loop through n-1 elements
# for i in range(count-1):
# cur_index = i
# smallest_index = cur_index
# # TO-DO: find next smallest element
# # (hint, can do in 3 loc)
# for j in range(cur_index, count):
# if arr[j] < arr[smallest_index]:
# smallest_index = j
# # TO-DO: swap
# arr[cur_index], arr[smallest_index] = arr[smallest_index], arr[cur_index]
# return arr
def selection_sort(arr):
count = len(arr)
# repeat arr[n-1] times
for i in range(count-1):
# set first element as minimum
min_value = i
# for each unsorted element
for j in range(i, count):
# if element is less than current minimum
if arr[j] < arr[min_value]:
# set element as new minimum
min_value = j
# swap minimum with first element position
arr[min_value], arr[i] = arr[i], arr[min_value]
# return sorted array
return arr
# TO-DO: implement the Bubble Sort function below
# def bubble_sort(arr):
# count = len(arr)
# for i in range(count):
# for j in range(count-1):
# if arr[j+1] < arr[j]:
# arr[j], arr[j+1] = arr[j+1], arr[j]
# return arr
def bubble_sort(arr):
count = len(arr)-1
swapped = True
while swapped:
# reset swapped value
swapped = False
for i in range(count):
# is left element greater than right element?
if arr[i] > arr[i+1]:
# swap and update status
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = True
# return sorted array
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
64a1ce9f6a308e0a4b2bdaa30ea59e53f140ae9c | emanuel-mazilu/python-projects | /calculator/calculator.py | 1,567 | 4.375 | 4 | import tkinter as tk
# the display string
expression = ""
# TODO
# Division by 0
# invalid expressions
def onclick(sign):
global expression
# Evaluate the expression on the display ex: 2+3/2-6*5
if sign == "=":
text_input.set(eval(expression))
expression = ""
# clear the memory and the display
elif sign == "C":
text_input.set("")
expression = ""
# adds numbers and operators one after another
else:
expression = expression + str(sign)
text_input.set(expression)
# create main window
calc = tk.Tk()
calc.title("Calculator")
# Used StringVar to easily change the value of text variable as it can not be done
# with normal variable
text_input = tk.StringVar()
# the display of the calculator
tk.Entry(calc, font=("arial", 20, "bold"), textvariable=text_input, bd=5, insertwidth=4,
justify='right').grid(columnspan=4)
# make the buttons and add them to the window in grid style
# starting from the bottom (now i'm here :)) ) and set the text
# with the signs contained in the sign list using an i iterator
# when button premed 'command' call onclick function sending the symbol corresponding to the btn
i = 0
signs = [0, "C", "=", "+", 1, 2, 3, "-", 4, 5, 6, "*", 7, 8, 9, "/"]
for r in range(5, 1, -1):
for c in range(4):
tk.Button(calc, padx=28, pady=16, bd=1, font=('arial', 20, 'bold'), text=signs[i],
command=lambda sign=signs[i]: onclick(sign)).grid(row=r, column=c)
i += 1
# display main window and keep it open
calc.mainloop()
| true |
d5a8976e67ff84c03bc5df83b65f5d2003e61692 | MattR-GitHub/Python-1 | /L2 Check_string.py | 1,637 | 4.28125 | 4 | # check_string.py
countmax = 5
count = 0
while count != countmax:
count+=1
uin = input(" Enter an uppercase word followed by a period. Or enter " "end" " to exit. ")
upperltrs = uin.upper()
if uin.endswith("end"):
print("Exiting")
count = 5
#Upper Letters
elif uin.isupper() and uin.endswith("."):
print("Very good job following directions with your input: ", uin)
elif uin.isupper()and not uin.endswith("."):
print("Upper case is good but missing the period . at the end: ", uin)
#Lower Letters
elif uin.islower() and uin.endswith(".") :
print("Please capitalize your letters. Having period at the end is good: ", uin)
elif uin.islower() and not uin.endswith(".") :
print("Please capitalize your letters. A period at the end is needed: ", uin)
#Mixed Upper and Lower Letters
elif uin not in upperltrs and uin.endswith(".") :
print("Please capitalize all of the letters. Ending with a period is correct.: ", uin)
elif uin not in upperltrs and not uin.endswith(".") :
print("Please capitalize all of the letters. And add a period at the end.: ", uin)
#Numbers
elif uin.isdigit() and not uin.endswith(".") :
print("Please enter letters not numbers followed by a period. ", uin)
# Figured this was fun to figure out but its odd since the above check operates but the below ck does not. Dont know how to get below ck to operate. Tried everything for 1.5 hours.
elif uin.isdigit() and uin.endswith(".") :
print("Please enter letters not numbers. Having period at the end is good ", uin)
| true |
a6e75c730a5255baf04335823bdf3e536eca2dcb | renbstux/geek-python | /assertions.py | 1,364 | 4.5 | 4 | """
Assertions (Afirmações) seria mais (Checagens/Questionamentos)
Em Python utilizamos a palavra reservada 'assert' para realizar simples
afirmações utilizadas nos testes.
Utilizamos o 'assert' em uma expressão que queremos checar se é válida ou não.
Se a expressão for verdadeira, retorna None é caso seja falsa levanta um erro
do tipo AssertionError.
#Obs: nós podemos especificar, opcionalmente, um segundo argumento ou mesmo uma
mensagem de erro personalizada.
#OBS: A palavra 'assert' pode ser utilizada em qualquer função ou código nosso...não precisa
ser exclusivamente nos testes.
# ALERTA: Cuidado ao utilizar 'assert'
Se um Programa Python for executado com parametro -O, nenhum assertion
será validado. Ou seja, todas as suas validações já eram.
"""
def soma_numeros_positivos(a, b):
assert a > 0 and b > a, 'Ambos numeros precisam ser positivos'
return a + b
ret = soma_numeros_positivos(2, 4)# 6
#ret = soma_numeros_positivos(-2, 4)# AssertionError: Ambos numeros precisam ser positivos
#print(ret)
def comer_fast_food(comida):
assert comida in [
'pizza',
'sorvete',
'doces',
'batata frita'
'cachorro quente',
], 'A comida precisa ser fast food!'
return f'Eu estou comendo {comida}'
comida = input('informe a comida: ')
print(comer_fast_food(comida))
| false |
a052edcc88582b70e71cae3518c00485d270959e | renbstux/geek-python | /intro_unittest.py | 1,543 | 4.40625 | 4 | """
Introdução ao módulo Unittest
Unittest -> Teste Unitarios
O que são testes unitários?
Teste é a forma de se testar unidades individuais de código fonte.
Unidades individuais podem ser: funções, métodos, classes, módulos etc.
OBS: Teste unitário não é especifico da linguagem Python.
Para criar nossos testes, criamos classes que herdam de unittest.TestCase
e a partir de então ganhamos todos os 'assertions' presentes no módulo.
Para rodar os testes, utilizamos unittest.main()
TestCase -> Casos de teste para sua unidade
# Conhecendo as Assertions
https://docs.python.org/3/library/unittest.html
Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
Por convenção, todos os testes em um test case, devem ter seu nome iniciando com 'test_nomedafuncao'
Para executar os teste com unittest
python nome_do_modulo.py
# Para executar os testes com unittest no modo verbose
python nome_do_modulo.py -v
# Docstrings nos testes
Podemos acrescentar (e é recomendado) docstrings nos nossos testes!
"""
# Prática - utilizando a abordagem TDD
| false |
e078c527a08b52faf2ab3e7b7ffb3d6facec9a42 | renbstux/geek-python | /manipulando_data_hora.py | 1,354 | 4.1875 | 4 | """
Manipulando Data e Hora
Python tem um módulo built-in (integrado) para se trabalhar com data e hora
chamado datetime
import datetime
print(dir(datetime))
print(datetime.MAXYEAR)
print(datetime.MINYEAR)
# Retorna a data e hora corrente
print(datetime.datetime.now()) # 2020-09-05 10:54:13.394297
# datetime.datetime(year, month, day, hour, minute, second, microsecond)
print(repr(datetime.datetime.now())) # Metodo repr - representação
# replace() para fazer ajustes na data/hora
inicio = datetime.datetime.now()
print(inicio)
# Alterar o horario para 16 hours, 0 minute, 0 second
inicio = inicio.replace(hour=16, minute=0, second=0, microsecond=0)
print(inicio)
# Recebendo dados do usuario e convertendo para data
import datetime
evento = datetime.datetime(2021, 1, 1, 0)
print(type(evento))
print(type('31/12/2020'))
print(evento)
nascimento = input('Informe sua data de nascimento(dd/mm/yyyy): ')
nascimento = nascimento.split('/')
nascimento = datetime.datetime(int(nascimento[2]), int(nascimento[1]), int(nascimento[0]))
print(type(nascimento))
print(nascimento)
"""
import datetime
evento = datetime.datetime.now()
# Acesso individual os elementos de data e hora
print(evento.year) # ano
print(evento.month)
print(evento.day)
print(evento.hour)
print(evento.second)
print(evento.microsecond)
print(dir(evento))
| false |
cc7306c01119d237d3e6df1c0d8cbe9afd856c59 | anushamurthy/CodeInPlace | /Assignment2/khansole_academy.py | 1,552 | 4.40625 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
RIGHT_SCORE = 3
RANDOM_MIN = 10
RANDOM_MAX = 99
def main():
test()
"""The function test begins with your score being 0. The users are continued to be tested until
their score matches the right score (which is 3 here). The user wins a score if they enter the correct
total of 2 random numbers. If they don't get the total right, score resets and test continues."""
def test():
score = 0
while score < RIGHT_SCORE:
actual_total,entered_total = generate_random()
if actual_total == entered_total:
score = score + 1
print("Correct! You've gotten " + str(score) + " correct in a row")
else:
print("Incorrect. The expected answer is " + str(actual_total))
score = 0
print("Congratulations, you've mastered addition.")
""" Generate random function generates 2 random numbers num1 & num2 between a specified maximum and minimum value.
It asks the users to sum up those 2 numbers. It then returns the entered sum and also the actual sum of the 2 numbers. """
def generate_random():
num1 = random.randint(RANDOM_MIN, RANDOM_MAX)
num2 = random.randint(RANDOM_MIN, RANDOM_MAX)
actual_total = num1 + num2
entered_total = int(input("What is " + str(num1) + " + " + str(num2) + "? "))
return actual_total, entered_total
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
58271b720700c5f61ef0bd7dd2bdd85865c0ac5f | esadakcam/assignment2 | /hash_passwd.py | 1,298 | 4.78125 | 5 | '''The below is a simple example of how you would use "hashing" to
compare passwords without having to save the password - you would-
save the "hash" of the password instead.
Written for the class BLG101E assignment 2.'''
'''We need to import a function for generating hashes from byte
strings.'''
from hashlib import sha256
''' To make use of the above sha256 function we need to do a couple
of things. So we write our own function which takes a password and
returns a string consisting of a hash of the password.'''
def create_hash(password):
pw_bytestring = password.encode()
return sha256(pw_bytestring).hexdigest()
'''In the following example we get a password from the user, generate a
hash from it, then get another password and generate a hash, and
check if they are the same. But note that we do not compare the
passwords themselves - once we have the hashes we no longer need the
passwords.'''
pw1 = input('Please enter your password:')
hsh1 = create_hash(pw1)
print('The hash of that is',hsh1)
pw2 = input('Please enter another password that we can check against that:')
hsh2 = create_hash(pw2)
print('The hash of that is',hsh2)
if hsh1 == hsh2:
print('Those were the same passwords')
else:
print('Those were different passwords')
| true |
e5a46864dd82d6d76a58fa17c36dbbf29283edd1 | Adroit-Abhik/CipherSchools_Assignment | /majorityElement.py | 1,300 | 4.125 | 4 | '''
Write a function which takes an array and prints the majority element (if it exists), otherwise prints “No Majority Element”.
A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
'''
# Naive approach
def find_majority_element(arr, n):
if n == 0:
return -1
maxCount = 0
resIndex = -1
for i in range(n):
count = 0
for j in range(n):
if arr[i] == arr[j]:
count += 1
if count > maxCount:
maxCount = count
resIndex = i
if maxCount > n//2:
return arr[resIndex]
else:
return -1
def find_majority_faster(arr, n):
res = 0
count = 1
# find element with highest count
for i in range(1, n):
if arr[res] == arr[i]:
count += 1
else:
count -= 1
if count == 0:
count = 1
res = i
count = 0
# check if majority
for i in range(n):
if arr[res] == arr[i]:
count += 1
if count > n//2:
return res
else:
return -1
if __name__ == "__main__":
n = int(input())
arr = list(map(int, input().strip().split()))
print(find_majority_element(arr, n))
| true |
92343cca077b80d95c93e8e643277232e29dd675 | reinaldoboas/Curso_em_Video_Python | /Mundo_1/desafio033.py | 951 | 4.34375 | 4 | ### Curso em Vídeo - Exercicio: desafio033.py
### Link: https://www.youtube.com/watch?v=a_8FbW5oH6I&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=34
### Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
# recebendo as variáveis
num1 = int(input("Digite um número: "))
num2 = int(input("Digite o segundo número: "))
num3 = int(input("Digite o terceiro número: "))
# Testando qual variável é a menor
menor = num1 # Assumimos que o primeiro número é o menor para evitar a necessidade de mais um if
if num2 < num1 and num2 < num3:
menor = num2
if num3 < num1 and num3 < num2:
menor = num3
# Testando qual variável é a maior
maior = num1 # Atribuimos o num1 como maior para evitar a necessidade de um if
if num2 > num1 and num2 > num3:
maior = num2
if num3 > num1 and num3 > num2:
maior = num3
print("=-" * 35)
print(f"O menor número é: {menor}.")
print(f"O maior número é: {maior}.")
| false |
415e4922f96ffb8a25795c35c36d8be765aaeb51 | reinaldoboas/Curso_em_Video_Python | /Mundo_1/desafio016.py | 470 | 4.28125 | 4 | ### Curso em Vídeo - Exercicio: desafio016.py
### Link: https://www.youtube.com/watch?v=-iSbDpl5Jhw&list=PLvE-ZAFRgX8hnECDn1v9HNTI71veL3oW0&index=25
### Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira.
### ex: Digite número: 6.127
### O número 6.127 tem a parte inteira 6.
num = float(input("Digite um número Real: "))
print("O número Real digitado foi {0} e tem a parte inteira {1}".format(num, int(num)))
| false |
be418db31599528f514cb2d6501b716c97121f58 | reinaldoboas/Curso_em_Video_Python | /Mundo_1/desafio008.py | 509 | 4.40625 | 4 | ### Curso em Vídeo - Exercicio: desafio008.py
### Link: https://www.youtube.com/watch?v=KjcdG05EAZc&list=PLvE-ZAFRgX8hnECDn1v9HNTI71veL3oW0&index=16
### Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros.
metro = int(input("Digite um valor em metros: "))
centimetros = float(metro * 100)
milimetros = float(metro * 1000)
print(30 * "=-")
print(f"O número digitado é {metro}\nConvertido em centimetros: {centimetros}\nConvertido em milimetros: {milimetros}")
| false |
0bbabac6787793025898422fef6e764e0f09f951 | reinaldoboas/Curso_em_Video_Python | /Mundo_2/desafio037.py | 1,019 | 4.1875 | 4 | ### Curso em Vídeo - Exercicio: desafio037.py
### Link: https://www.youtube.com/watch?v=B3F0IjH5WAM&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=38
### Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual base será a base de conversão:
### - 1 para binário
### - 2 para octal
### - 3 para hexadecimal
num = int(input("Digite um número inteiro: "))
escolha = (int(input("Escolha qual opção você deseja: \n\t(1) - Converter para binário\n\t(2) - Converter para octal\n\t(3) - Converter para hexadecimal\nQual a sua opção: ")))
if escolha == 1:
print("Você escolheu a opção 1")
print(f"O número {num} convertido em bínario: {bin(num)[2:]}")
elif escolha == 2:
print("Você optou pela opção 2")
print(f"O número {num} convertido em Octal: {oct(num)[2:]}")
elif escolha == 3:
print("Você selecionou a opção 3")
print(f"O número {num} convertido em Hexadecimal: {hex(num)[2:]}")
else:
print("Opção invalida! Tente novamente.")
| false |
b3197fd59fdaab5e4bac8663a3920fcd0686628c | anschy/Hacktober-Challenges | /Simple_Caluclator/simpleCalculator.py | 1,480 | 4.375 | 4 | # Python program of a simple calculator
# This function performs addition of two number's
def add(num_one, num_two):
return num_one + num_two
# This function performs subtraction of two number's
def subtract(num_one, num_two):
return num_one - num_two
# This function performs multiplication of two number's
def multiply(num_one, num_two):
return num_one * num_two
# This function performs division of two number's
def divide(num_one, num_two):
return num_one / num_two
# Selection of operation
print("Please select the operation you would like to perform.")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
while True:
# Take choice from the user
choice = input("Enter your choice: ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
# Take input of first and second number from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Check which operation to perform
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
break
else:
print("Invalid Input") | true |
4491e1510e6ad57212fe327be2b5fd2225cb4d31 | ICS3U-Programming-LiamC/Unit6-01-Python | /random_array.py | 1,153 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Liam Csiffary
# Created on: June 6, 2021
# This program generates 10 random numbers then
# it calculates the average of them
# import the necessary modules
import random
import const
# greet the user
def greet():
print("Welcome! This program generates 10 random numbers and will then\
find the average of all these numbers")
# main function
def main():
# initialize the list
array_of_nums = []
# generate 10 random numbers and add them to the list
for each in range(0, const.NUM_NUMS):
array_of_nums.append(random.randint(const.MIN, const.MAX))
# set total to zero and then add each element in the list
# to the total
total = 0
for each in array_of_nums:
total = total + each
# find the average by dividing the total by the number of numbers
average = total / len(array_of_nums)
# print all these things back to the user
print(array_of_nums)
print("All the numbers added up = {}".format(total))
print("The average of all these numbers is {}".format(average))
# gets the program started
if __name__ == "__main__":
greet()
main()
| true |
720f81c9dba4a84201b901fa6f4f1c2ee4655346 | kgy-idea-study/study | /python/python_base/python_base/DataType/String.py | 1,502 | 4.25 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -
"""
String(字符串)
Python中的字符串用单引号(')或双引号(")括起来,同时使用反斜杠(\)转义特殊字符。
字符串的截取的语法格式如下:
变量[头下标:尾下标]
索引值以 0 为开始值,-1 为从末尾的开始位置。
加号 (+) 是字符串的连接符, 星号 (*) 表示复制当前字符串,紧跟的数字为复制的次数
"""
str = 'Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + "TEST") # 连接字符串
#Python 使用反斜杠(\)转义特殊字符,如果你不想让反斜杠发生转义,
# 可以在字符串前面添加一个 r,表示原始字符串
print('Ru\noob')
print(r'Ru\noob')
"""
与 C 字符串不同的是,Python 字符串不能被改变。向一个索引位置赋值,比如word[0] = 'm'会导致错误。
注意:
1、反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
2、字符串可以用+运算符连接在一起,用*运算符重复。
3、Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
4、Python中的字符串不能改变。
"""
word = 'Python'
print(word[0], word[5])
print(word[-1], word[-6]) | false |
bcad13d1e474c82bc26f31f7c6b9bd2979ff3044 | clancybawdenjcu/cp1404practicals | /prac_01/shop_calculator.py | 466 | 4.125 | 4 | total_price = 0
number_of_items = int(input("Number of items: "))
while number_of_items < 0:
print("Invalid number of items!")
number_of_items = int(input("Number of items: "))
for i in range(1, number_of_items + 1):
price = float(input(f"Price of item {i}: "))
total_price += price
if total_price > 100:
total_price *= 1.1 # apply 10% discount if total equals over $100
print(f"Total price for {number_of_items} items is: ${total_price:.2f}")
| true |
675c1d75cd985355454cf95418586469a15bc83e | candrajulius/Phyton | /PerulanganPadaPhyton/PerulanganPadaPhyton.py | 825 | 4.15625 | 4 | # Example for pertama pada phyton
for letter in 'phyton':
print("Current letter {}".format(letter))
# Cara kedua menggunakan list
fruits = ["Apel","jeruk","Pisang"]
for j in fruits:
print("Current in {}".format(j))
# Mengitung berdasarkan len atau panjang pada variabel list
print("\n")
for k in range(len(fruits)):
print("Current fruits {}".format(fruits[k]))
# Menggunakan While
# Nilai true pada phyton adalah nilai yang non zero
# Contohnya
var = 1
while var > 0:
print("nilai {} sangat besar dari 0".format(var))
break # kalau tidak ditambah statement break maka akan muncul infinitive loop
while var < 10:
print("Nilai dari {}".format(var))
var = var + 1
print("\n")
# Perulangan bertingkat
for b in range(0,5):
for u in range(0,5 - b):
print('*',end='')
print() | false |
de7d2d4ce3881419864b5aa119e01261e0f43159 | zweed4u/Python-Concepts | /Design patterns/creational_patterns/factory.py | 843 | 4.625 | 5 | """
Factory Pattern example - creational design pattern
Scenario: Pet shop - orginally sold dogs, now sell cats as well
"""
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return "Meow"
class Dog():
def __init__(self, name):
self.name = name
def speak(self):
return "Bark"
class Fish():
def __init__(self, name):
self.name = name
def speak(self):
return "Glub glub"
def get_pet(pet="dog"):
"""
The factory method used to create objects
(Create and return object to user of the function)
"""
# Adding new classes/type is easy
pets = {
'dog': Dog("Kaiser"),
'cat': Cat("Satan"),
'fish': Fish("Nemo")
}
return pets[pet]
dog = get_pet()
print(dog.speak())
dog2 = get_pet("dog")
print(dog2.speak())
cat = get_pet("cat")
print(cat.speak())
fish = get_pet("fish")
print(fish.speak()) | true |
a323a530af7ab84312d682db75191f80c75ef3da | zweed4u/Python-Concepts | /Map Filter Reduce functions/map_function.py | 1,067 | 4.5625 | 5 | """
Map function
"""
import math
def area(radius):
"""
Area of circle given radius
"""
return math.pi*(radius**2)
# Compute areas of many circles given all of their radius'
radii = [2, 5, 7.1, .3, 10]
print(radii)
# Direct method
areas = []
for radius in radii:
areas.append(area(radius))
print(areas)
# Map method - takes a function and iterable (list here)
# Map() applies the function given as the first arg to each element in the iterable fiven as the second arg
# Cast as list to print out as map returns iterator not data
print(list(map(area, radii)))
# Using map function on map data - celsius datapoints to farenheit
celsius_temps = [('Berlin',29),('Cairo',36),('Buenos Aires',19),('Los Angeles',26),('Tokyo',27),('New York',28),('London',22),('Beijing',32)]
# Lambda function convert tuple's temp element from celsius to farenheit
celsius_to_farenheit = lambda city_and_temp: (city_and_temp[0], (9/5)*city_and_temp[1]+32 )
# Maps the lambda function to each element in the celisus temp array
print(list(map(celsius_to_farenheit, celsius_temps))) | true |
b738330a15670e15e37e80adde72a00e290b573a | haominhe/Undergraduate | /CIS211 Computer Science II/Projects/p4/flipper.py | 1,727 | 4.75 | 5 | """CIS 211 Winter 2015
Haomin He
Project 4: Building GUIs with Tk
3. Write a program that will display three playing card images and a button
labeled "flip". Each time the user clicks the button one of the card images
should be updated.
When the window is first opened the user should see the backs of three cards.
The first button click should turn over the first card, and the next two
clicks should turn over the other two cards.
When you display the front of a card you can pick any card at random.
The fourth click should appear to remove a card, but in fact your program
should change the image to a white square the size of a card. The next two
clicks will remove the other two cards.
The next three clicks should appear to “deal” three new cards face down.
Your program just needs to replace the blank images with the image for the
back side of a card.
"""
from tkinter import *
from random import randint
from CardLabel import *
root = Tk()
CardLabel.load_images()
sides = ['back', 'front', 'blank']# values that can be passed to display method
n = 0 # index into list of sides
a = [CardLabel(root), CardLabel(root), CardLabel(root)]
for i in range(3):
a[i].grid(row = 0, column = i)
def flip():
global n
x = (n+3) // 3
if x == 3:
x = 0
a[n%3].display(sides[x], randint(0,51))
print(n, n%3, (n+3)//3)
n = (n+1) % 9 #9 events
root.rowconfigure(0, minsize=115)
root.columnconfigure(0, minsize=85)
button = Button(root, text='Flip', width = 10, command = flip)
button.grid(row = 1, column = 1, pady = 10, rowspan = 1)
if __name__ == '__main__':
root.mainloop()
| true |
4f49a3f6fb7ecb9ca302f0f6db2ff7dedc870d4e | Severian999/Homework-7 | /DonGass_hw7_task2.py | 1,449 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 21:36:26 2017
@author: Don Gass
"""
word = 'onomatopoeia'
def hangman(num_guesses, word):
"""
Controls the logic of the hangman game.
Handles the guesses and determines whether the user wins or loses.
Calls hidden_word(word, guesses) to get the hidden word string with
correctly guessed letters indicated. Eg. onom--opo--i-
"""
guesses = ""
print('\nYou have %d guesses. The word has %d letters.' % \
(num_guesses, len(word)))
while len(guesses) < num_guesses:
guess = input('Enter guess (#%d): ' % (len(guesses)+ 1))
if len(guess) < 1 or len(guess) > 1:
print('You must enter a single letter! Please try again')
continue
else:
guesses += guess
result = hidden_word(word, guesses)
print(result)
if '-' not in result:
print('Congratulations! You guessed the word: ', word)
return None
print('You did not guess the word: ', word)
def hidden_word(word, guesses):
"""
Takes in the word and string of guessed letters and returns a formatted
hidden word string.
"""
hidden_word = ""
for letter in word:
if letter in guesses:
hidden_word += letter
else:
hidden_word += '-'
return hidden_word
hangman(10, word)
| true |
1ae0a8a71681f0e5d2c5ba091d6e5d8ff6076f6f | melodist/CodingPractice | /src/HackerRank/Day 25: Running Time and Complexity.py | 578 | 4.21875 | 4 | """
https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem
Checks if n is divisible by 2 or any odd number from 3 to sqrt(n)
"""
import sys
def isPrime(n):
if n == 2: return True # 2 is divisible by 2
if (n == 1) or (n & 1 == 0): return False
root_n = int(n**0.5)
for i in range(3, root_n+2, 2):
if n % i == 0:
return False
return True
n = int(input())
a = [int(sys.stdin.readline()) for _ in range(n)]
for t in a:
if isPrime(t):
print('Prime')
else:
print('Not prime')
| false |
729c1be4abda4dd01233a37a442700e302620929 | NoxCi/diagramador-ajedrez | /utils.py | 1,979 | 4.25 | 4 | def recta(p1,p2):
"""
Modela una linea recta, devuelve su pendiente y la funcion
que modela la recta.
"""
m = (p2[1]-p1[1])/(p2[0]-p1[0])
b = m*(-p1[0]) + p1[1]
return m, (lambda x : m*x + b)
def is_number(n):
"""
Checa si un string es un numero, si lo es regresa el numero
de lo contrario regresa False
"""
try:
return int(n)
except Exception as e:
return False
def chess_position(col, row):
"""
Covierte una posicion capaz de axceder a un arreglo de 8x8
a un formato de ajedrez
"""
letras='abcdefgh'
casilla = letras[col] + str(8-row)
return casilla
def chess_directions(piece,color,col,row):
"""
Devuelve las posibles direcciones de una pieza
"""
recursive = False
if piece == 'P':
if color == 'n':
directions = [(0,1),(-1,1),
(1,1),]
if row == 1:
directions.append((0,2))
if color == 'b':
directions = [(0,-1),(-1,-1),
(1,-1),]
if row == 6:
directions.append((0,-2))
if piece == 'R':
directions = [(0,1),(-1,1),
(1,1),(0,-1),(-1,-1),
(1,-1),(-1,0),(1,0)]
if col == 4 and row == 7 and color == 'b':
directions.append((2,0))
directions.append((-2,0))
if col == 4 and row == 0 and color == 'n':
directions.append((2,0))
directions.append((-2,0))
if piece == 'D':
recursive = True
directions = [(0,1),(-1,1),
(1,1),(0,-1),(-1,-1),
(1,-1),(-1,0),(1,0)]
if piece == 'T':
recursive=True
directions = [(0,1),(0,-1),
(-1,0),(1,0)]
if piece == 'A':
recursive = True
directions = [(1,1), (-1,1),
(-1,-1), (1,-1)]
if piece == 'C':
directions=[(1,-2),(-1,-2),
(2,1),(2,-1),(1,2),
(-1,2),(-2,1),(-2,-1)]
return directions, recursive
| false |
c4281cd1d3bad824e8199801179681d3228c5037 | shaneleblanc/codefights | /permutationCypher.py | 1,149 | 4.1875 | 4 | # You found your very first laptop in the attic, and decided to give in to nostalgia and turn it on. The laptop turned out to be password protected, but you know how to crack it: you have always used the same password, but encrypt it using permutation ciphers with various keys. The key to the cipher used to protect your old laptop very conveniently happened to be written on the laptop lid.
# Here's how permutation cipher works: the key to it consists of all the letters of the alphabet written up in some order. All occurrences of letter 'a' in the encrypted text are substituted with the first letter of the key, all occurrences of letter 'b' are replaced with the second letter from the key, and so on, up to letter 'z' replaced with the last symbol of the key.
# Given the password you always use, your task is to encrypt it using the permutation cipher with the given key.
# Example
# For password = "iamthebest" and
# key = "zabcdefghijklmnopqrstuvwxy", the output should be
# permutationCipher(password, key) = "hzlsgdadrs".
def permutationCipher(password, key):
table = str.maketrans(string.ascii_lowercase, key)
return password.translate(table)
| true |
be1ae91337d2cd47b65b443521e755e0abe43b85 | eSanchezLugo/programacionPython | /src/sintaxisBasica/diccionarios/trabajandoDiccionarios.py | 307 | 4.125 | 4 | capitales = {"China":"Pekin", "Inidia":"Nueva Delhi","Indonesia":"Yakarta", "Japón": "Tokio", "Blangadesh": "Dacca"}
for clave in capitales:
valor = capitales[clave]
print(clave)
print(valor)
print(capitales.items())
for clave, valor in capitales.items():
print(clave + " -> " + valor ) | false |
066a21b7900b051269d72ba7b57d1ec8bfce3dbd | eSanchezLugo/programacionPython | /src/condicionalesYBucles/while/raizCuadrada.py | 452 | 4.15625 | 4 | import math
print(" Este programa halla la raíz cuadrada de un valor numérico")
numero = int(input("Introduce un número, por favor : "))
intentos = 1
while numero<0:
print(" El valor numérico no puede ser negativo")
numero = int(input("Introduce un número, por favor : "))
intentos +1
if intentos == 5:
break
if intentos == 5:
print("Lo siento no puedo realizar el calculo")
else:
print(math.isqrt(numero))
| false |
345b9214b6288bdb379a1bc0f94fb49e4fd4d6b5 | mghamdi86/Python-Lesson | /Lesson1.py | 401 | 4.3125 | 4 | Variables will teach us how to store values for later use:
x = 5
Loops will allow us to do some math on every value in a list:
print(item) for item in ['milk', 'eggs', 'cheese']
Conditionals will let us run code if some test is true:
"Our test is true!" if 1 < 2 else "Our test is false!"
Math Operators allow us to perform mathematical operations on numbers
5 + 5 # 10
5 - 5 # 0
5 * 5 # 25
5 / 5 # 1
| true |
1ba71e3e3f8ab2cc4584c20924d6456da5854b42 | michberr/code-challenges | /spiral.py | 2,215 | 4.65625 | 5 | """Print points in matrix, going in a spiral.
Give a square matrix, like this 4 x 4 matrix, it's composed
of points that are x, y points (top-left is 0, 0):
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
3,0 3,1 3,2 3,3
Starting at the top left, print the x and y coordinates of each
point, continuing in a spiral.
(Since we provide 3 different versions, you can change this to
the routine you want to test:
Here are different sizes:
>>> spiral(1)
(0, 0)
>>> spiral(2)
(0, 0)
(0, 1)
(1, 1)
(1, 0)
>>> spiral(3)
(0, 0)
(0, 1)
(0, 2)
(1, 2)
(2, 2)
(2, 1)
(2, 0)
(1, 0)
(1, 1)
>>> spiral(4)
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(1, 3)
(2, 3)
(3, 3)
(3, 2)
(3, 1)
(3, 0)
(2, 0)
(1, 0)
(1, 1)
(1, 2)
(2, 2)
(2, 1)
"""
def heading(current, vx, vy, length):
"""Head in a direction with vx, vy from current for a given length"""
for i in range(length-1):
current = (current[0] + vx, current[1] + vy)
print current
return current
def spiral(matrix_size):
"""Spiral coordinates of a matrix of `matrix_size` size.
Use vectors as algorithm
"""
box_size = matrix_size
current = (0, 0)
while box_size > 1:
# Print corner of the box
print current
# Heading East
current = heading(current, 0, 1, box_size)
# Heading South
current = heading(current, 1, 0, box_size)
# Heading West
current = heading(current, 0, -1, box_size)
# Heading North
# Go one less unit North than any other direction
current = heading(current, -1, 0, box_size-1)
# Slide current one unit to the East
current = (current[0], current[1] + 1)
# Deprecate box size by 2
box_size -= 2
# If matrix size is odd, we need to add in middle coordinate
if matrix_size % 2 != 0:
middle = matrix_size//2
print (middle, middle)
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. YOU MUST BE DIZZY WITH PRIDE!\n"
| true |
186e9a29e00e43262654e667e1029e457eeb655a | michberr/code-challenges | /sum_recursive.py | 370 | 4.15625 | 4 | def sum_list(nums):
"""Sum the numbers in a list with recursion
>>> sum_list([])
0
>>> sum_list([1])
1
>>> sum_list([1, 2, 3])
6
"""
if not nums:
return 0
return nums[-1] + sum_list(nums[:-1])
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "\n***ALL TESTS PASS!\n"
| true |
fd3d0e66e5d3b98b2ee796ae7e3e8c46d3919a66 | thepros847/python_programiing | /lessons/#Python_program_to_Find_day.py | 392 | 4.25 | 4 | # Python program to find day of the week for a given date
while True:
import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
return (calendar.day_name[born])
# Driver program
date = '04 07 1962'
print(findDay(date))
print("Python Program To Find Day Of The Week For A Given Date")
quit() | true |
64e4437e992ab02b351d6ce1fd0968037e369cbc | richa067/Python-Basics | /Dictionaries.py | 2,579 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 22:18:33 2020
@author: Richa Arora
"""
#Dictionaries
# Add code to the above program to figure out who has the most messages in the file. After all the data has beenread and the dictionary has been created, look through the dictionary using a maximum
# loop to find who has the most messages and print how many messages the person has.
# Enter a file name: mbox-short.txt
# cwen@iupui.edu 5
# Enter a file name: mbox.txt
# zqian@umich.edu 195
#Solution:-
fname = input('Enter the file name:')
fhand = open(fname)
counts = dict()
for line in fhand:
words = line.rstrip().split()
if line.startswith("From "):
words = words[1]
counts[words] = counts.get(words,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigword is None or count > bigcount:
bigword = word
bigcount = count
print(bigword,bigcount)
#OR
hand = open('C:\\Users\\Piyush Raj\\Desktop\\mbox-short.txt')
counts = dict()
for line in hand:
if line.startswith("From "):
words = line.strip().split()
day = words[1]
if day not in counts:
counts[day] = 1
else:
counts[day] += 1
print(counts)
largest = None
for itervar in counts:
if largest is None or counts[itervar] > largest :
largest = counts[itervar]
sender = itervar
print('Largest:', largest, sender)
# This program records the domain name (instead of theaddress) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print
# out the contents of your dictionary.
# python schoolcount.py
# Enter a file name: mbox-short.txt
# {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7,
# 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
#Solution:-
name = input('Enter the file name:')
fhand = open(name)
counts = dict()
for line in fhand:
words = line.rstrip().split()
if line.startswith("From "):
words = words[1]
k = words.split("@")[1]
counts[k] = counts.get(k,0) + 1
print(counts)
#OR
hand = open('mbox-short.txt')
counts = dict()
for line in hand:
if line.startswith("From"):
words = line.rstrip().split()
email = words[1]
domain = email.split("@")[1]
counts[domain] = counts.get(domain,0) + 1
# if day not in counts:
# counts[day] = 1
# else:
# counts[day] += 1
print(counts) | true |
2f50199874eb8936c327b02c6a6ea27ecefbfb89 | kaiserkonok/python-data-structures-for-beginner | /linked_list.py | 1,416 | 4.1875 | 4 | class Node:
def __init__(self, item, next=None):
self.data = item
self.next = next
class LinkedList:
def __init__(self, head):
self.head = head
def prepend(self, item):
new_node = Node(item, self.head)
self.head = new_node
def append(self, item):
new_node = Node(item)
if self.head is None:
self.head = new_node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def print_linked_list(self):
current_node = self.head
while current_node is not None:
print(current_node.data, end=' ')
current_node = current_node.next
print()
def remove_node(self, node):
if node is self.head:
self.head = self.head.next
else:
current_node = self.head
while current_node.next is not node:
current_node = current_node.next
current_node.next = node.next
def insert(self, node, item):
new_node = Node(item, node.next)
node.next = new_node
head = Node(5)
new_ll = LinkedList(head)
new_ll.prepend(8)
new_ll.prepend(20)
new_ll.prepend(10)
new_ll.append(10)
new_ll.remove_node(new_ll.head)
new_ll.insert(new_ll.head, 5)
new_ll.print_linked_list()
| true |
c610ab39a3357f974c47fd46c39b2a26f6b7e079 | sibaken33/mysite | /Python/def.py | 1,172 | 4.125 | 4 | # 関数の定義
# def sample_function(x, y):
# def sample_function(arg1, arg2):
# def sample_function(arg1, *arg2):
# def sample_function(arg1, arg2 = 'x', arg3 = 'y'):
# def sample_function(arg1, **arg2):
def sample_function(arg1, *arg2, **arg3):
print(arg1, arg2, arg3)
#z = sample_function(1, 2)
#print(z)
# sample_function('a', 'b') #順番に引数を指定する
# sample_function(arg1='c', arg2='d') #キーワードを指定する
# sample_function(arg2='f', arg1='e') #キーワードの場合は順番通りでなくてもよい
# sample_function('a', 'b', 'c') #引数を全部指定している
# sample_function('a', arg2 ='b') #3番目を省略できる
# sample_function('a') #2,3番目を省略する
# sample_function('a', key1='x', key2='y', key3='z')
# sample_function('a', 'b', 'c', 'd', key1='x', key2='y', key3='z')
def sample_function1():
""" 数値を返却 """
return 1
def sample_function2():
""" 何も返さない関数 """
pass
def sample_function3():
""" 複数の値を返却 """
return 3, 'b'
x = sample_function1()
print(x)
y = sample_function2()
print(y)
a, b = sample_function3()
print(a, b)
| false |
9209b667e5a198e3b32b860c4eb05bc14c1281b4 | HGWright/QA_Python | /programs/grade_calculator.py | 617 | 4.25 | 4 | print("Welcome to the Grade Calculator")
maths_mark = int(input("Please enter your Maths mark: "))
chemistry_mark = int(input("Please enter your Chemistry mark: "))
physics_mark = int(input("Please enter your Physics mark: "))
total_mark = (maths_mark + chemistry_mark + physics_mark)/3
print(f"Your overall percentage is {total_mark}%")
if total_mark >= 70:
print(f"You earned a grade of: A")
elif total_mark >= 60:
print(f"You earned a grade of: B")
elif total_mark >= 50:
print(f"You earned a grade of: C")
elif total_mark >= 40:
print(f"You earned a grade of: D")
else:
print("You Failed") | true |
4113c239c2cb18566b1b0d7b29114fbc49ac1fcb | Pramod123-mittal/python-prgs | /guessing_problem.py | 546 | 4.125 | 4 | # guessing problem
number = 18
no_of_guessses = 1
print('you have 9 guesses to win the game')
while no_of_guessses<=9:
guess_number = int(input('enter a number'))
if guess_number > 18:
print('greater then required')
elif guess_number < 18:
print('lesser then required')
else:
print('WINNER')
print('no_of_guessses taken by a player :',no_of_guessses)
break
print(9-no_of_guessses,'left guesses')
no_of_guessses = no_of_guessses+1
if no_of_guessses>9:
print('you lost the game')
| true |
629884eeae4316a7e795dd72110c063bde43a01a | Pramod123-mittal/python-prgs | /decorators.py | 606 | 4.15625 | 4 | '''def func1():
print('my name is pramod mittal')
func2 = func1
func2()
del func1
print('deleted')
func2()'''
# def funcret(num):
# if num ==0:
# return print
# if num==1:
# return int
# a=funcret(1)
# print(a)
#
# def executer(func):
# func('this')
#
#
# executer(print)
def dec(func1):
def nowexec():
print('executing now')
func1()
print('executed')
return nowexec
@dec
def who_is_pramod():
print('pramod is a good boy')
# decorators means adjusting a function into another function
# who_is_pramod = dec(who_is_pramod)
who_is_pramod()
| false |
0779c332c9be6b1c2c9b0dd14965e56b2ab3ef09 | PROTECO/curso_python_octubre_2019 | /Jueves-31-oct/diez.py | 757 | 4.21875 | 4 | #################################################################################################
# Tarea 3 , Problema 10
# Escriba un programa de Python que solicite una cadena al usuario e imprima la misma cadena omitiendo todas sus vocales.
# EJEMPLO: Entrada: "¡Hola, mundo!" - Salida: "¡Hl, mnd!"
#################################################################################################
cadena = input("Escribe una cadena, la dejaré sin vocales: ")
cadena_aux = ''
vocales = ['a','e','i','o','u','A','E','I','O','U']
for letra in cadena:
if letra not in vocales:
cadena_aux += letra
print("La cadena sin vocales es: %s"%cadena_aux)
print("La cadena sin vocales es: ",''.join(letra for letra in cadena if letra not in 'aeiouAEIOU'))
| false |
15cfd57c7a6a58f6fb90e93b23056c33399228dd | BennettBierman/recruiting-exercises | /inventory-allocator/Warehouse.py | 1,317 | 4.40625 | 4 | class Warehouse:
"""
Warehouse encapsulates a string and a dictionary of strings and integers.
"""
def __init__(self, name, inventory):
"""
Construct a new 'Warehouse' object.
:param name: string representing name of Warehouse
:param inventory: dictionary representing names and quantities of items stored in Warehouse
:return: returns nothing
"""
self.name = name
self.inventory = inventory
def __str__(self):
"""
Construct string to represent state of a Warehouse object.
:return: returns a string
"""
return f"{{name: {self.name}, inventory: {self.inventory}}}"
def __repr__(self):
"""
Construct string to represent state of a Warehouse object.
:return: returns a string
"""
return f"{{name: {self.name}, inventory: {self.inventory}}}"
def __eq__(self, other):
"""
Determine equality between this Warehouse and another Warehouse object.
Warehouses are equal if their string and dictionary are equal
:param other: another Warehouse object
:return: returns boolean representing whether two objects are equal
"""
return self.name == other.name and self.inventory == other.inventory
| true |
5d85bb6b4e6901944cf11e502d10a1ca450f9a8b | ashish8796/python | /day-5/list_methods.py | 886 | 4.5 | 4 | #Useful Functions for Lists
len() #returns how many elements are in a list.
max() #returns the greatest element of the list.
#The max function is undefined for lists that contain elements from different, incomparable types.
min() #returns the smallest element in a list.
sorted() #returns a copy of a list in order from smallest to largest, leaving the list unchanged.
#.join method
#Join is a string method that takes a list of strings as an argument, and returns a string consisting of the list elements joined by a separator string.
new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
#fore
#aft
#starboard
#port
name = "-".join(["García", "O'Kelly"])
print(name)
#García-O'Kelly
#append method
#A helpful method called append adds an element to the end of a list.
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
#['a', 'b', 'c', 'd', 'z'] | true |
6e990727edcfb9781d3741a19e798aa443fa7405 | ashish8796/python | /day-11/for_through_dictionaries.py | 878 | 4.65625 | 5 | #Iterating Through Dictionaries with For Loops
'''
When you iterate through a dictionary using a for loop, doing it the normal way (for n in some_dict) will only give you access to the keys in the dictionary
'''
cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
"Jason Alexander": "George Costanza",
"Michael Richards": "Cosmo Kramer"
}
for key in cast:
print(key)
'''
Jason Alexander
Michael Richards
Jerry Seinfeld
Julia Louis-Dreyfus
'''
#If you wish to iterate through both keys and values, you can use the built-in method items
for key, value in cast.items():
print("Actor: {} Role: {}".format(key, value))
'''
Actors: Jason Alexander Role: George Costanza
Actors: Michael Richards Role: Cosmo Kramer
Actors: Jerry Seinfeld Role: Jerry Seinfeld
Actors: Julia Louis-Dreyfus Role: Elaine Benes
'''
#items is an awesome method that returns tuples of key, value pairs,
# which you can use to iterate over dictionaries in for loops. | true |
a3fa02ef6abf8fedd48ff9f01c5da79ade01265f | ashish8796/python | /day-17/scripting.py | 426 | 4.375 | 4 | #Scripting With Raw Input
#input, the built-in function, which takes in an optional string argument form user.
name = input("Enter your name: ")
print("Hello there, {}!".format(name.title()))
num = int(input("Enter an integer"))#change string into integer
print("hello" * num)
result = eval(input("Enter an expression: "))#to interpret input as a python code by eval
print(result)
#If the user inputs 2 * 3, this outputs 6. | true |
d4c3c7cfd283136567979e0fdf1c0dc495889778 | ashish8796/python | /day-6/dictionaries_identity_operators.py | 1,587 | 4.59375 | 5 | #Dictionaries
#A dictionary is a mutable data type that stores mappings of unique keys to values.
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"]) # print the value mapped to "helium"
#2
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
print(elements)
#{'helium': 2, 'lithium': 3, 'hydrogen': 1, 'carbon': 6}
#dictionaries also alows 'in' operator like list.
print("carbon" in elements)
#True
#.get()
#get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.
print(elements.get("dilithium"))
#None
#Identity Operators
#Keyword Operator
is # evaluates if both sides have the same identity
is not # evaluates if both sides have different identities
n = elements.get("dilithium")
print(n is None)
#True
print(n is not None)
#False
#question
# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions of people.
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
population = {"Shanghai": 17.8, "Istanbul": 13.3, "Karachi": 13.0, "Mumbai": 12.5}
print(population.get('Happy', 'There\'s no such thing.'))
#There's no such thing.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == b)
print(a is b)
print(a == c)
print(a is c) #False why?
#True,True,True,False | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.