blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
f3f4eca9cee37f6e1906840c088e1576421a0911
|
fatimaalheeh/python_stack
|
/_python/assignments/users_with_bank_account.py
| 2,858
| 4.28125
| 4
|
class BankAccount:
interest=1
rate=1
balance=0
def __init__(self, int_rate=1, balance=0):
self.rate=int_rate
self.balance=balance
def deposit(self, amount):
self.balance+=amount
def withdraw(self, amount):
self.balance-=amount
def display_account_info(self):
print("Account info:","--interest:",self.interest,"--rate:",self.rate,"--balance:",self.balance) #\n new line
def yield_interest(self):
self.balance*=self.rate
class User:
def __init__(self, name, email_address):# now our method has 2 parameters!
self.name = name # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.BankAccount = BankAccount() # added association
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
#change .deposit to .balance :.balance is an attribute of the current child and .deposit is an attribute of the associated class, what ed do is exchange the method of the current class with a similar method from the class it is associated with, that it should iherti that specific method from
self.balance.deposit += amount # the specific user's account decreases by the amount of the value withdrawn, balance is an attribute
def make_withdrwal(self, amount): # takes an argument that is the amount of the deposit
if self.balance.withdraw-amount>=0: #as long as there is some money, withdraw money
self.balance -= amount # the specific user's account decreases by the amount of the value withdrawn
else:
print("Dear Mr.",self.name," ,you tried to withdraw: ",amount, "but you have insufficient balance so your withdrawal has failed. Your current balance is: ",self.account_balance)
def display_user_balance(self): # takes an argument that is the amount of the deposit
pass # the specific user's account decreases by the amount of the value withdrawn
def transfer_money_to_other_user(self,other,amount): # takes an arguments self, other relates to other user and the amount to be transferred
if self.balance - amount >=0: #this is to check if the user got enough money
self.balance-=amount
other.balance+=amount
print("success. Dear",self.name,", you have transferred an amount of: ",amount," to ",other.name,". Your current Balancec is",self.account_balance)
else:
print("Failed. Dear",self.name,", you have tried to transfer an amount of: ",amount," to ",other.name,"but your balance is insufficient.Your current Balancec is",self.account_balance)
me = User("fatima","mail@gmail.com")
me.BankAccount.deposit(34343)
me.BankAccount.withdraw(34343)
me.BankAccount.display_account_info()
| true
|
4690cd9ff624a71728980ad40c60d686da8fd5c0
|
shrenik77130/Repo5Batch22PythonWeb
|
/#3_Python_Complex_Programs/Program15.py
| 241
| 4.25
| 4
|
#WAP to input three digit number and print its reverse
no = int(input("Enter 3 Digit Number :")) #276 -> 27 -> 2
rem=no%10 #6
rev=rem
no=no//10
rem=no%10 #7
rev=rev*10+rem
no=no//10
rem=no%10 #2
rev=rev*10+rem
print("Reverse = ",rev)
| true
|
3833d1646b0470f64f8258265681cb1d098d9e39
|
shrenik77130/Repo5Batch22PythonWeb
|
/#3_Python_Complex_Programs/Program10.py
| 256
| 4.125
| 4
|
#WAP to input two numbers and perform Swapping
a=int(input("Enter value of a :"))
b=int(input("Enter value of b :"))
print(f"value of a = {a} and value of b = {b}")
t=a
a=b
b=t
print("After interchange")
print(f"value of a = {a} and value of b = {b}")
| true
|
55394cb82db15168880bdcddcfc2d3992bc2950b
|
shrenik77130/Repo5Batch22PythonWeb
|
/#4_IfElse_ConditionChecking/IfElseEx4.py
| 375
| 4.1875
| 4
|
'''
WAP to input any character and chek that entered character is vowel or consonent
'''
ch=input("Enter any Character :") #d
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
print(ch," is vowel")
else:
print(ch," is Consonent")
#Method-2
print("Using Method 2")
if ch in "aeiouAEIOU":
print(ch," is vowel")
else:
print(ch," is Consonent")
| false
|
2b44364a2d8bac7c9ac95bafe580d55e2e209613
|
paris3200/AdventOfCode
|
/code/Y2015/D05.py
| 2,562
| 4.15625
| 4
|
import re
import string
if __name__ != "__main__":
from Y2015 import utils
else:
import utils
def check_three_vowels(text: str) -> bool:
"""Checks if the input text has 3 or more vowels [aeiou]."""
result = re.search("^(.*[aeuio].*){3,}$", text)
if result:
return True
else:
return False
def check_repeat_characters(text: str) -> bool:
"""Checks if two characters repeat one after another in the text."""
chars = list(string.ascii_lowercase)
for char in chars:
regex_str = char + "{2}"
result = re.search(regex_str, text)
if result:
return True
return False
def check_forbidden_characters(text: str) -> bool:
"""Checks if the forbidden characters are found in the text."""
forbidden_characters = ["ab", "cd", "pq", "xy"]
for chars in forbidden_characters:
result = re.search(chars, text)
if result:
return True
return False
def check_letter_pairs(text: str) -> bool:
"""Checks if a pair of letters occurs twice in the text without overlapping."""
result = re.search("(\\w{2}).*?(\\1)", text)
if result:
return True
else:
return False
def check_single_letter_repeat_with_single_char_between(text: str) -> bool:
"""Returns true if a single letter is repeated in the string with exactly one character between the repeats."""
result = re.search("(\\w)\\w{1}?(\\1)", text)
if result:
return True
else:
return False
def check_nice_words(text: str, version="1.0") -> bool:
"""Returns True for nice words, False for naughty words."""
if version == "1.0":
if (
check_repeat_characters(text) is True
and check_three_vowels(text) is True
and check_forbidden_characters(text) is False
):
return True
elif version == "2.0":
if (
check_letter_pairs(text) is True
and check_single_letter_repeat_with_single_char_between(text) is True
):
return True
return False
def part_one():
data = utils.read_lines("data/05.data")
sum = 0
for word in data:
if check_nice_words(word):
sum += 1
return sum
def part_two():
data = utils.read_lines("data/05.data")
sum = 0
for word in data:
if check_nice_words(word, version="2.0"):
sum += 1
return sum
if __name__ == "__main__":
print("Part One")
print(part_one())
print("Part Two")
print(part_two())
| true
|
5ad40813a589481b8afa46844746a3eb6e4c9da6
|
jessicagamio/calculator
|
/calculator.py
| 2,605
| 4.15625
| 4
|
"""Calculator
>>> calc("+ 1 2") # 1 + 2
3
>>> calc("* 2 + 1 2") # 2 * (1 + 2)
6
>>> calc("+ 9 * 2 3") # 9 + (2 * 3)
15
Let's make sure we have non-commutative operators working:
>>> calc("- 1 2") # 1 - 2
-1
>>> calc("- 9 * 2 3") # 9 - (2 * 3)
3
>>> calc("/ 6 - 4 2") # 6 / (4 - 2)
3
"""
def calc(s):
"""Evaluate expression."""
# create symbols string
symbol = '*/+-'
# convert s to list
s_list = s.split(' ')
# set current as a empty list
current = []
# while s_list has a value keep looping
while s_list:
# pop the last item in the list
num = s_list.pop()
# if not an operator append number as an int to current list
if num not in symbol:
current.append(int(num))
# if operator is + add each element in current list
elif num == '+':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc += curr
if len(s_list) == 0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '-':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc - curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '*':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc * curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
elif num == '/':
for i, curr in enumerate(current[::-1]):
if i == 0:
calc=curr
else:
calc = calc // curr
if len(s_list)==0:
return calc
else:
s_list.extend([str(calc)])
current=[]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED; WELL-CALCULATED! ***\n")
| true
|
2e655cc1d809c964b90f44f24d76126547ca0bba
|
Seabagel/Python-References
|
/3-working-with-strings/6-counting-all-the-votes-function.py
| 1,110
| 4.28125
| 4
|
# Create an empty dictionary for associating radish names
# with vote counts
counts = {}
# Create an empty list with the names of everyone who voted
voted = []
# Clean up (munge) a string so it's easy to match against other strings
def clean_string(s):
return s.strip().capitalize().replace(" "," ")
# Check if someone has voted already and return True or False
def has_already_voted(name):
if name in voted:
print(name + " has already voted! Fraud!")
return True
return False
# Count a vote for the radish variety named 'radish'
def count_vote(radish):
if not radish in counts:
# First vote for this variety
counts[radish] = 1
else:
# Increment the radish count
counts[radish] = counts[radish] + 1
for line in open("radishsurvey.txt"):
line = line.strip()
name, vote = line.split(" - ")
name = clean_string(name)
vote = clean_string(vote)
if not has_already_voted(name):
count_vote(vote)
voted.append(name)
print()
print("Results:")
for name in counts:
print(name + ": " + str(counts[name]))
| true
|
407b01007f41aeb2f7a3d055a0492a2f19c539eb
|
Nemo1122/python_note
|
/Python笔记/python基础/内置函数/enumerate函数.py
| 555
| 4.59375
| 5
|
# enumerate
"""
enumerate()是python的内置函数
enumerate在字典上是枚举、列举的意思
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,
利用它可以同时获得索引和值
enumerate多用于在for循环中得到计数
"""
# for index, number in enumerate(range(10)):
# print(index, number)
# enumerate还可以接收第二个参数,用于指定索引起始值
for index, number in enumerate(range(10), 1):
print(index, number)
| false
|
69b8ecf656173add61531024d7d8ed636e7f6f2b
|
maiwen/LeetCode
|
/Python/739. Daily Temperatures.py
| 1,904
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on 2018/7/16 15:22
@author: vincent
Given a list of daily temperatures, produce a list that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
"""
class Solution:
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
stack = []
result = [0] * len(temperatures)
stack.append(0)
for i, v in enumerate(temperatures):
while len(stack) !=0 and v > temperatures[stack[-1]]:
pre = stack.pop()
result[pre] = i-pre
stack.append(i)
return result
def dailyTemperatures1(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
# clever solution
# start backwards from the array
# first element is 0
# supporse we have found the correct days from position j+1 to the last
# consider j. two possibilities appear:
# temp[j] < temp[j+1] -> days[j] = 1
# temp[j] >= temp[j+1] -> we can skip to j+1 + days[j+1], since previous days are colder anyway
n = len(temperatures)
days = [0] * n
for i in range(n - 2, -1, -1):
j = i + 1
while True:
if temperatures[i] < temperatures[j]:
days[i] = j - i
break
elif days[j] == 0:
break
j += days[j]
return days
| true
|
a8141241380818f22c3f8a0f6285a247e01d11ce
|
NRJ-Python/Learning_Python
|
/Ch3/dates_start.py
| 923
| 4.5
| 4
|
#
# Example file for working with date information
# (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
from datetime import date
from datetime import time
from datetime import datetime
def main():
#Date Objects
#Get today's date from today() method from date class
today=date.today()
print("Today's date is :",today)
#Print out date's individual components
print("Date Components :",today.day,today.month,today.year)
#Retrieve today's weekday (0=Monday , 6=Sunday)
print("Today's weekday is",today.weekday())
#Get today's date and time from datetime class
today=datetime.now()
print("The date and time is :",today)
#Get the current time
t=datetime.time(datetime.now())
print("The current time is :",t)
#Getting day number and day
wd=date.weekday(today)
print("Today's day number is %d" % wd)
day=["Mon", "Tue" ,"Wed"]
print("And the days is ",day[wd])
if __name__ == "__main__":
main();
| true
|
06f466b42e1bf98c87524ce271dbaa86356fdbe0
|
decodificar/EstruturaDeDados
|
/Aula02/e1_maximo.py
| 1,804
| 4.125
| 4
|
'''
defina uma funcao maximo2 que recebe dois numeros e retorna o maior deles
'''
def maximo2(a, b):
if a > b:
return a
return b
'''
defina uma funcao maximo3 que recebe três numeros e retorna o maior deles
'''
def maximo3(a, b, c):
m = maximo2(a, b)
if m > c:
return m
return c
'''
defina uma funcao maximo4 que recebe quatro numeros e retorna o maior deles
'''
def maximo4(a, b, c, d):
m4 = maximo3(a, b, c)
if m4 > d:
return m4
return d
'''
defina uma funcao maximo5 que recebe cinco numeros e retorna o maior deles
'''
def maximo5(a, b, c, d, e):
m5 = maximo4(a, b, c, d)
if m5 > e:
return m5
return e
import unittest
class TestStringMethods(unittest.TestCase):
def test_maximo2(self):
self.assertEqual(maximo2(1,2),2)
self.assertEqual(maximo2(3,2),3)
self.assertEqual(maximo2(-1,-2),-1)
self.assertEqual(maximo2(-1,2),2)
def test_maximo3(self):
self.assertEqual(maximo3(1,2,3),3)
self.assertEqual(maximo3(10,2,3),10)
self.assertEqual(maximo3(1,20,3),20)
def test_maximo4(self):
self.assertEqual(maximo4(1,2,3,4),4)
self.assertEqual(maximo4(10,2,3,4),10)
self.assertEqual(maximo4(1,20,3,4),20)
self.assertEqual(maximo4(1,2,30,4),30)
def test_maximo5(self):
self.assertEqual(maximo5(10,2,3,4,5),10)
self.assertEqual(maximo5(1,20,3,4,5),20)
self.assertEqual(maximo5(1,2,30,4,5),30)
self.assertEqual(maximo5(1,2,3,40,5),40)
self.assertEqual(maximo5(1,2,3,4,50),50)
def runTests():
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestStringMethods)
unittest.TextTestRunner(verbosity=2,failfast=True).run(suite)
runTests()
| false
|
ce8e850c1b992acfacce608077bca948c4f33373
|
AlexDamiao86/python-projects
|
/Battleship.py
| 1,142
| 4.1875
| 4
|
from random import randint
board = []
#Inicializa um array com 5 posições com "O"
ocean = ["O"] * 5
#Inicializa a matriz de duas dimensões
for i in range(5):
board.append(ocean)
def print_board(board):
for row in board:
print(" ".join(row))
def random_row(board):
row = randint(0, len(board) - 1)
print(row)
return row
def random_col(board):
col = randint(0, len(board) - 1)
print(col)
return col
print_board(board)
ship_row = random_row(board)
ship_col = random_col(board)
for turn in range(3):
guess_row = int(input("Guess row: "))
guess_col = int(input("Guess col: "))
if guess_row not in range(len(board)) or \
guess_col not in range(len(board)):
print("Oops, that's not even in the ocean.")
else:
if guess_row == ship_row and guess_col == ship_col:
print("Right!")
else:
if board[guess_row][guess_col] == "X":
print("You guessed that one already")
else:
print("Wrong..")
board[guess_row][guess_col] = 'X'
print_board(board)
| false
|
ff407d313085cd40426d61ffc481ffc44acb0f71
|
srczhou/ProficientPython
|
/palindrome_linked_list.py
| 2,355
| 4.21875
| 4
|
#!/usr/bin/env python3
import sys
class ListNode:
def __init__(self, data=0, next_node=None):
self.data = data
self.next = next_node
#from reverse_linked_list_iterative import reverse_linked_list
def reverse_singly_list(L):
if not L:
return None
dummy_head = ListNode(0, L)
while L.next:
temp = L.next
dummy_head.next, L.next, temp.next = (temp, temp.next, dummy_head.next)
return dummy_head.next
def is_linked_list_a_palindrome(L):
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# Compares the first half and the reversed second half lists.
# if n is odd, the first half will go one step more step, but same result.
first_half_iter, second_half_iter = L, reverse_singly_list(slow)
while second_half_iter and first_half_iter:
if second_half_iter.data != first_half_iter.data:
return False
second_half_iter, first_half_iter = (second_half_iter.next,
first_half_iter.next)
return True
def main():
head = None
if len(sys.argv) > 2:
# Input the node's value in reverse order.
for i in sys.argv[1:]:
curr = ListNode(int(i), head)
head = curr
print('Yes' if is_linked_list_a_palindrome(head) else 'No')
assert is_linked_list_a_palindrome(None)
assert is_linked_list_a_palindrome(ListNode(1))
assert is_linked_list_a_palindrome(ListNode(1, ListNode(1)))
assert is_linked_list_a_palindrome(ListNode(1, ListNode(2))) == False
assert is_linked_list_a_palindrome(
ListNode(1, ListNode(3, ListNode(2, ListNode(1))))) == False
head = None
# A link list is a palindrome.
for _ in range(6):
curr = ListNode(1, head)
head = curr
assert is_linked_list_a_palindrome(head)
# Still a palindrome linked list.
head = None
for _ in range(5):
curr = ListNode(1, head)
head = curr
head.next.next.data = 3
assert is_linked_list_a_palindrome(head)
# Not a palindrome linked list.
head = None
for i in reversed(range(1, 5)):
curr = ListNode(i, head)
head = curr
assert is_linked_list_a_palindrome(head) == False
if __name__ == '__main__':
main()
| true
|
4d3751389ef8147c17e6bb43da20015a41761864
|
narnat/leetcode
|
/sort_list/sort_list.py
| 2,728
| 4.15625
| 4
|
#!/usr/bin/env python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
""" Regular recursive solution"""
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
mid = self.middleNode(head)
middle = mid.next
mid.next = None
left = self.sortList(head)
right = self.sortList(middle)
return self.mergeTwoLists(left, right)
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
cur = head
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return head.next
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = prev = head
while fast and fast.next:
fast = fast.next.next
prev = slow
slow = slow.next
return prev
class Solution_2:
""" Bottom up, no recursion solution"""
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
def length(head):
count = 0
while head:
count += 1
head = head.next
return count
def split(head, step):
i = 1
while i < step and head:
head = head.next
i += 1
if not head: return None
middle, head.next = head.next, None
return middle
def mergeTwoLists(l1: ListNode, l2: ListNode, root: ListNode) -> ListNode:
head = root
cur = head
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
while cur.next: cur = cur.next
return cur # Returns the last node
size = length(head)
step = 1
dummy = ListNode()
dummy.next = head
tail = l = r = None
while step < size:
cur = dummy.next
print(cur.val)
tail = dummy
while cur:
l = cur
r = split(l, step)
cur = split(r, step)
tail = mergeTwoLists(l, r, tail)
step *= 2
return dummy.next
| true
|
90cdd14aa9dfef098b62b74116c000ad29a9783e
|
Bryan1998/python
|
/year-2/convert-km-mi.py
| 532
| 4.1875
| 4
|
# convert-km-mi.py bph
def print_menu():
print('1: Kilometers to Miles')
print('2: Miles to Kilometers')
def converter(selector):
if selector == 1:
distance = float(input('Enter a distance in Kilometers: '))
math = distance / 1.60934
elif selector == 2:
distance = float(input('Enter a distance in Miles: '))
math = distance * 1.60934
print('Converted distance for selection {0}: {1}'.format(selector, math))
if __name__ == '__main__':
print_menu()
choice = int(input('Choose a conversion: '))
converter(choice)
| false
|
a7198cf7640343771137bec333d57f8b777301b1
|
Lyubov-smile/SEP
|
/Data/task24.py
| 499
| 4.4375
| 4
|
# 24. Write a Python program to print the elements of a given array.
Sample array : ["Ruby", 2.3, Time.now]
import sys
sv = (sys.version)
sv1 = sv[0:6]
print(sv)
print(sv1,"\n")
import datetime
import array
now = datetime.datetime.now()
dt = datetime.datetime.now().strftime("%H.%M")
print(dt, type(dt))
dt1 = float(dt)
a1 = "Ruby"
a2 = 2.3
a3 = dt1
print(a1, a2, a3)
ar = [a1, a2, a3]
print(ar)
#ar = ar + [dt]
#a = ["Ruby", 2.3, % now.hour, % now.minute"]
#print(a[0],a[1],a[2])
| true
|
48f6dc47d99b3f3e679c12a02c44af0edc9885c7
|
Lyubov-smile/SEP
|
/Statements_syntax/task23.py
| 696
| 4.25
| 4
|
# 23. Write a Python program to check whether a given value appears everywhere in a given array.
# A value is "everywhere" in an array if it presents for every pair of adjacent elements in the array.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
#arr = [1, 3, 5, 2, 7, 5]
value = int(input('Input value which you want to check:'))
for i in range(len(arr)):
if arr[i] == value:
i += 1
inf = 'Every element in array = '
else:
inf = 'Not every element in array = '
break
print(inf, value)
| true
|
0ea8922947d6f6b578adf79034feb4af42f49620
|
Lyubov-smile/SEP
|
/Statements_syntax/task14.py
| 474
| 4.28125
| 4
|
# 14. Write a Python program to check if a given array of integers contains 3 twice, or 5 twice.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
if arr.count(3) == 2 or arr.count(5) == 2:
print('Array of integers contains 3 or 5 twice')
else:
print('Array of integers doesn\'t contains 3 or 5 twice')
| true
|
29a7e843519581a67df4ac8a22a3c24512b17662
|
Lyubov-smile/SEP
|
/Data/task04.py
| 267
| 4.46875
| 4
|
# 4. Write a Python program which accepts the radius of a circle from the user and compute the parameter and area.
r = float(input('Input the radius of a circle: '))
import math
p = 2 * r * math.pi
s = r ** 2 * math.pi
print('P=', p, sep='')
print('S=', s, sep='')
| true
|
787360a936fa50633e29dac47347e9c49fb8a520
|
Lyubov-smile/SEP
|
/Statements and syntax/task22.py
| 360
| 4.375
| 4
|
# 22. Write a Python program to check whether every element is a 3 or a 5 in a given array of integers.
arr = [3, 5, 3, 5, 3]
#[1, 3, 5, 2, 7, 5]
for i in range(len(arr)):
if arr[i] == 3 or arr[i] == 5:
i += 1
inf = 'Every element in array = 3 or 5'
else:
inf = 'Not every element in array = 3 or 5'
break
print(inf)
| true
|
26100f9023f28861bcb35b8a5fbc20f26bcd15c4
|
Lyubov-smile/SEP
|
/Statements_syntax/task17.py
| 427
| 4.375
| 4
|
# 17. Write a Python program to get the number of even integers in a given array.
n = int(input('Input the length of your array: '))
if n < 1:
print("The length of array can't be less than 1!")
arr = []
for i in range(n):
arr.append(int(input('Input an integer element of array: ')))
n = 0
for i in range(len(arr)):
if arr[i] %2 == 0:
n += 1
print('The number of even integers in a given array is', n)
| true
|
a45b7b1ea7b5f9ab8d48c6507cd1d9c2f1d57f34
|
Lyubov-smile/SEP
|
/Statements and syntax/task23.py
| 425
| 4.21875
| 4
|
# 23. Write a Python program to check whether a given value appears everywhere in a given array.
# A value is "everywhere" in an array if it presents for every pair of adjacent elements in the array.
arr = [1, 3, 5, 2, 7, 5]
value = 3
for i in range(len(arr)):
if arr[i] == 3:
i += 1
inf = 'Every element in array = 3'
else:
inf = 'Not every element in array = 3'
break
print(inf)
| true
|
507e355168f72472d5b189bb95e9783c6539e554
|
1877762890/python_all-liuyingyign
|
/day05任务及课上代码/代码/day05/demo/demo1.py
| 1,153
| 4.28125
| 4
|
'''
python:
56,23,25:整型(int)
56.31:浮点数据(float,double)
"hello world" "刘嘉伟":字符串(str)
True,False:布尔(boolean)
元组:(1,4,5,6,6,8,2,10) 不可能在改变
列表:[1,2,3,4,5,6,65,5,47] 数据可以随时改变
字典:{
"010":"南京",
"020":"上海",
}
(键值对应关系。特点:不能存储重复数据。)
集合:(1,5,7,8,9,9):不能存储重复的数据
''',
'''
a = 56
b = "张家玮"
c = True
d = 6.32
print(type(a))
print(type(b))
print(type(c))
print(type(d))
'''
'''
列表:[]
常用的api:
len() 求长度
'''
'''print(a[0])
print(a[1])
print(a[2])
print("列表的长度:",len(a))
'''
a = [-9,-5,-4,-2,-3,-7,-8,-9]
max = a[0]
index = -1
for i in range(0,len(a)):
if a[i] >= max:
max = a[i]
index = i
print("a里的最大值为:",max,",所对应角标为:",index)
# 求所有数的和
| false
|
62683c96cca30403c196eaf641b2e3e712cb1a1b
|
Max-Rider/basic-number-guessing-game
|
/number_guesser.py
| 952
| 4.25
| 4
|
# Maxwell Rider
# September 23 2020
# A very simple number guessing game where you guess a number between 1 and 100
# and the computer tells you if its too high or too low
# This is simply to help boost my python knowledge as I am very much a beginner as of writting this
from __future__ import print_function
import random
def higherOrLower():
numToGuess = random.randint(1, 100)
userNum = None
while userNum != numToGuess:
userNum = int(input("Guess my number (between 1 and 100): "))
if userNum > numToGuess:
print("To high!")
elif userNum < numToGuess:
print("To low")
else:
break
print("You got my number!")
if __name__ == "__main__":
higherOrLower()
playAgain = input("Want to play again? Y/N: ")
if playAgain == "Y" or playAgain == "y":
higherOrLower()
else:
print("Thanks for playing!")
| true
|
dcfe96e876467e66b04247b2bf6b5cd0222b826f
|
avielz/self.py_course_files
|
/hangman_project/5.5.1.py
| 1,823
| 4.28125
| 4
|
#hangman code learning python
HANGMAN_ASCII_ART = ("""Welcome to the game Hangman\n _ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \'
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/""")
print(HANGMAN_ASCII_ART)
#import random
#print (random.randint(5,10))
MAX_TRIES = 6
print(MAX_TRIES)
#>>> is_valid_input('a')
#True
#>>> is_valid_input('A')
#True
#>>> is_valid_input('$')
#False
#>>> is_valid_input("ab")
#False
#>>> is_valid_input("app$")
#False
#Guess a letter: ab
#E1
#Guess a letter: $
#E2
#Guess a letter: app$
#E3
def is_valid_input(letter_guessed):
"""Cheking that the guessed letter is a valid letter.
:param letter_guessed: the letter the user guessed already in lower case
:param letter_test: holds the result of the validation test
:type letter_guessed: string
:type letter_test: boolean
:return: The result of the letter test
:rtype: boolean
"""
if len(letter_guessed) > 1 and not letter_guessed.isalpha() :
letter_test = False
elif len(letter_guessed) > 1 :
letter_test = False
elif not letter_guessed.isalpha() :
letter_test = False
else : letter_test = True
return(letter_test)
guessed_letter = input("Guess a letter: ")
letter_guessed_lower = guessed_letter.lower()
check_letter = is_valid_input(letter_guessed_lower)
print(check_letter)
#Please enter a word: hangman
#_ _ _ _ _ _ _
#i thought the solution was based on the replace method but it turned out to be much more simple!
#new_string = input_string[0] + sliced_input_string.replace(first_chr, "e")
#guessed_word = input("Please enter a word: ")
#spaces = (len(guessed_word) * "_ ")
#print(spaces)
| false
|
be28e73a27607679fa8b6a87bc7c8f7c44279367
|
avielz/self.py_course_files
|
/self.py-unit6 lists/6.1.2.py
| 579
| 4.28125
| 4
|
def shift_left(my_list):
"""Shift items in the list to the left.
:param my_list: the list with the items
:param last_item: will get the last item from my list
:type my_list: list
:type last_item: string
:return: The list with the items shifted to the left
:rtype: list
"""
last_item = my_list.pop()
my_list.insert(0,last_item)
return(my_list)
the_list = input("Enter items to place in a list: ")
the_list = the_list.split()
print(the_list)
shifted_list = shift_left(the_list)
print("I shifted all the items to the lfet: ",shifted_list)
| true
|
2cf335bf134fe8301e05aa9c60ef03d154be10ab
|
nicholasji/IS211_Assignment1
|
/assignment1_part1.py
| 1,098
| 4.21875
| 4
|
#!usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 1 Part 1"""
class ListDivideException(Exception):
"""Exception"""
def listDivide(numbers, divide=2):
"""Divisible by divide.
Args:
numbers(list): a list of numbers
divide(integer): a divisor integer default set to 2
Return:
Int: Number of elements divisible by divide.
"""
counter = 0
for number in numbers:
if number % divide == 0:
counter += 1
return counter
def testListDivide():
"""Test of listDivide."""
test1 = listDivide([1, 2, 3, 4, 5])
test2 = listDivide([2, 4, 6, 8, 10])
test3 = listDivide([30, 54, 63, 98, 100], divide=10)
test4 = listDivide([])
test5 = listDivide([1, 2, 3, 4, 5], 1)
bigtest = (test1, test2, test3, test4, test5)
while test1 == int(2):
while test2 == int(5):
while test3 == int(2):
while test4 == int(0):
while test5 == int(5):
return bigtest
else:
raise ListDivideException('List Divide Exception')
| true
|
2e88aa71a50bec39e0c64b8466c2f5bc888b7340
|
delacruzfranklyn93/Python--Challenge
|
/PyBank/Bank.py
| 2,486
| 4.1875
| 4
|
# import libraries
import os
import csv
# Declare the variable that you think you might be using
months = 0
net_total = 0
avg_change = []
greatest_increase = 0
greatest_decrease = 0
current = 0
past = 0
month_increase = ""
month_decrease = ""
# Read in the data into a list
csv_path = os.path.join( "Resources", "budget_data.csv")
txt_outpath = os.path.join("Analysis", "bank.txt")
with open(csv_path) as csv_file:
budget_data = csv.reader(csv_file, delimiter = ",")
header = next(budget_data)
# Create a for statements that will go thorugh each row in the dataset that was read in
for i, row in enumerate(budget_data):
# Increase the month counter for to receive the total number of months
months += 1
# Start adding the profit losses to net_total to get the final net_total
net_total += int(row[1])
# Create the list of profit/losses changes month to month for the entire data set
if i > 0:
current = int(row[1])
avg_change.append(current - past)
monthly_change = current - past
# Check to see if the monthly_change is greater than the greatest_increase thus far and if so update.
if monthly_change > greatest_increase:
month_increase = row[0]
greatest_increase = monthly_change
# Check to see if the monthly_change is less than the greatest_decrease thus far and if so update.
elif monthly_change < greatest_decrease:
month_decrease = row[0]
greatest_decrease = monthly_change
past = int(row[1])
else:
past = int(row[1])
# Calculate the avg_change using sum and len
avg_change = round(sum(avg_change)/len(avg_change), 2)
# Open a new file where we will write our Analysis to and start writing
with open(txt_outpath, "w") as outfile:
outfile.write("Financial analysis\n")
outfile.write("-----------------------------\n")
outfile.write(f"Total Months: {months}\n")
outfile.write(f"Total: ${net_total}\n")
outfile.write(f"Average Change: ${avg_change}\n")
outfile.write(f"Greatest Increase in Profits: {month_increase} (${greatest_increase})\n")
outfile.write(f"Greatest Decrease in Profits: {month_decrease} (${greatest_decrease})\n")
# Open the new file you just created and also print the results on the terminal
with open(txt_outpath) as print_file:
print(print_file.read())
| true
|
9fac2d1b600b43bb2e9842ca5028532f5b6feb1b
|
icimidemirag/GlobalAIHubPythonCourse
|
/Homeworks/HW1.py
| 542
| 4.4375
| 4
|
#Create two lists. The first list should consist of odd numbers. The second list is also of even numbers.
#Merge two lists. Multiply all values in the newlist by 2.
#Use the loop to print the data type of the all values in the new list.
#Question 1
oddList = [1,3,5,7,9]
evenList = [0,2,4,6,8]
oddList.extend(evenList)
newList = [x*2 for x in oddList]
for i in newList: #newList elemanlarını yazdırır.
print(i, end=" ")
print("\n")
for i in newList: #newlist elemanlarının typelarını yazdırır.
print(type(i), end=" ")
| true
|
c17b1ed61bb9753fcae4633bb059af8f5ffba1e1
|
BhargavKadali39/Python_Data_Structure_Cheat_Sheet
|
/anti_duplicator_mk9000.py
| 474
| 4.125
| 4
|
List_1 = [1,1,1,2,3,4,4,4,5,5,6,6]
'''
# The old method
List_2 = []
for i in List_1:
if i not in List_2:
List_2.append(i)
print(List_2)
# Still this old method is faster than the other.
# Execution time is: 0.008489199999999975
# That much doesn't matter much,not in the case while working with big amount of data.
'''
# Removing Duplicates using set() and List() methods.
List_3 = list(set(List_1))
print(List_3)
# Execution time is: 0.011315100000000022
| true
|
9e10430c18dbdc82851fa9e58dacfb435b749b5e
|
Dillonso/bio-django
|
/ReverseComplement/process.py
| 547
| 4.25
| 4
|
# reverseComplement() function returns the revurse complement of a DNA sequence
def reverseComplement(stringInput):
# Reverse the input
string = stringInput[::-1].upper()
# define pairs dict
pairs = {
'A':'T', 'T':'A',
'G':'C', 'C':'G'
}
# Turn string into list
_list = list(string)
# Define a new empty list
new = []
# Iterate through the sequence list and append corresponding chars from pairs dict to new list
for char in _list:
new.append(pairs[char])
# Join and return the new list as a string
return ''.join(new)
| true
|
5e55d26cb147fcb6afba6d672328471a00c39dc5
|
compwron/euler_py
|
/euler9.py
| 463
| 4.25
| 4
|
# A Pythagorean triplet is a set of three natural numbers, a b c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def pythagorean_triplet_adds_up_to(number):
for a in range(1, number -1):
for b in range(1, number -1):
for c in range(1, number -1):
if ((a + b + c == number) and (a * a + b * b == c * c)):
return a * b * c
| false
|
0f89dafea5460e09641fde03a3bba3f8571e4641
|
arjunreddy-001/DSA_Python
|
/Algorithms/CountdownUsingRecursion.py
| 294
| 4.25
| 4
|
# use recursion to implement a countdown timer
def countdown(x):
if x == 0:
print("Done!")
return
else:
print(x, "...")
countdown(x - 1)
print("foo") # this code will execute after we reach the top of call stack
countdown(5)
| true
|
ffbcd78e46dbb32c172ee980f837c5c32d3a118f
|
jkorstia/Intro2python
|
/population.py
| 1,284
| 4.125
| 4
|
# a program to calculate population size after a user specified time (in years)
# demographic rates are fixed, initial population size is 307357870 selfie taking quokkas
# This script is designed to model quokka populations! Use with other species at your own risk.
# ask user for number of years (inputs as string)
yr_str=input("How many years into the future would you like to predict the population size?")
# convert year string to integer
yr_int=int(yr_str)
# define demographic statistics in seconds
birth_s=7
death_s=13
imm_s=35
# starting population size in quokkas
pop=307357870
# convert demographic statistics to years. 31536000 seconds are in a year (60s*60m*24hrs*365days).
birth_y=birth_s*31536000
death_y=death_s*31536000
imm_y=imm_s*31536000
#since the population changes every year, this must be re-evaluated after each year
#sets up the initial population for the loop
initial_population=pop
count=0
while(count < yr_int):
#counter for number of years
count = count + 1
#figures out the final population after i years
final_population=initial_population+birth_y+imm_y-death_y
#prints out results
print("After", count, "years the population is", final_population)
# readjusts the initial population for subsequent years
initial_population=final_population
| true
|
673d177a709a5c019892d42b8579b12e6d13c790
|
alexwolf22/Python-Code
|
/Cities QuickSort/quicksort.py
| 1,203
| 4.34375
| 4
|
#Alex Wolf
#Quicksort Lab
#functions that swaps two elements in a list based off indexs
def swap(the_list,x,y):
temp=the_list[x]
the_list[x]=the_list[y]
the_list[y]=temp
#partition function that partitions a list
def partition(the_list, p, r, compare_func):
pivot =the_list[r] #sets pivot to last element of list
i=p-1
j=p
while j<r:
if compare_func(the_list[j],pivot):
i+=1
swap(the_list, j,i) #swaps elements at index i and j if j is less than pivot
j+=1
#swaps pivot with index i+1, and returns that index
swap(the_list,r,i+1)
return i+1
#recursive quicksort function
def quicksort(the_list, p, r, compare_func):
if r>p:
#q= index of the list which list was partitioned
q= partition(the_list, p, r, compare_func)
#recursively call quicksort on the two sublist left and right of q
quicksort(the_list, p, q-1, compare_func)
quicksort(the_list, q+1, r, compare_func)
#function that sorts a list based off a specific comparison
def sort(the_list, compare_func):
quicksort(the_list,0,len(the_list)-1, compare_func)
| true
|
60fab78905611616e336ccd8a320332099302905
|
jjinho/rosalind
|
/merge_sort_two_arrays/main.py
| 1,755
| 4.15625
| 4
|
#!/usr/bin/python3
"""
Merge Sort Two Arrays
Given: A positive integer n <= 10^5 and a sorted array A[1..n] of integers
from -10^5 to 10^5, a positive integer m <= 10^5 and a sorted array B[1..m] of
integers from -10^5 to 10^5.
Return: A sorted array C[1..n+m] containing all the elements of A and B.
"""
def main():
n = 0 # number of elements in array A
m = 0 # number of elements in array B
array_a = []
array_b = []
# Parse in.txt
with open('./in.txt') as f:
for i, line in enumerate(f):
if i == 0:
n = int(line.strip())
if i == 1:
array_a = [int(x) for x in line.split()]
if i == 2:
m = int(line.strip())
if i == 3:
array_b = [int(x) for x in line.split()]
# Non-recursive way to solve
array_c = []
while array_a and array_b:
if array_a[0] < array_b[0]:
array_c += [array_a.pop(0)]
else:
array_c += [array_b.pop(0)]
# Can do this because array_a and array_b are already sorted
if array_a:
array_c += array_a
if array_b:
array_c += array_b
for x in array_c:
print(x, end=" ")
print()
# This works but is too
def merge_arrays(array_a, array_b):
if array_a and array_b:
if array_a[0] < array_b[0]:
return [array_a.pop(0)] + merge_arrays(array_a, array_b)
else:
return [array_b.pop(0)] + merge_arrays(array_a, array_b)
else:
if array_a:
return array_a
if array_b:
return array_b
return array_c
if __name__ == '__main__':
main()
| true
|
d239f0a21759c9cc3275d87c740fca7a525a094c
|
jjinho/rosalind
|
/insertion_sort/main.py
| 1,028
| 4.4375
| 4
|
#!/usr/bin/python3
"""
Insertion Sort
Given: A positive ingeter n <= 10^3 and an array A[1..n] of integers.
Return: The number of swaps performed by insertion sort algorithm on A[1..n].
"""
def main():
n = 0 # number of integers in array A
array = []
# Parse in.txt
with open('./in.txt') as f:
for i, line in enumerate(f):
if i == 0:
n = int(line)
else:
array = [int(x) for x in line.split()]
print(insertion_sort_swaps(array))
def insertion_sort_swaps(array):
"""Number of times insertion sort performs a swap
Args:
array: An unsorted list that will undergo insertion sort.
Returns:
The number of swaps that insertion sort performed.
"""
swap = 0
for i, x in enumerate(array):
k = i
while k > 0 and array[k] < array[k-1]:
array[k], array[k-1] = array[k-1], array[k]
swap += 1
k -= 1
return swap
if __name__ == '__main__':
main()
| true
|
17c1ead3976a4f33a8a101096a3b963f722d95ed
|
gutnikvk/learning_python
|
/gvk/fibonacci/better_alg.py
| 436
| 4.125
| 4
|
def check_input_number(n):
if n < 0: raise ValueError('It has to be >= 0')
def get_fibonacci_number(n):
fibonacciRow = []
for i in range(n+1):
if i<=1: fibonacciRow.append(i)
else: fibonacciRow.append(fibonacciRow[i-1] + fibonacciRow[i-2])
return fibonacciRow[n]
if __name__ == '__main__':
n = int(input('Input a positive integer\n'))
check_input_number(n)
print(get_fibonacci_number(n))
| false
|
1df31164bee68d1f7a3d824d820f9be602797b3f
|
ziyang-zh/pythonds
|
/01_Introduction/01_03_input_and_output.py
| 741
| 4.15625
| 4
|
#input and output
#aName=input('Please enter your name: ')
aName="David"
print("Your name in all capitals is",aName.upper(),"and has length",len(aName))
#sradius=input("Please enter the radius of the circle ")
radius=2
radius=float(radius)
diameter=2*radius
print(diameter)
#format string
print("Hello")
print("Hello","world")
print("Hello","world",sep="***")
print("Hello","world",end="***\n")
age=18
print(aName,"is",age,"years old.")
print("%s is %d years old."%(aName,age))
price=24
item="banana"
print("The %s costs %d cents"%(item,price))
print("The %+10s costs %5.2f cents"%(item,price))
print("The %+10s costs %10.2f cents"%(item,price))
itemdict={"item":"banana","cost":24}
print("The %(item)s costs %(cost)7.1f cents"%itemdict)
| true
|
5cf1d1d96e8ea34205a206273b8e8eb7e1a466ca
|
prohodilmimo/turf
|
/packages/turf_helpers/index.py
| 2,552
| 4.34375
| 4
|
from numbers import Number
factors = {
"miles": 3960,
"nauticalmiles": 3441.145,
"degrees": 57.2957795,
"radians": 1,
"inches": 250905600,
"yards": 6969600,
"meters": 6373000,
"metres": 6373000,
"kilometers": 6373,
"kilometres": 6373
}
def radians_to_distance(radians, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from radians to a more friendly unit
:type radians: Number
:param radians: distance in radians across the sphere
:type units: str
:param units: units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: distance
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError('Invalid unit')
return radians * factor
def distance_to_radians(distance, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from a real-world unit into radians
:type distance: Number
:param distance: distance in real units
:type units: str
:param units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: radians
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError("Invalid unit")
return distance / factor
def distance_to_degrees(distance, units="kilometers"):
# type: (Number, str) -> Number
"""
Convert a distance measurement from a real-world unit into degrees
:type distance: Number
:param distance: distance in real units
:type units: str
:param units: one of miles, nauticalmiles, degrees, radians,
inches, yards, metres, meters, kilometres, kilometers
:rtype: Number
:return: degrees
:raises ValueError: when fed with an invalid unit type
"""
factor = factors[units]
if factor is None:
raise ValueError("Invalid unit")
return (distance / factor) * 57.2958
__all__ = [
"factors",
"radians_to_distance",
"distance_to_radians",
"distance_to_degrees"
]
| true
|
7efe282d6ded5d17da05d420c71f7963be4dc419
|
alexacanaan23/COSC101
|
/hw03_starter/hw03_turtleword.py
| 1,619
| 4.34375
| 4
|
# ----------------------------------------------------------
# -------- HW 3: Part 3.1 ---------
# ----------------------------------------------------------
# ----------------------------------------------------------
# Please answer these questions after you have completed this
# program
# ----------------------------------------------------------
# Name: Alexa Canaan
# Time spent on part 3.1: 1.5 hours
# Collaborators and sources: https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.getshapes
# (List any collaborators or sources here.)
# ----------------------------------------------------------
# Write your python program for part 3.1 below:
#set up turtle
import turtle
wn = turtle.Screen()
bob = turtle.Turtle
#set attributes
wn.bgcolor("black")
turtle.pencolor("white")
#get the word to be used
word = input("Word to be spaced in a circular, clockwise position: ")
num = len(word)
angle = 360 / num
#turns turtle to appropriate starting position facing north
turtle.left(90)
#for words with even amount of letters or for words with odd amount
if num % 2 == 0:
for i in word:
turtle.right(angle)
turtle.penup()
turtle.forward(200)
turtle.write(i, True, align="right", font=("Arial", 16, "normal"))
turtle.backward(200)
else:
turtle.right(angle/2)
for i in word:
turtle.penup()
turtle.forward(200)
turtle.write(i, True, align="right", font=("Arial", 16, "normal"))
turtle.backward(200)
turtle.right(angle)
#ending
turtle.hideturtle()
wn.exitonclick()
| true
|
83c64368ab1d5b532f42d8a792f6e60c8b195f3c
|
AndriiSotnikov/py_fcsv
|
/fcsv.py
| 462
| 4.28125
| 4
|
"""There is a CSV file containing data in this format: Product name, price, quantity
Calculate total cost for all products."""
import csv
def calc_price(filename: str, open_=open) -> float:
"""Multiply every second and third element in the row, and return the sum"""
with open_(filename, 'rt') as file:
reader = csv.reader(file, delimiter=',')
total_cost = sum([float(row[1])*float(row[2]) for row in reader])
return total_cost
| true
|
22815c71694d907bb322a2ef02f73bd2d617856d
|
newbieeashish/LeetCode_Algo
|
/3rd_30_questions/ConstructTheRectangle.py
| 1,202
| 4.34375
| 4
|
'''
For a web developer, it is very important to know how to design a
web page's size. So, given a specific rectangular web page’s area,
your job by now is to design a rectangular web page, whose length
L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal to
given target area.
2. The width W should not be larger than the length L, which means
L >= W.
3. The difference between length L and width W should be as small
as possible.
You need to output the length L and the width W of the web page
you designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to
construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to
requirement 3, [4,1] is not optimal compared to [2,2]. So the
length L is 2, and the width W is 2.
'''
import math
def constructRectangle(area):
sqrt_val = int(math.sqrt(area))
l = w = sqrt_val
while (l * w) != area and l > 0 and w > 0:
l += 1
w = area // l
return [l, w] if w > 1 else (area, 1)
print(constructRectangle(4))
| true
|
e0e976dd9ec32a240382544cb36bf2f42a59a0df
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/TransposeMatrix.py
| 456
| 4.46875
| 4
|
'''
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main diagonal,
switching the row and column indices of the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
'''
import numpy as np
def TransposeMatrix(A):
return np.transpose(A)
print(TransposeMatrix([[1,2,3],[4,5,6]]))
| true
|
884106b89d0e1bf8b34f22c55e53894f8b587191
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/ShortestCompletingWord.py
| 1,714
| 4.40625
| 4
|
'''
Find the minimum length word from a given dictionary words, which has all the
letters from the string licensePlate. Such a word is said to complete the
given string licensePlate
Here, for letters we ignore case. For example, "P" on the licensePlate still
matches "p" on the word.
It is guaranteed an answer exists. If there are multiple answers, return the
one that occurs first in the array.
The license plate might have the same letter occurring multiple times. For
example, given a licensePlate of "PP", the word "pair" does not complete the
licensePlate, but the word "supper" does.
Example 1:
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters
"S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the
word twice.
Also note that we ignored case for the purposes of comparing whether a
letter exists in the word.
Example 2:
Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.
'''
def ShortestCompletingWord(licensePlate, words):
words.sort(key=len)
licensePlate = licensePlate.lower()
for w in words:
flag = True
for char in licensePlate:
if char.isalpha():
if char not in w or licensePlate.count(char) > w.count(char):
flag = False
if flag == True:
return w
print(ShortestCompletingWord("1s3 456",["looks", "pest", "stew", "show"]))
| true
|
a788778604536cd38c6f74e26c982157cd874fb0
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/SelfDividingNumber.py
| 1,010
| 4.21875
| 4
|
'''
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0,
and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self
dividing number, including the bounds if possible.
Example 1:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
'''
def SelfDividingNumber(left,right):
output = []
for i in range(left, right+1):
number = 1
flag = 0
while i>0:
last_digit = i%10
if last_digit !=0:
if number%last_digit !=0:
flag =1
break
else:
flag = 1
break
if flag ==0:
output.append(number)
return output
print(SelfDividingNumber(1,22))
| true
|
86e19e215343fe545217ee67a4ea91ca28d2720c
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/CountLargestGroup.py
| 889
| 4.34375
| 4
|
'''
Given an integer n. Each number from 1 to n is grouped according to the sum of
its digits.
Return how many groups have the largest size.
Example 1:
Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its
digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with
largest size.
Example 2:
Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.
Example 3:
Input: n = 15
Output: 6
Example 4:
Input: n = 24
Output: 5
'''
def CountLargestGroup(n):
groups = {}
for i in range(1, n + 1):
key = sum(int(c) for c in str(i))
groups[key] = groups.get(key, 0) + 1
largest_size = max(groups.values())
return sum(size == largest_size for size in groups.values())
print(CountLargestGroup(2))
| true
|
ee428ee38ebe0ee081d7c0c3ebd982d6fa2c7649
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/SubtractProductAndSumOfDigit.py
| 656
| 4.21875
| 4
|
'''
Given an integer number n, return the difference between the product of its
digits and the sum of its digits.
Example 1:
Input: n = 234
Output: 15
Explanation:
Product of digits = 2 * 3 * 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
Example 2:
Input: n = 4421
Output: 21
Explanation:
Product of digits = 4 * 4 * 2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21'''
def SubtractProductAndSum(n):
product = 1
sum_n = 0
while(n!=0):
sum_n += (n%10)
product *= (n%10)
n = n//10
return product-sum_n
print(SubtractProductAndSum(4421))
| true
|
f1a7ee2726ef7de780efc31ba89d0e4e785036ee
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/ReverseWordsInSring3.py
| 378
| 4.21875
| 4
|
'''
Given a string, you need to reverse the order of characters in each word
within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
'''
def ReverseWords(s):
return ' '.join([w[::-1] for w in s.split()])
print(ReverseWords("Let's take LeetCode contest"))
| true
|
0305df4441a66096b9af78d25eff6892e76fdad1
|
newbieeashish/LeetCode_Algo
|
/1st_100_questions/MinAbsoluteDiff.py
| 976
| 4.375
| 4
|
'''
Given an array of distinct integers arr, find all pairs of elements with the
minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs),
each pair [a, b] follows
a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]
Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
'''
def MinAbsoluteDiff(arr):
arr.sort()
diff = [arr[i+1]-arr[i] for i in range(len(arr)-1)]
target = min(diff)
ouput = []
for i,d in enumerate(diff):
if d == target:
ouput.append([arr[i],arr[i+1]])
return ouput
print(MinAbsoluteDiff([4,2,1,3]))
| true
|
d15a64e9e07b8d528a42553c1a10ec070707b7ce
|
rob-kistner/modern-python
|
/orig_py_files/input.py
| 218
| 4.28125
| 4
|
""" ------------------------------
USER INPUT
------------------------------ """
# to get user input, just use the input() command...
answer = input("What's your favorite color? ")
print(f"you said {answer}")
| true
|
fdd2452fb771381589ba1aba38a9614c38eb0e60
|
olamiwhat/Algos-solution
|
/Python/shipping_cost.py
| 1,798
| 4.34375
| 4
|
#This program calculates the cheapest Shipping Method
#and Cost to ship a package at Sal's shipping
weight = int(input("Please, enter the weight of your package: "))
#define premium shipping cost as a variable
premium_shipping = 125.00
#Function to calculate cost of ground shipping
def ground_shipping (weight):
flat_rate = 20
if weight <= 2.0:
cost = (1.5 * weight) + flat_rate
return cost
elif weight <= 6.0:
cost = (3 * weight) + flat_rate
return cost
elif weight <= 10.0:
cost = (4 *weight) + flat_rate
return cost
else:
cost = (4.75 * weight) + flat_rate
return cost
#Test Function (uncomment)
#print(ground_shipping (8.4))
#Function to calculate cost of drone shipping
def drone_shipping (weight):
if weight <= 2.0:
cost = (4.5 * weight)
return cost
elif weight <= 6.0:
cost = (9 * weight)
return cost
elif weight <= 10.0:
cost = (12 *weight)
return cost
else:
cost = (14.25 * weight)
return cost
#Test Function(uncomment)
#print(drone_shipping (1.5))
#Function to determine the cheapest shipping method and cost
def cheapest_shipping_method_and_cost(weight):
ground = ground_shipping(weight)
drone = drone_shipping(weight)
premium = premium_shipping
if ground < drone and ground < premium:
print("Your cheapest shipping method is ground shipping, it will cost " + "$" + str(ground))
elif ground > drone and drone < premium:
print("Your cheapest shipping method is drone shipping, it will cost " + "$" + str(drone))
else:
print("Your cheapest shipping method is premium shipping, it will cost " + "$" + str(premium))
#Calculating the cheapest way to ship 4.8lb and 41.5lb of packages
cheapest_shipping_method_and_cost(weight)
#cheapest_shipping_method_and_cost()
| true
|
9410bcb027d9e094a401b37f04d02058109e6ae8
|
eduards-v/python_fundamentals
|
/newtons_square_root_problem.py
| 573
| 4.125
| 4
|
import math
x = 60 # a number to be square rooted
current = 1 # starting a guess of a square root value from 1
# function that returns a value based on a current guess
def z_next(z):
return z - ((z*z - x) / (2 * z)) # Newton's formula for calculating square root of a number
while current != z_next(current):
current = z_next(current)
# this line allows to break from infinite loop
# if square root value goes to infinity
if(math.fabs(current - z_next(current))<0.000000001): break
print(current)
print("\nSquare root of ", x, " is ", current)
| true
|
42c76cf495a75abc3db6ad82e690903c9eced113
|
paco-portada/Python
|
/Python basico/arraysPython/unidimensionalesPython/ejercicio8.py
| 644
| 4.125
| 4
|
# -*- coding: utf-8 -*-
# ejercicio8.py
# Programa que pide la temperatura media que ha hecho en cada mes
# de un determinado año y muestra a continuación un diagrama de barras
# horizontales con esos datos. Las barras del diagrama se dibujan a base
# de asteriscos.
# entrada de datos
year = []
for i in range( 0 , 12 ):
print( "Introducir temperatura del " + str( i+1 ) + "er mes" , end=" " )
year.append( int( input() ) )
# crear diagrama de barras
for i in range( 0 , 12 ):
for j in range( int( year[i] / 2 ) ):
print( "*" , end="" )
print( " " + str( year[i] ) )
# Fin del programa
| false
|
f8466ceffa16b50353709259db1a57ae1e3c9814
|
paco-portada/Python
|
/Python basico/secuencialesPython/ejercicio12.py
| 595
| 4.21875
| 4
|
# ejercicio12.py
# Pide al usuario dos pares de números x1,y2 y x2,y2,
# que representen dos puntos en el plano.
# Calcula y muestra la distancia entre ellos.
# @author Alvaro Garcia Fuentes
from math import sqrt
print( "Datos del primer punto." )
x1 = ( float( input( "Introduzca x1: " ) ) )
y1 = ( float( input( "Introduzca y1: " ) ) )
print()
print( "Datos del segundo punto." )
x2 = ( float( input( "Introduzca x2: " ) ) )
y2 = ( float( input( "Introduzca y2: " ) ) )
distancia = sqrt( ( x2 - x1 )**2 + ( y2 - y1 )**2 )
print( "Distancia:" , distancia )
# Fin del programa
| false
|
14dada3e093e658d0125a68a3521358f1d7d1a0d
|
kapis20/IoTInternships
|
/GPS/GPS_four_bytes.py
| 1,494
| 4.125
| 4
|
from decimal import Decimal
"""
Works similarly to the three byte encoder in that it will only work if the point
is located within that GPS coordinate square of 53, -1. Note that this is a far
larger area than could be transmitted by the three byte version. The encoder
strips the gps coordinates (Ex. 53.342, -1.445 -> 0.342, 0.445) and splits them
into two bytes each. This is then sent to the decoder which will put together
the split bytes and assume that they lie within the coordinate square 53, -1.
"""
# create function that will strip the numbers
def numberStrip(number):
return float(Decimal(number) % 1)
def encodeGPS(latitude, longitude):
# strip the laitude and longitude coordinates and make them into 'short' types
# short type can be up to ~65000 so need to make sure numbers are within range
latStrip = round(abs(numberStrip(latitude))*1e5/2)
longStrip = round(abs(numberStrip(longitude))*1e5/2)
# create a list for the bytes to be stored in
byteList = []
# use bit methods to split values
byteList.append((latStrip & 0xFF00) >> 8)
byteList.append(latStrip & 0x00FF)
byteList.append((longStrip & 0xFF00) >> 8)
byteList.append(longStrip & 0x00FF)
byteList = bytes(byteList)
return byteList
def decodeGPS(byteList):
# reverse the actions of the decoder
latitude = 53 + ((byteList[0] << 8) + byteList[1])*2/1e5
longitude = -(1 + ((byteList[2] << 8) + byteList[3])*2/1e5)
return latitude, longitude
| true
|
7a66249816da377c1e4b76a361dcce543496ae65
|
RashmiVin/my-python-scripts
|
/Quiz.py
| 995
| 4.34375
| 4
|
#what would the code print:
def thing():
print('Hello')
print('There')
#what would the code print:
def func(x):
print(x)
func(10)
func(20)
#what would the code print:
def stuff():
print('Hello')
return
print('World')
stuff()
#what would the code print:
def greet(lang):
if lang == 'es':
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'
print(greet('fr'), 'Michael')
#Will the below code get executed? No
if x == 5 :
print('Is 5')
print('Is Still 5')
print('Third 5')
# what would the code print:
x = 0
if x < 2:
print('Small')
elif x < 10:
print('Medium')
else:
print('LARGE')
print('All done')
# what would the code print:
if x < 2:
print('Below 2')
elif x >= 2:
print('Two or more')
else:
print('Something else')
# what would the code print:
astr = 'Hello Bob'
istr = 0
try:
istr = int(astr)
except:
istr = -1
| true
|
708fd980e7acf93a457e282fd6f607ac61cea6cd
|
ksvtmb/python
|
/dz2/coin.py
| 621
| 4.15625
| 4
|
# подбрось монетку 100 раз и посчитай, сколько решек а сколько орлов
# переменные решек и орлов создать ты должен, падаван
reshka=0
orel=0
count=100
import random
while True:
guess=random.randint(0,1)
if guess==0:
reshka+=1
else:
orel+=1
# print (count)
count-=1
if count==0:
break
print("\tподкинув монетку 100 раз мы узнали:")
print("Решек выппало: ",reshka, "раз(а)")
print("Ну а Орлов выпало: ",orel, "раз(а)")
| false
|
8ad708f6ce4fc9fd48d76271f246a69685bd4024
|
ksvtmb/python
|
/annag.py
| 1,000
| 4.125
| 4
|
# игра в слова по анаграма
import random
# константа
WORDS=("питон","гадюка", "кобра","мамба")
# выбираем один элемент с кортежа рандомно
word=random.choice(WORDS)
# записываем корректное выбраное словов в отдельную переменную
correct=word
# пустая анаграма
jumble=""
# начинаем цикл
while word:
position=random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[(position+1):]
print("чувак отгадай загадку. вот тебе анаграма: ",jumble,"\nОтгадай исходное слово")
guess=input("давай вариант: ")
while guess!=correct and guess!="":
print("не угадали, трай эген")
guess=input("еще раз вариант: ")
if guess==correct:
print("bingo! ты угадал")
print("game over")
input("press any key")
| false
|
9cb4a5716496f51d2fe167c7431e4e12e3647bff
|
money1won/Read-Write
|
/Read_Write EX_1.py
| 591
| 4.375
| 4
|
# Brief showing of how a file reads, writes, and appends
file = open("test.txt","w")
file.write("Hello World")
file.write("This is our new text file")
file.write("New line")
file.write("This is our new text file")
file.close
# Reads the entire file
# file = open("test.txt", "r")
# print(file.read())
# Reads only the line selected
file = open("test.txt", "r")
print(file.readline())
file.close
# Will add onto the end of the file currently existing
file = open("test.txt","a")
file.write("END")
file.close()
file = open("test.txt", "r")
print(file.read())
| true
|
c2e1286123bab6e5e179d7f815ee62c763bf37fb
|
Jidnyesh/pypass
|
/pypass.py
| 1,237
| 4.3125
| 4
|
"""
This is a module to generate random password of different length for your project
download this or clone and then from pypass import randompasswordgenerator
"""
import random
#String module used to get all the upper and lower alphabet in ascii
import string
#Declaring strings used in password
special_symbols = "!@#$%^&*()_+{}|:<>?-=[]\;',./"
alphabets = string.ascii_letters
numbers = string.digits
def randompasswordgenerator():
#Taking inputs for information of password
n = int(input("Enter the length of password:"))
print("1:Alpha \n2:Alpha numeric \n3:Aplha symbol numeric")
choice = int(input("Choose the type of password:\n"))
#Making a empty list to store passwords
passw = []
#Setting value of str_list to combination according to choice
if choice == 1:
str_list = alphabets
elif choice == 2:
str_list = alphabets + numbers
elif choice == 3:
str_list = special_symbols + alphabets + numbers
for x in range(n):
rnd = random.choice(str_list)
passw.append(rnd)
password = "".join(passw)
print(password)
#Function call
if __name__=="__main__":
randompasswordgenerator()
| true
|
5c67c7ebcf9390eb22bd0a7d951ee3e8ceb0ba42
|
61a-su15-website/61a-su15-website.github.io
|
/slides/09.py
| 961
| 4.125
| 4
|
def sum(lst):
"""Add all the numbers in lst. Use iteration.
>>> sum([1, 3, 3, 7])
14
>>> sum([])
0
"""
"*** YOUR CODE HERE ***"
total = 0
for elem in lst:
total += elem
return total
def count(d, v):
"""Return the number of times v occurs as
a value in dictionary d.
>>> d = {'a': 4, 'b': 3, 'c': 4}
>>> count(d, 4)
2
>>> count(d, 3)
1
>>> count(d, 1)
0
"""
"*** YOUR CODE HERE ***"
total = 0
for val in d.values():
if val == v:
total += 1
return total
def most_frequent(lst):
"""Return the element in lst that occurs
the most number of times.
>>> lst = [1, 4, 2, 4]
>>> most_frequent(lst)
4
"""
"*** YOUR CODE HERE ***"
count = {}
for elem in lst:
if elem not in count:
count[elem] = 1
else:
count[elem] += 1
return max(count, key=lambda k: count[k])
| true
|
46abc1d446933a99fdab6df2a4c6b6b51495b625
|
jorgecontreras/algorithms
|
/binary_search_first_last_index.py
| 2,936
| 4.34375
| 4
|
# Given a sorted array that may have duplicate values,
# use binary search to find the first and last indexes of a given value.
# For example, if you have the array [0, 1, 2, 2, 3, 3, 3, 4, 5, 6]
# and the given value is 3, the answer will be [4, 6]
# (because the value 3 occurs first at index 4 and last at index 6 in the array).
#
# The expected complexity of the problem is 𝑂(𝑙𝑜𝑔(𝑛)) .
def binary_search(target, source, i=0):
mid = len(source) // 2
if target == source[mid]:
return mid + i
elif target < source[mid]:
source = source[:mid]
else:
i += mid
source = source[mid:]
if len(source) == 1 and source[0] != target:
return -1
return binary_search(target, source, i)
def first_and_last_index(arr, number):
"""
Given a sorted array that may have duplicate values, use binary
search to find the first and last indexes of a given value.
Args:
arr(list): Sorted array (or Python list) that may have duplicate values
number(int): Value to search for in the array
Returns:
a list containing the first and last indexes of the given value
"""
# find occurence of element in any position, return -1 if not found
start_index = binary_search(number, arr)
if start_index < 0:
return [-1, -1]
# with the element found, keep looking in adjacent indexes both sides
index = start_index
#find first ocurrence (go to left one by one)
while arr[index] == number:
if index == 0:
left = 0
break
elif arr[index-1] == number:
index -= 1
else:
left = index
break
#find last ocurrence (go to right one by one)
index = start_index
while arr[index] == number:
if index == len(arr) - 1:
right = index
break
elif arr[index + 1] == number:
index += 1
else:
right = index
break
return [left, right]
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
solution = test_case[2]
output = first_and_last_index(input_list, number)
if output == solution:
print("Pass")
else:
print("Fail")
# test case 1
input_list = [1]
number = 1
solution = [0, 0]
test_case_1 = [input_list, number, solution]
test_function(test_case_1)
# test case 2
input_list = [0, 1, 2, 3, 3, 3, 3, 4, 5, 6]
number = 3
solution = [3, 6]
test_case_2 = [input_list, number, solution]
test_function(test_case_2)
# test case 3
input_list = [0, 1, 2, 3, 4, 5]
number = 5
solution = [5, 5]
test_case_3 = [input_list, number, solution]
test_function(test_case_3)
# test case 4
input_list = [0, 1, 2, 3, 4, 5]
number = 6
solution = [-1, -1]
test_case_4 = [input_list, number, solution]
test_function(test_case_4)
| true
|
5af3949f1989ce98cb9c7e207eb5ff7453caa6c0
|
jasha64/jasha64
|
/Spring 2019/Python/5.31/带两颗星的形参.py
| 406
| 4.1875
| 4
|
#带两个星号参数的函数传入的参数存储为一个字典(dict),并且在
#调用时采取 key1 = value1, key2 = value2, ... 的形式。
#由于传入的参数个数不定,所以当与普通参数一同使用时,必须把带星号的参
#数放在最后。
#def demo(p):
def demo(**p):
for item in p.items():
print(item)
#demo({'x':1, 'y':2, 'z':3})
demo(x=1, y=2, z=3)
| false
|
a67ff64f4cf8dfc80b5fae725f50e9bbbd9f3c86
|
shahp7575/coding-with-friends
|
/Parth/LeetCode/Easy/rotate_array.py
| 889
| 4.15625
| 4
|
"""
Runtime: 104 ms
Memory: 33 MB
"""
from typing import List
class Solution:
"""
Problem Statement:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
"""
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if k > len(nums):
k = k % len(nums)
if k > 0:
nums[:] = eval(str(nums[-k:] + nums[:len(nums)-k]))
else:
return nums
return nums
if __name__ == "__main__":
result = Solution()
nums = [1]
k = 1
print(result.rotate(nums, k))
| true
|
78a3034cbd3d459797a10a91cd52cd244a12cc05
|
jinjuleekr/Python
|
/problem143.py
| 466
| 4.21875
| 4
|
#Roof
#Problem143
#Running the roof until the input is either even or odd
while True:
num_str = input("Enter the number : ")
if num_str.isnumeric():
num = int(num_str)
if num==0:
print("It's 0")
continue
elif num%2==1:
print("odd number")
break
else :
print("even number")
break
else:
print("It's not a number")
continue
| true
|
7a12958150d9f5d253e5f12de3feb7c879a21368
|
DanyT011/EjerciciosExercism
|
/raindrops/raindrops.py
| 753
| 4.21875
| 4
|
def convert(number):
number = (int(input("Type the Number: ")))
if (number % 3 == 0 and number % 5 == 0 and number % 7 ==0):
return print('PlingPlangPlong')
else:
if (number % 3 == 0 and number % 5 == 0):
return print("PlingPlang")
elif (number % 3 == 0 and number % 7 == 0):
return print("PlingPlong")
elif(number % 5 == 0 and number % 7 == 0):
return print("PlangPlong")
else:
if(number % 3 == 0):
return print("Pling")
elif(number % 5 == 0):
return print("Plang")
elif(number % 7 == 0):
return print("Plong")
else:
return print(number)
| false
|
279bb6837788f7a7cb77797940c35e9317891fbc
|
nagask/leetcode-1
|
/310 Minimum Height Trees/sol2.py
| 1,631
| 4.125
| 4
|
"""
Better approach (but similar).
A tree can have at most 2 nodes that minimize the height of the tree.
We keep an array of every node, with a set of edges representing the neighbours nodes.
We also keep a list of the current leaves, and we remove them from the tree, updating the leaf list.
We continue doing so until the size of the tree is 2 or smaller.
O(nodes) to build the graph, to identify the leaves. Then every node is added and removed from the leaf array at most once, so overall the time complexity is O(nodes)
Space: O(nodes + edges), to build the graph
"""
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
def build_graph(n, edges):
graph = [set() for _ in range(n)]
for start, end in edges:
graph[start].add(end)
graph[end].add(start)
return graph
def get_initial_leaves(graph):
leaves = []
for i in range(len(graph)):
if len(graph[i]) == 1:
leaves.append(i)
return leaves
if n <= 2:
return [i for i in range(n)]
graph = build_graph(n, edges)
leaves = get_initial_leaves(graph)
nodes = n
while nodes > 2:
nodes -= len(leaves)
new_leaves = []
for leaf in leaves:
neighbour = list(graph[leaf])[0]
graph[neighbour].remove(leaf)
if len(graph[neighbour]) == 1:
new_leaves.append(neighbour)
leaves = new_leaves
return leaves
| true
|
1d90053bbdce1a1c82312d77f0ee4f98e5fc3c2b
|
nagask/leetcode-1
|
/25 Reverse Nodes in k-Group/sol2.py
| 2,593
| 4.15625
| 4
|
"""
Reverse a linked list in groups of k nodes.
Before doing so, we traverse ahead of k nodes from the current point, to know wehre the next reverse will start.
The function `get_kth_ahead` returns the k-th node ahead of the current position (can be null) and a boolean indicating whether there are at list k nodes after the current position,
and therefore we must reverse. In this way, when we call `reverse`, we are sure we have at least k nodes, and the reverse function does not need to handle edge cases.
The reverse function returns the new head and the new tail of the portion of the list that has been reversed.
We need to keep track of the tail of the last portion that was reversed in the previous iteration, to connect the two pointers together and not to lose part of the list.
Another edge case is the first reversion, where we have to update the main head of the list. That's why we use the variable `is_head`.
Finally, we need to update the last reversed tail to point to the remaining part of the list (either null if k is multiple of the lenght of the list, or the first not-reversed node)
O(N) time, O(1) space
"""
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
def get_kth_ahead(current, k):
# returns a node and a boolean indicating whether there are k nodes after current
for i in range(k):
if i < k - 1 and not current.next:
return None, False
current = current.next
return current, True
def reverse(current, k):
prev = None
succ = None
tail = current
for _ in range(k):
succ = current.next
current.next = prev
prev = current
current = succ
return prev, tail
is_head = True
new_head = None
current = head
last_reversed_tail = None
must_reverse = True
while must_reverse and current:
k_th_ahead, must_reverse = get_kth_ahead(current, k)
if must_reverse:
reversed_head, reversed_tail = reverse(current, k)
if is_head:
is_head = False
new_head = reversed_head
if last_reversed_tail:
last_reversed_tail.next = reversed_head
last_reversed_tail = reversed_tail
current = k_th_ahead
if last_reversed_tail:
last_reversed_tail.next = current
return new_head
| true
|
5101c36f61e29a8015a67afacdb7c6927e0b3514
|
SwagLag/Perceptrons
|
/deliverables/P3/Activation.py
| 991
| 4.46875
| 4
|
# Activation classes. The idea is as follows;
# The classes should have attributes, but should ultimately be callable to be used in the Perceptrons, in order
# to return an output.
# To this end, make sure that implemented classes have an activate() function that only takes a int or float input
# and outputs a int or float.
from typing import Union
import math
class Step:
"""Step-based activation. If the sum of the input is above the treshold, the output is 1. Otherwise,
the output is 0."""
def __init__(self, treshold: Union[int, float] = 0):
self.treshold = treshold
def activate(self, input: Union[int, float]):
if input >= self.treshold:
return 1
else:
return 0
class Sigmoid:
"""Sigmoid-based activation. The output is defined by the sigmoid function."""
def __init__(self):
"""Creates the object."""
def activate(self, input: Union[int, float]):
return 1 / (1 + (math.e ** -input))
| true
|
01da994ca131afa3e8adcc1ff14e92ca5285f376
|
tanmaysharma015/Tanmay-task-1
|
/Task1_Tanmay.py
| 657
| 4.3125
| 4
|
matrix = []
interleaved_array = []
#input
no_of_arrays = int(input("Enter the number of arrays:")) #this will act as rows
length = int(input("Enter the length of a single array:")) #this will act as columns
print(" \n")
for i in range(no_of_arrays): # A for loop for row entries
a =[]
print("enter the values of array " + str(i+1) + ": ")
for j in range(length): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
#processing
for m in range(length):
for n in range(no_of_arrays):
interleaved_array.append(matrix[n][m])
#output
print(" \n\n\n\n")
print(interleaved_array)
| true
|
31f5fd00943b1cd8f750fec37958e190b6f2a041
|
aanzolaavila/MITx-6.00.1x
|
/Final/problem3.py
| 551
| 4.25
| 4
|
import string
def sum_digits(s):
""" assumes s a string
Returns an int that is the sum of all of the digits in s.
If there are no digits in s it raises a ValueError exception. """
assert isinstance(s, str), 'not a string'
found = False
sum = 0
for i in s:
if i in string.digits:
found = True
sum += int(i)
if found == False:
raise ValueError("input string does not contain any digit")
return sum
print(sum_digits("a;35d4"))
print(sum_digits("a;d"))
| true
|
6d251e9edeb2f9a67f9238f65c92c8161fe1e6cf
|
VivancoJose/Tarea_2
|
/Tarea_2/ejercicio2.py
| 318
| 4.21875
| 4
|
#Realiza un programa que lea un número impar por teclado. Si el usuario no introduce un número impar,
# debe repetise el proceso hasta que lo introduzca correctamente.
numero_1= 0
while numero_1 % 2 == 0:
numero_1 = int(input(" Ingrese un numero impar: \n") )
print("El numemro ue ha introducido es correcto")
| false
|
7621071381ddeb2d5c5fdbde64ed90d87aeb8f67
|
ebsbfish4/classes_lectures_videos_etc
|
/video_series/sentdex_machine_learning_with_pyhton/how_to_program_the_best_fit_slope.py
| 869
| 4.15625
| 4
|
'''
We know definition of line is y = mx + b.
So, first we will calculate for m.
Included next video in this file as well
'''
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
# plt.scatter(xs, ys)
# plt.show()
def best_fit_slope_and_intercept(xs, ys):
m = (((mean(xs) * mean(ys))-mean(xs*ys)) /
(mean(xs)**2 - mean(xs**2)))
b = mean(ys) - m * mean(xs)
return m, b
m, b = best_fit_slope_and_intercept(xs, ys)
regression_line = [(m*x)+b for x in xs]
'''
List comprehension, same as
for x in xs:
regression_line.append((m*x)+b)
'''
predict_x = 8
predict_y = m*predict_x + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y)
plt.plot(xs, regression_line)
plt.show()
| false
|
1ef2a328b5d3d4de6ab9a68a3c45d75959155ac3
|
alejandradean/digital_archiving
|
/filename_list_with_dirs.py
| 801
| 4.3125
| 4
|
import os
directory_path = input("Enter directory path: ")
# the below will create a file 'filenames.txt' in the same directory the script is saved in. Enter the full path in addition to the .txt filename to create the file elsewhere.
with open('filenames.txt', 'a') as file:
for root, dirs, files in os.walk(directory_path):
file.write('-- Directory: {} --'.format(root))
file.write('\n\n')
for filename in files:
file.write('{}'.format(filename))
file.write('\n')
file.write('\n')
file.close()
# the below code prints the output in the shell and uses old syntax
# for root, dirs, files in os.walk(directory_path):
# print('Directory: %s' % root)
# for filename in files:
# print('\t%s' % filename)
| true
|
a28a5240fb888c7686624e6186a5b3f77c5b4825
|
speed785/Python-Projects
|
/lab8.py
| 743
| 4.1875
| 4
|
#lab8 James Dumitru
#Using built in
number_1 = int(input("Enter a number: "))
number_2 = int(input("Enter a number: "))
number_3 = int(input("Enter a number: "))
number_4 = int(input("Enter a number: "))
number_5 = int(input("Enter a number: "))
number_6 = int(input("Enter a number: "))
num_list = []
num_list.append(number_1)
num_list.append(number_2)
num_list.append(number_3)
num_list.append(number_4)
num_list.append(number_5)
num_list.append(number_6)
#Sort in Inputted order
print("~~~~~~ Inputted Order ~~~~~~~~")
print(num_list)
#Sort in increasing order
print("~~~~~~ Increasing Order ~~~~~~")
num_list.sort()
print(num_list)
#Sort in decreasing order
print("~~~~~~ Decreasing Order ~~~~~~")
num_list.sort(reverse=True)
print(num_list)
| true
|
e0f95acb97a5f921722dacdf2773808421c80bc5
|
speed785/Python-Projects
|
/Temperature converter.py
| 1,289
| 4.28125
| 4
|
#Coded by : James Dumitru
# input #
y=int(input("Please Enter A Number "))
x=int(input("Please Enter A Second Number "))
# variables #
add=x+y
multi=x*y
div=x/y
sub=x-y
mod=x%y
# What is shown #
print("This is the addition for the two numbers=", add)
print("This is the multiplication for the two numbers=", multi)
print("This is the division for the two numbers=", div)
print("This is the subtraction for the two numbers=", sub)
print("This is the mod for the two numbers=", mod)
# input for Temperature Conversion #
Celsius=eval(input("Please Enter a temperature in Celsius you would like to convert: "))
Fahrenheit=eval(input("Please Enter a temperature in Farenheit you would like to convert: "))
# Math #
# (F - 32) * 5/9 = C #
# (C * 9/5) + 32 = F #
# What is shown #
#print("Fahrenheit Conversion = ", Fahrenheit)
#print("Celsius Conversion = ", Celsius)
#####
#Extra testing using the for loop
print("{0:10} {1:20} {2:20} {3:20}".format("Celsius", "Farenheit", "Values for F to C", "Values for C to F",))
i=0
for i in range(15):
# variables #
cel=round(((Fahrenheit - 32) * 5/9), 2)
far=round(((Celsius * 9/5) + 32), 2)
print("{0:<10.2f} {1:10.2f} {2:20.2f} {3:20.2f}".format(cel, far, Celsius, Fahrenheit))
Fahrenheit += 1
Celsius += 1
| true
|
b779cabe46235f12afb6d08104c2fe05e94f0c23
|
khaldi505/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/5-text_indentation.py
| 574
| 4.1875
| 4
|
#!/usr/bin/python3
""" function that add a text indentation. """
def text_indentation(text):
"""
text = str
"""
txt = ""
if not isinstance(text, str):
raise TypeError("text must be a string")
for y in range(len(text)):
if text[y] == " " and text[y - 1] in [".", "?", ":"]:
txt += ""
else:
txt += text[y]
for x in range(len(txt)):
if txt[x] in [".", "?", ":"]:
print(txt[x])
print()
else:
print(txt[x], end="")
| true
|
57c2fd29fa65988bcc3a38013f48ecb3a5c8aa02
|
mafudge/learn-python
|
/content/lessons/07/Now-You-Code/NYC4-Sentiment-v1.py
| 2,824
| 4.34375
| 4
|
'''
Now You Code 3: Sentiment 1.0
Let's write a basic sentiment analyzer in Python. Sentiment analysis is the
act of extracting mood from text. It has practical applications in analyzing
reactions in social media, product opinions, movie reviews and much more.
The 1.0 version of our sentiment analyzer will start with a string of
positive and negative words. For any input text and the sentiment score
will be calculated as follows:
for each word in our tokenized text
if word in positive_text then
increment seniment score
else if word in negative_text then
decrement sentiment score
So for example, if:
positive_text = "happy glad like"
negative_text = "angry mad hate"
input_text = "Amazon makes me like so angry and mad"
score = -1 [ +1 for like, -1 for angry, -1 for mad]
You want to write sentiment as a function:
Function: sentiment
Arguments: postive_text, negative_text, input_text
Returns: score (int)
Then write a main program that executes like this:
Sentiment Analyzer 1.0
Type 'quit' to exit.
Enter Text: i love a good book from amazon
2 positive.
Enter Text: i hate amazon their service makes me angry
-2 negative.
Enter Text: i love to hate amazon
0 neutral.
Enter Text: quit
NOTE: make up your own texts of positive and negative words.
Start out your program by writing your TODO list of steps
you'll need to solve the problem!
'''
# TODO: Write Todo list then beneath write your code
# 1. define our function sentiment
# a. Should take postive_text, negative_text, input_text
# b. Check each word in input_text against negative decrement 1
# c. Check each work in input_text against positive increment 1
# d. return score
# 2. define our list of positive_words
# 3. define our list of negative_words
# 4. Ask the user for input
# 5. Call our sentiment function
# 6. Print out the score
"""
sentiment:
Checks user input against positive and negative list of words
decrements score if negative
increments score if positive
returns score.
params:
positive_text list(strings)
negative_text list(strings)
input_text string
return: integer
"""
def sentiment(positive_text, negative_text, input_text):
score = 0
words = input_text.split()
for word in words:
if word in positive_text:
score = score + 1
if word in negative_text:
score = score - 1
return score
positive_list_words = ['happy', 'ist256', 'fun', 'python', 'great']
negative_list_words = ['school', 'sad', 'mad', 'bad', 'terrible']
user_input = input("Please enter a string")
result = sentiment(positive_list_words, negative_list_words, user_input)
result_text = 'neutral'
if result > 0:
result_text = 'positive'
elif result < 0:
result_text = 'negative'
print('%d %s' % (result, result_text))
| true
|
ac594af8db3882620707a74c6600e667f8d2b784
|
tayloradam1999/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/0-add_integer.py
| 627
| 4.34375
| 4
|
#!/usr/bin/python3
"""
add_integer - adds 2 integers
a - first integer for addition
b - second integer for addition
Return: sum of addition
"""
def add_integer(a, b=98):
"""This def adds two integers and returns the sum.
Float arguments are typecasted to ints before additon is performed.
Raises a TypeError if either a or b is a non-integer or non-float."""
if ((not isinstance(a, int) and not isinstance(a, float))):
raise TypeError("a must be an integer")
if ((not isinstance(b, int) and not isinstance(b, float))):
raise TypeError("b must be an integer")
return (int(a) + int(b))
| true
|
a88ee84f46356c83315bd3c0ce2e81d0328a8733
|
tayloradam1999/holbertonschool-higher_level_programming
|
/0x0A-python-inheritance/1-my_list.py
| 416
| 4.34375
| 4
|
#!/usr/bin/python3
"""
This module writes a class 'MyList' that inherits from 'list'
"""
class MyList(list):
"""Class that inherits from 'list'
includes a method that prints the list, but in ascending order"""
def print_sorted(self):
"""Prints the list in ascending order"""
sort_list = []
sort_list = self.copy()
sort_list.sort()
print("{}".format(sort_list))
| true
|
3277de75085d160a739f2ea059361152403de931
|
tayloradam1999/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/4-print_square.py
| 542
| 4.375
| 4
|
#!/usr/bin/python3
"""This module defines a square-printing function.
size: Height and width of the square."""
def print_square(size):
"""Defines a square-printing function.
Raises a TypeError if:
Size is not an integer
Raises a ValueError if:
Size is < 0"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
for x in range(size):
for y in range(size):
print("#", end="")
print()
| true
|
4afb5f6f85657bb8b2586792c1ffdb03cabba379
|
fitzystrikesagain/fullstack-nanodegree
|
/sql_and_data_modeling/psycopg-practice.py
| 1,382
| 4.34375
| 4
|
"""
Exercise 1
----------
Create a database in your Postgres server (using `createdb`)
In psycopg2 create a table and insert some records using methods for SQL string composition. Make sure to establish
a connection and close it at the end of interacting with your database. Inspect your table schema and data in psql.
(hint: use `SELECT *` `\\dt` and `\\d`)
"""
from utils.constants import get_conn
TABLE_NAME = "vehicles"
def main():
"""
Creates a vehicles table, inserts some values, then queries and prints the results
:return: None
"""
create_table = f"""
DROP TABLE IF EXISTS {TABLE_NAME};
CREATE TABLE IF NOT EXISTS {TABLE_NAME} (
year int,
make varchar,
model varchar,
mileage float
)
"""
insert_values = f"""
INSERT INTO {TABLE_NAME} VALUES
(1994, 'Ford', 'Pinto', 18),
(1997, 'Chevy', 'Malibu', 23),
(1990, 'Nissan', '300ZX', 16),
(2019, 'Nissan', 'Altima', 23)
"""
select_all = f"SELECT * FROM {TABLE_NAME}"
# Retriever cursor from the helper
conn, cur = get_conn()
# Create table and insert values
cur.execute(create_table)
cur.execute(insert_values)
# Select and display results, then close the cursor
cur.execute(select_all)
for row in cur.fetchall():
print(row)
cur.close()
if __name__ == "__main__":
main()
| true
|
6e89046c4bab8515317fa3b4de91502ae333e8d0
|
bj-mckay/atbswp
|
/Chapter 7/dateDetection.py
| 1,454
| 4.4375
| 4
|
#! python3
# dateDetection.py - detects dates in the DD/MM/YYY format
import re, sys
print('Enter a date DD/MM/YYYY.')
date = str(input())
#date = str('28/02/2001')
leapyear = None
dateRegex = re.compile(r'''(
([0][1-9]|[1|2][0-9]|[3][0|1]) # Day
\/ # slash
([0][0-9]|[1][0-2]) # Month
\/ # slash
([1|2][0-9][0-9][0-9]) # Year
)''', re.VERBOSE)
validaton = dateRegex.search(date)
if validaton is None:
print('This is an invalid date.')
sys.exit()
else:
day = int(validaton.group(2))
month = validaton.group(3)
year = int(validaton.group(4))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
leapyear = True
else:
leapyear = False
if month == '02':
if leapyear == True:
if int(day) < 30:
print('This is an valid February leapyear date!')
else:
if int(day) > 29:
print('This is an invalid February Date')
if leapyear != True:
if int(day) > 28:
print('This is an invalid February Date')
else:
print('This is a valid date.')
elif month in ['04', '06', '09', '11']:
if day > 30:
print('Invalid: This month only has 30 days')
else:
print('This is a valid date.')
elif month in ['01', '03', '05', '07', '08', '10', '12']:
print('This is a valid date.')
| false
|
4f170c0d111c2c5b2ffcdd62714c0e8613eadfe2
|
mariettas/SmartNinja_Project_smartninja_python2_homework
|
/fizzbuzz.py
| 320
| 4.21875
| 4
|
print("Hello, welcome to the fizzbuzz game!")
choice = int(input("Please, enter a number between 1 and 100: "))
for x in range(1, choice + 1):
if x % 3 == 0 and x % 5 == 0:
print("fizzbuzz")
elif x % 3 == 0:
print("fizz")
elif x % 5 == 0:
print("buzz")
else:
print(x)
| true
|
552dcfca3facace254db3e547a547f11271d2cc0
|
Vadum-cmd/lab5_12
|
/cats.py
| 1,867
| 4.125
| 4
|
"""
Module which contains classes Cat and Animal.
"""
class Animal:
"""
Class for describing animal's properties.
"""
def __init__(self, phylum, clas):
"""
Initializes an object of class Animal and sets its properties.
>>> animal1 = Animal("chordata", "mammalia")
>>> assert(animal1.phylum == "chordata")
>>> assert(animal1.clas == "mammalia")
>>> animal2 = Animal("chordata", "birds")
>>> assert(not (animal1 == animal2))
"""
self.phylum = phylum
self.clas = clas
def __str__(self):
"""
Represents this object in more-like-human language.
>>> animal1 = Animal("chordata", "mammalia")
>>> assert(str(animal1) == "<animal class is mammalia>")
"""
return f"<animal class is {self.clas}>"
class Cat(Animal):
"""
Class for describing cat's properties.
"""
def __init__(self, phylum, clas, genus):
"""
Initializes an object of class Cat and sets its properties.
>>> cat1 = Cat("chordata", "mammalia", "felis")
>>> assert(cat1.genus == "felis")
>>> assert(isinstance(cat1, Animal))
"""
super().__init__(phylum, clas)
self.genus = genus
def sound(self):
"""
Barsic(imagine it's your cat's name)! Say 'Meow'!
>>> cat1 = Cat("chordata", "mammalia", "felis")
>>> assert(cat1.sound() == "Meow")
"""
return "Meow"
def __str__(self):
"""
Represents this object in more-like-human language.
>>> cat1 = Cat("chordata", "mammalia", "felis")
>>> assert(str(cat1) == "<This felis animal class is mammalia>")
"""
return f"<This {self.genus} animal class is {self.clas}>"
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
84360bc297d4b20494db6d8782ed980cb9f55b9f
|
asimMahat/Advanced-python
|
/lists.py
| 1,365
| 4.21875
| 4
|
mylist = ['banana', 'apple','orange']
# print(mylist)
mylist2 = [5,'apple',True]
# print (mylist2)
item = mylist[-1]
# print (item)
for i in mylist:
print(i)
'''
if 'orange' in mylist:
print("yes")
else:
print("no")
'''
# print(len(mylist))
mylist.append("lemon")
print(mylist)
mylist.insert(1,'berry')
print(mylist)
#removing the data from the list
item=mylist.pop()
print (item) # gives which item is removed
print(mylist)
#removing the specific element from the list
item = mylist.remove("berry")
print(mylist)
#inserting specific item into the list
item = mylist.insert(2,"berry")
print(mylist)
#sorting the list in ascending order
mylist3 = [-1,-2,7,9,3,2,1]
items = sorted(mylist3)
print(items)
print("-----------------------------------------------")
#adding the two lists
first_list = [0] *5
print (first_list)
second_list = [2,3,1,7,9]
print (second_list)
third_list = first_list + second_list
print(third_list)
print("-----------------------------------------------")
#slicing
my_list =[1,2,3,4,5,6,7,8,9]
a = my_list[1:5]
print(a)
#lists, ordered , mutable , allows duplicate elements
lists_org = ["banana","cherry","apple"]
list_cpy = lists_org
list_cpy.append("lemon")
print(list_cpy)
print("----------------------------------------------")
#list comprehension
b = [1,2,3,4,5,6]
c = [i*i for i in b]
print(b)
print(c)
| true
|
517bf3dbd653001c3e70c1f222f00b695414d370
|
asimMahat/Advanced-python
|
/tuples.py
| 1,405
| 4.375
| 4
|
#in tuples the paranthesis are optional
mytuples = "Max",28,"Boston"
print (type(mytuples))
print(mytuples)
item = mytuples[2]
print (item)
#tuples are immutable
for i in mytuples:
print(i)
if "Max" in mytuples:
print ("yes")
else:
print ("no")
print("---------------------------------------")
my_tuple = ('a','p','p','l','e')
print(len(my_tuple))
print (my_tuple.count('p'))
#finding the index of item inside the tuples
print(my_tuple.index('p'))
#creating list out of tuples
my_list = list(my_tuple)
print(my_list)
print("----------------------------------------")
#creating tuples from list
my_tuple2 = tuple(my_list)
print(my_tuple2)
print ("-----------------------------------------")
#slicing with the tuples
d = 1,2,3,4,5,6,7,8,9,10
print(d)
e = d[2:6]
print (e)
#tuples unpacking
my_tuple3 = "Mike", 21, "NewYork"
name,age,city = my_tuple3
print(name)
print(age)
print(city)
#if there are too many values to unpack
my_tuple4 = 1,2,3,4,5,6
i1, *i2, i3 = 1,2,3,4,5,6
print(i1)
print(i2)
print(i3)
print("-----------------------------------------")
#comparing the size of lists and tuples
import sys
MY_list = [0,1,2,"hello",True]
MY_tuple = {0,1,2,"hello",True}
print(sys.getsizeof(MY_list),"bytes")
print(sys.getsizeof(MY_tuple),"bytes")
import timeit
print(timeit.timeit(stmt="[0,1,2,3,4,5]",number=1000000))
print(timeit.timeit(stmt="{0,1,2,3,4,5}",number=1000000))
| false
|
b9f9c0c94167c21e15632171149413eeeccc359a
|
Guessan/python01
|
/Assignments/Answer_3.3.py
| 971
| 4.34375
| 4
|
#Assignment: Write a program to prompt for a score between 0.0 and 1.0.
#If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
#Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
#< 0.6 F
#If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
#Please begin writing the program with the code below:
#score = raw_input("Enter Score: ")
score = raw_input("Enter your score: ")
#if type(raw_input) == string
#print "ERROR: Please enter a number score."
#score = raw_input("Enter your score: ")
elif score <= 0.9:
print "Your grade is an A"
elif score >= 0.8:
print "Your grade is a B"
elif score >= 0.7:
print "Your grade is a C"
elif score >= 0.6:
print "Your grade is a D"
elif score < 0.6:
print "Your grade is a F"
if score > 1:
print "Please enter a score within the range of 0.0 to 1.0"
raw_input("Enter your score: ")
| true
|
eadb4a678a48bef0d15acb3e9e2abfb6929c8f2c
|
archimedessena/Grokkingalgo
|
/selectionsort.py
| 1,626
| 4.3125
| 4
|
# selection sort algorithm
def findSmallest(arr):
smallest = arr[0] #Stores the smallest value
smallest_index = 0 #Stores the index of the smallest value
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
#Now you can use this function to write selection sort:
def selectionSort(arr): #Sorts an array
newArr = []
for i in range(len(arr)):
smallest = findSmallest(arr) # Finds the smallest element in the array, and adds it to the new array
newArr.append(arr.pop(smallest))
return newArr
our_list = [5, 3, 6, 2, 10, 23, 78, 89, 12, 4, 6, 89, 2, 57, 84, 35, 67, 56783, 78, 23, 56, 7889, 5, 6, 6, 8, 2, 4, 56, 7, 433, 7, 8, 9, 0, 7, 4, 3, 22, 4, 5, 66, 789, 2, 33, 44, 5, 5, 6778, 9, 900, 5667, 89, 123, 4556, 778, 990, 23]
#print(len(our_list))
#print(findSmallest(our_list))
#print(selectionSort(our_list))
def my_number(a):
smallest_number = a[0]
smallest_number_position = 0
for i in range(1, len(a)):
if a[i] < smallest_number:
smallest_number = a[i]
smallest_number_position = i
return smallest_number
def sort_me(a):
new = []
for i in range(len(a)):
smallest_number = my_number(a)
new.append(a.pop(smallest_number))
return new
our_list = [5, 3, 6, 2, 10, 23, 78, 89, 12, 4, 6, 89, 2, 57, 84, 35, 67, 56783, 78, 23, 56, 7889, 5, 6, 6, 8, 2, 4, 56, 7, 433, 7, 8, 9, 0, 7, 4, 3, 22, 4, 5, 66, 789, 2, 33, 44, 5, 5, 6778, 9, 900, 5667, 89, 123, 4556, 778, 990, 23]
print(my_number(our_list))
| true
|
9339fdaeb9f8271c05910ecc4b1ee7d0a71f7d30
|
bekahbooGH/Stacks-Queues
|
/queue.py
| 1,113
| 4.3125
| 4
|
class MyQueue:
def __init__(self):
"""Initialize your data structure here."""
self.stack1 = Stack()
self.stack2 = Stack()
def push(self, x: int) -> None:
"""Push element x to the back of queue."""
while not self.stack2.empty():
self.stack1.push(self.stack2.pop())
self.stack1.push(x)
def pop(self) -> int:
"""Removes the element from in front of queue and returns that element."""
self.peek()
return self.stack2.pop()
def pop2(self) -> int:
"""Removes the element from in front of queue and returns that element."""
while not self.stack1.empty():
self.stack2.push(self.stack1.pop())
return self.stack2.pop()
def peek(self) -> int:
"""Get the front element."""
while not self.stack1.empty():
self.stack2.push(self.stack1.pop())
return self.stack2.peek()
def empty(self) -> bool:
"""Returns whether the queue is empty."""
return self.stack1.empty() and self.stack2.empty()
my_queue = MyQueue()
| true
|
cde4e88e4c072257ca7e7489888a9a370b34c47c
|
sumit-kushwah/oops-in-python
|
/files/Exercise Files/Ch 4/immutable_finished.py
| 574
| 4.4375
| 4
|
# Python Object Oriented Programming by Joe Marini course example
# Creating immutable data classes
from dataclasses import dataclass
@dataclass(frozen=True) # "The "frozen" parameter makes the class immutable
class ImmutableClass:
value1: str = "Value 1"
value2: int = 0
def somefunc(self, newval):
self.value2 = newval
obj = ImmutableClass()
print(obj.value1)
# attempting to change the value of an immutable class throws an exception
obj.value1 = "Another value"
print(obj.value1)
# Frozen classes can't modify themselves either
obj.somefunc(20)
| true
|
fe480bc286b420be4109bbdbfa2ea9a2d7d97896
|
sumit-kushwah/oops-in-python
|
/files/Exercise Files/Ch 4/datadefault_start.py
| 471
| 4.3125
| 4
|
# Python Object Oriented Programming by Joe Marini course example
# implementing default values in data classes
from dataclasses import dataclass, field
import random
def price_func():
return float(random.randrange(20, 40))
@dataclass
class Book:
# you can define default values when attributes are declared
title: str = 'No title'
author: str = 'No author'
pages: int = 0
price: float = field(default_factory=price_func)
b1 = Book()
print(b1)
| true
|
a8c9d7355b63df85868b8c53198828b50d4098e8
|
Richiewong07/Python-Exercises
|
/python-udemy/Assessments_and_Challenges/Statements/listcomprehension.py
| 211
| 4.46875
| 4
|
# Use List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
print([word[0] for word in st.split()])
| true
|
ae16fb85dcd03542eb414a5ba6e1d707b9afc01f
|
Richiewong07/Python-Exercises
|
/python-assignments/python-part1/work_or_sleep_in.py
| 396
| 4.21875
| 4
|
# Prompt the user for a day of the week just like the previous problem.
# Except this time print "Go to work" if it's a work day and "Sleep in" if it's
# a weekend day.
input = int(input('What day is it? Enter (0-6): '))
def conv_day(day):
if day in range(1,6):
print('It is a weekday. Wake up and go to work')
else:
print("It's the weekend! Sleep in")
conv_day(input)
| true
|
56529869d13d6bc30f578675cc8bfb510f81a8c4
|
Richiewong07/Python-Exercises
|
/python-assignments/functions/plot_function.py
| 300
| 4.21875
| 4
|
# 2. y = x + 1
# Write a function f(x) that returns x + 1 and plot it for x values of -3 to 3 in increments of 1.
import matplotlib.pyplot as plot
def f(x):
return x + 1
xs = list(range(-3,4))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.axis([-3, 3, -2, 4])
plot.show()
| true
|
f1531778b5f766b5512a34b1c6d373ee5da71c39
|
Richiewong07/Python-Exercises
|
/callbox-assesment/exercise3.py
| 854
| 4.625
| 5
|
# Exercise 3:
# Write a function that identifies if an integer is a power of 2. The function should return a boolean. Explain why your function will work for any integer inputs that it receives.
# Examples:
# is_power_two(6) → false is_power_two(16) → true
input_num = 16
def is_power_two(num):
"""If a number is a power of 2 then the square root of the number must be a whole number. My function takes the square root of a input number and then checks if the square root of that number is an interger; return a boolean value."""
square_root = num ** 0.5
print(square_root.is_integer())
is_power_two(6)
is_power_two(16)
| true
|
57ec4253919ae789a437781b3c0d3bd92b073480
|
Richiewong07/Python-Exercises
|
/python-assignments/list/matrix_addition.py
| 654
| 4.1875
| 4
|
# 9. Matrix Addition
# Given two two-dimensional lists of numbers of the size 2x2 two dimensional list is represented as an list of lists:
#
# [ [2, -2],
# [5, 3] ]
# Calculate the result of adding the two matrices. The number in each position in the resulting matrix should be the sum of the numbers in the corresponding addend matrices. Example: to add
#
# 1 3
# 2 4
# and
#
# 5 2
# 1 0
# results in
#
# 6 5
# 3 4
m1 = [[1, 3], [2, 4]]
m2 = [[5, 2], [1, 0]]
def matrix_add(a, b):
for i in range(0, len(a)):
row = []
for j in range(0, len(a[0])):
row.append(a[i][j] + b[i][j])
print(row)
matrix_add(m1, m2)
| true
|
1cfee3a4f5f8af85c0f764ed9bacd4795df24ac6
|
Richiewong07/Python-Exercises
|
/numpy/slicing_stacking.py
| 503
| 4.28125
| 4
|
import numpy as np
a = np.array([6,7,8])
print(a)
# HOW TO SLICE ARRAY
print(a[0:2])
print(a[-1])
a = np.array([[6,7,8], [1,2,3], [9,3,2]])
print(a)
# ROW 1 COLUMN 2 --> 3
print(a[1,2])
# FROM 0 TO 2ND ROW, COLUMN 2 --> [8,3]
print(a[0:2,2])
# GIVES LAST ELEMENT
print(a[-1])
# GIVES LAST ELEMENT, ELEMENTS 0 AND 1
print(a[-1, 0:2])
# : GIVES ALL THE ROWS, COLUMNS 1 AND 2
print(a[:, 1:3])
# ITERATE THROUGH ROWS
for row in a:
print(row)
# FLATTEN LIST
for cell in a.flat:
print(cell)
| false
|
10d0346dabc7e4135ab9981d49f0df762694b43d
|
abhishekkulkarni24/Machine-Learning
|
/Numpy/operations_on_mobile_phone_prices.py
| 1,643
| 4.125
| 4
|
'''
Perform the following operations on an array of mobile phones prices 6999, 7500, 11999,
27899, 14999, 9999.
a. Create a 1d-array of mobile phones prices
b. Convert this array to float type
c. Append a new mobile having price of 13999 Rs. to this array
d. Reverse this array of mobile phones prices
e. Apply GST of 18% on mobile phones prices and update this array.
f. Sort the array in descending order of price
g. What is the average mobile phone price
h. What is the difference b/w maximum and minimum price
'''
import numpy as np
arr = np.array([6999, 7500, 11999,
27899, 14999, 9999]); #Create a 1d-array of mobile phones prices
print(arr)
arr = arr.astype(np.float); #Convert this array to float type
print(arr)
arr2 = np.append(arr , 13999) #Append a new mobile having price of 13999 Rs. to this array
print(arr2)
arr2 = arr2[::-1] #Reverse this array of mobile phones prices
print(arr2)
m = (arr2 != 0)
arr2[m] = arr2[m] - (arr2[m] * (18 /100)) #Apply GST of 18% on mobile phones prices and update this array.
print(arr2)
arr2 = np.sort(arr2)[::-1] #Sort the array in descending order of price
print(arr2)
print(np.average(arr2)) #What is the average mobile phone price
print(arr2.max() - arr2.min()) #What is the difference b/w maximum and minimum price
'''
Output
[ 6999 7500 11999 27899 14999 9999]
[ 6999. 7500. 11999. 27899. 14999. 9999.]
[ 6999. 7500. 11999. 27899. 14999. 9999. 13999.]
[13999. 9999. 14999. 27899. 11999. 7500. 6999.]
[11479.18 8199.18 12299.18 22877.18 9839.18 6150. 5739.18]
[22877.18 12299.18 11479.18 9839.18 8199.18 6150. 5739.18]
10940.439999999999
17138.0
'''
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.