blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0d68551843d403dfe1ba8f923220c70937532eb0 | paradoxal/3.-linkedlist | /linkedlist MALLI.py | 2,810 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:File: linkedlist.py
:Author: <Your email>
:Date: <The date>
"""
class LinkedList:
"""
A doubly linked list object class.
The implementation makes use of a `ListNode` class that is used to
store the references from each node to its predecessor and follower
and to the data object associated with the node.
Note: The position of a node can be defined with a value `n` which
equals the number of nodes between it and the head of the linked list.
In other words: The node that immediately follows the head guardian
node is at position 0, its follower at position 1, and so on.
"""
class ListNode:
"""
A doubly linked list node object class.
List nodes are ment to act as list element(/item) containers that
wrap the objects inserted into the linked list.
Attributes:
obj (object): Any object that need to be stored
follower (ListNode): The node that follows this (self) in the linked list
predecessor (ListNode): The node that precedes this (self) in the linked list
"""
def __init__(self, obj):
"""Initialize a list node object."""
self.obj = obj
self.follower = None
self.predecessor = None
def addAfter(self, node):
"""Adds node `node` as the follower."""
tmp = self.follower
self.follower = node
node.predecessor = self
node.follower = tmp
if tmp:
tmp.predecessor = node
def removeAfter(self):
"""Removes the follower."""
if self.follower:
self.follower = self.follower.follower
if self.follower:
self.follower.predecessor = self
def __init__(self):
"""Initialize the linked list."""
# Does this seem reasonable?
self.h = self.ListNode(None) # Left guardian (head)
self.z = self.ListNode(None) # Right guardian (tail)
self.h.addAfter(self.z)
def _get_at(self, n):
"""Return the node at position `n`."""
raise NotImplementedError('Fixme!')
def addFirst(self, obj):
"""Add the object `obj` as the first element."""
raise NotImplementedError('Fixme!')
def addLast(self, obj):
"""Add the object `obj` as the last element."""
raise NotImplementedError('Fixme!')
def addPosition(self, n, obj):
"""Insert the object `obj` as the `n`th element."""
raise NotImplementedError('Fixme!')
def removePosition(self, n):
"""Remove the object at the `n`th position."""
predecessor = self._get_at(n).predecessor
if predecessor:
predecessor.removeAfter()
def getPosition(self, n):
"""Return the object at the `n`th position."""
return self._get_at(n).obj
def getSize(self):
"""Return the number of objects in the list."""
raise NotImplementedError('Fixme!')
# EOF
| true |
81fe36735b80677a69cd5f1b229ba777cb0dcdf9 | santosh-srm/srm-pylearn | /28_max_of_three_numbers.py | 917 | 4.40625 | 4 | """28_max_of_three_numbers.py"""
print("----Finding max of 3 numbers----")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
if (num1 > num2):
if (num1 > num3):
print(f'The max number is {num1}')
else:
print(f'The max number is {num3}')
else:
if (num2 > num3):
print(f'The max number is {num2}')
else:
print(f'The max number is {num3}')
"""
Output
----Finding max of 3 numbers----
Enter the first number: 2
Enter the second number: 3
Enter the third number: 4
The max number is 4
PS C:\akademize\W01D01> & C:/Users/santosh/AppData/Local/Programs/Python/Python39/python.exe c:/akademize/W01D01/srm-pylearn/28_max_of_three_numbers.py
----Finding max of 3 numbers----
Enter the first number: 4
Enter the second number: 3
Enter the third number: 5
The max number is 5
""" | true |
485638e90767c3729c2e58115078a84fba15158a | santosh-srm/srm-pylearn | /W03D01/32_multiplicationtable.py | 708 | 4.3125 | 4 | """Print a multiplication table."""
def main():
"""Printing Multiplication Table"""
print_table(2)
print_table(7)
print_table(13)
def print_table(n):
"""Print nth Multiplication Table"""
print(f"Table {n}")
for i in range(1, 11):
print(f'{n} * {i} = {n*i}')
print("\n")
main()
""" Output
Table 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Table 7
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Table 13
13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130
"""
| false |
8a8b90655fc27a1434364c3581fdb48792f07658 | dlenwell/interview-prep-notes | /code-samples/python/inverting_trees/invert.py | 1,913 | 4.25 | 4 | """
Tree inversion:
"""
from tree import Node, Tree
from collections import deque
class InvertTree(Tree):
"""
InvertTree Tree class extends the base Tree class and just adds the invert
functions.
This class includes a recursive and an iterative version of the function.
"""
def invert_aux(self, node):
"""
invert tree
"""
# entry point
if node is None:
return(None)
# invert my children
node.left, node.right = \
self.invert_aux(node.right), self.invert_aux(node.left)
return(node)
def recursive_invert(self):
"""
invert tree
"""
self.invert_aux(self.root)
def invert_iterative(self):
"""
iterative function to invert the binary tree using a queue
"""
queue = deque()
queue.append(self.root)
while queue:
current = queue.popleft()
current.left, current.right = current.right, current.left
if current.left is not None:
queue.append(current.left)
if current.right is not None:
queue.append(current.right)
def main():
"""
main exercise run through...
"""
import random
tree = InvertTree()
unsorted_node_values = []
print('generating tree with 100 nodes with random values between 1 and 999')
# add 100 random values to the tree
for i in range(12):
value = random.randint(1,999)
unsorted_node_values.append(value)
tree.add(value)
print()
tree.print()
print()
print('Inverting tree with recursion:')
tree.recursive_invert()
print()
tree.print()
print()
print('Inverting tree with iterative style:')
tree.invert_iterative()
print()
tree.print()
print()
print()
if __name__ == "__main__":
main()
| true |
3110b65f4b971f4a2c2967f250e3a22afd73e8f0 | ajerit/python-projects | /sorting/binary.py | 451 | 4.15625 | 4 | #
# Adolfo Jeritson
# Binary search implementation
# 2016
#
# inputs: A: Array of elements
# x: Target element
# returns None if the element is not found
# the position in the array if the element is found
def binarySearch(A, x):
start = 0
end = len(A)
while start < end:
mid = end + (start-end) / 2
if A[mid] == x:
return mid
elif A[mid] < x:
start = mid + 1
else:
end = mid - 1
return start if A[start] == x else None
| true |
ea30d850e5f06ac21da9ef24a9f1e4d6cade3401 | Anupama-Regi/python_lab | /24-color1_not_in_color2.py | 235 | 4.1875 | 4 | print("Program that prints out all colors from color-list1 not contained in color-list2")
l=input("Enter list1 of colors : ")
l2=input("Enter list2 of colors : ")
a=l.split()
b=l2.split()
l3=[i for i in a if i not in b]
print(l3) | true |
674392160a40f2309d6542271f2325d25bd5abc8 | Anupama-Regi/python_lab | /28-remove_even_numbers.py | 315 | 4.21875 | 4 | print("*Program to create a list removing even numbers from a list of integers.*")
n=input("Enter the list of integers : ")
l=list(map(int,n.split()))
print("List of numbers : ",l)
#l2=[i for i in l if i%2!=0]
#print(l2)
for i in l:
if(i%2==0):
l.remove(i)
print("List after removing even numbers : ",l) | true |
7f902eb622852e3435c85d96ab00338b215a3f1e | Anupama-Regi/python_lab | /Cycle_3-python-Anupama_Regi/15-factorial_using_function.py | 209 | 4.4375 | 4 | print("Program to find factorial using function")
def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
print("Factorial is ",f)
n=int(input("Enter the number to find factorial : "))
factorial(n)
| true |
10c8ddc131128cc08d98033c80d062d4a09e1484 | inventionzhang/TensorFlowApplication | /tensorFlowApp/test/ReloadFunction2.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 定义在类的内部
class time:
# 构造函数
def __init__(self, hour=0, minutes=0, seconds=0):
self.hour = hour
self.minutes = minutes
self.seconds = seconds
# 函数的第一个参数是self,如果没有第二个参数,具体就用self.hour
def printTime(self, t):
print str(t.hour) + ":" + \
str(t.minutes) + ":" + \
str(t.seconds)
# 定义增加秒数的函数,并设置缺省参数为30
def increseconds(self, sec=30):
self.seconds += sec
if (self.seconds > 60):
self.seconds = self.seconds - 60
self.minutes += 1
if (self.minutes > 60):
self.minutes = self.minutes - 60
self.hour += 1
t1 = time()
t1.hour = 10
t1.minutes = 8
t1.seconds = 50
# 第一个参数self就是类的对象t1
t1.printTime(t1) # 10:8:50
t1.increseconds(20);
t1.printTime(t1) # 10:9:10
# 有的参数之所以可以省略,是因为函数中已经给出了缺省的参数
t1.increseconds();
t1.increseconds();
t1.printTime(t1) # 10:10:10
# 构造函数是任何类都有的特殊方法。当要创建一个类时,就调用构造函数。它的名字是: __init__ 。
t2 = time(10, 44, 45)
t2.printTime(t2)
print ("done!") | false |
54c1bc7e8f9d226fb869cd0da58026cfb5b08d24 | Jazmany23/Codigos | /ciclos.py | 917 | 4.125 | 4 | # ciclos
class Ciclos:
def __init__(self,num1=0,num2=1):
self.numero1=num1
def usoWhile(self):
# ciclo reetitivo que se ejecuta por verdadero y sale por falso
car = input("Ingrese vocal: ")
car = car.lower()
while car not in('a','e','i','o','u'):
car = input("Ingrese una vocal: ").lower()
print("""Felicidades el caracter ingresado : {}
es una vocal""".format(car))
# forma realizada hecha clase
# class Ciclo:
# def __init__(self, n1=0):
# self.numero = n1
# def usoWhilee(self):
# caracter = input("Ingrese una vocal")
# caracter = caracter.lower()
# while caracter not in ("a", "e", "i", "o", "u"):
# caracter = input("Ingrese una vocal").lower()
# print("El caracter ingresado {} si es una vocal".format(caracter))
ciclo1 = Ciclos()
ciclo1.usoWhile() | false |
3bf050700ee59e70d6fa1b5f41b4829a1b033df9 | horia94ro/python_fdm_26februarie | /day_2_part_1.py | 1,981 | 4.25 | 4 | print(7 >= 10)
print(10 != 12)
print(15 > 10)
a = 32
if (a >= 25 and a <= 30):
print("Number in the interval")
else:
if (a < 25):
print("Number is smaller than 25")
else:
print("Number is bigger than 30")
if a >= 25 and a <= 30:
print("Number in the interval")
elif a < 25:
print("Number is smaller than 25")
elif a > 30:
print("Number is bigger than 30")
else:
print("The default case")
season = input("Enter the value: ").lower()
if season == "summer":
print("HOT :D")
else:
if season == "winter":
print("COLD :(")
else:
if season == "fall" or season == "spring":
print("RAIN")
else:
print("Invalid value for season")
if season == "summer":
print("HOT :D")
elif season == "winter":
print("COLD :(")
elif season == "fall" or season == "spring":
print("RAIN :(")
else:
print("Invalid value")
hour = input("Enter the hour: ")
if hour.isnumeric():
hour = int(hour)
if hour > 0 and hour <= 23:
if hour >= 6 and hour < 12:
print("Good morning!")
elif hour >= 12 and hour < 17:
print("Good afternoon!")
elif hour >= 17 and hour <= 22:
print("Good evening!")
else:
print("You should be sleeping")
else:
print("Value is not on the clock!")
else:
print("The value is not correct.")
if 123:
print(":)")
if "non empty string":
print(":)")
a = 100
while a > 5:
print(a, end = "\t")
a -= 8
print("\ninstruction after the loop")
count = 15
while count: #count > 0
count -= 1
print(count, end = " ")
if count == 10:
print("Execution of loop will now stop")
break #Break will stop the whole while loop, not just the current iteration
print("Instruction after the loop")
count = 10
while count:
if count == 5:
count -= 1
continue
print(count, end=" ")
count -= 1
| true |
ac3ef1b204dc2e5be36f08d323737db025865c55 | Woodforfood/learn_how_to_code | /Codewars/7kyu/Find_the_capitals.py | 260 | 4.125 | 4 | # Write a function that takes a single string (word) as argument.
# The function must return an ordered list containing the indexes of all capital letters in the string.
def capitals(word):
return [i for i, letter in enumerate(word) if letter.isupper()]
| true |
7a63e23ebafcc8275fa1307cfa41aa79050538ba | aslishemesh/Exercises | /exercise1.py | 692 | 4.125 | 4 | # Exercise1 - training.
def check_div_even(num, check):
if num % check == 0:
return True
else:
return False
num = input("Please enter a number: ")
if check_div_even(num, 4):
print "The number %d can be divided by 4" % num
elif check_div_even(num, 2):
print "The number %d is an even number but not a multiple of 4" % num
else:
print "The number %d is an odd number and therefor cannot be divided by 2 or 4" % num
check = input("please enter a number to check (as a divider): ")
if check_div_even(num, check):
print "The number %d can be divided by %d" % (num, check)
else:
print "The number %d cannot be divided by %d" % (num, check) | true |
5db0c8336d976269440ab89746298616c314654a | DDinCA/Byte-of-Python | /ds_using_tuple.py | 973 | 4.25 | 4 | #推荐总是使用括号来指明元组的开始和结束
#尽管括号只是一个可选选项
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
#把zoo作为一个整体带入了new zoo,所以new zoo一共只有三个个体
print('Number of cages in the new zoo is', len(new_zoo))
#这句其实就是计算new zoo里的个体数量
print('All animals in new zoo are', new_zoo)
#注意打印出的zoo是包括在括号里的
print('Animals brought from old zoo are', new_zoo[2])
#Python从0开始计数
print('Lase animal brought from old zoo is', new_zoo[2][2])
#new zoo【2】【2】,第一个【2】表示是new zoo中的第三个,第二个【2】表示new zoo中的第三个里的第三个
#看样子指定个数可以叠加
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
#减去new zoo中最后那个zoo整体,同时加上zoo的数量
| false |
9f1157b501791c4cac209b2ebacefaf0c04da0aa | benfield97/info-validator | /info_validator.py | 1,041 | 4.1875 | 4 | import pyinputplus as pyip
import datetime
import re
while True:
name = pyip.inputStr("What is your name? ")
if all(x.isalpha() or x.isspace() for x in name):
name_len = name.split()
if len(name_len) < 2:
print("Please enter both a first and last name")
continue
else:
break
else:
print("Name Invalid: Please only use letters")
continue
birthday = pyip.inputDate(prompt="Please enter your date of birth (example: 4 Jan 2001) ", formats=['%d %b %Y'])
# will need to check address with a regex expression
while True:
pattern = re.compile(r'\d+\s[A-z]+\s[A-z]+,\s(VIC|NSW|TAS|ACT|NT|SA|WA)', re.IGNORECASE)
address = input('Enter you address (Example: 4 Example St, VIC) ')
result = pattern.search(address)
if result:
break
else:
print('Address Invalid')
goals = input("What are your goals? ")
print(f"Name: {name}")
print(f"Birthday: {birthday}")
print(f"Address: {address}")
print(f"Goals: {goals}")
| true |
7e2a2ca00bbaac892cd350564e296d9fc06b3b76 | Xuezhi94/learning-and-exercise | /.vscode/数据结构的Python实现/02.数组结构/02.09.左下三角矩阵.py | 924 | 4.125 | 4 | #设计一个Python程序,将左下三角矩阵压缩为一维数组
global arr_size #矩阵维数大小
arr_size = 5
#一维数组的数组声明
num = int(arr_size * (arr_size + 1) / 2)
b = [None] * num
def get_value(i, j):
index = int(i * (i + 1) / 2 + j)
return b[index]
#下三角矩阵的内容
a = [[76, 0, 0, 0, 0], [54, 51, 0, 0, 0], [23, 8, 26, 0, 0],
[43, 35, 28, 18, 0], [12, 9, 14, 35, 46]]
print('=' * 40)
print('下三角矩阵为:')
for i in range(arr_size):
for j in range(arr_size):
print('%d' % a[i][j], end='\t')
print()
#将下三角矩阵压缩为一维数组
index = 0
for i in range(arr_size):
for j in range(i + 1):
b[index] = a[i][j]
index += 1
print('=' * 40)
print('以一维数组的方式表示为:')
print('[', end='')
for i in range(arr_size):
for j in range(i + 1):
print('%d' % get_value(i,j), end=' ')
print(']')
| false |
a4e828ffddc57348328a53dae0208e7be7044902 | nerdycheetah/lessons | /recursion_practice.py | 339 | 4.28125 | 4 | '''
Recursion Practice 10/17/2020
Example: Let's make a function that takes in a number and recursively adds to the total until the number reaches 1
'''
def recursive_total(n:int) -> int:
if n == 1:
return n
else:
print(f'n is currently: {n}')
return recursive_total(n - 1) + n
print(recursive_total(10)) | true |
edcab377fe47ccda40631e5c4a906446972c0ca3 | nicowjy/practice | /Leetcode/101对称二叉树.py | 753 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 对称二叉树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(root1, root2):
if not root1 and not root2:
return True
if (not root1 and root2) or (not root2 and root1):
return False
if root1.val != root2.val:
return False
return helper(root1.left, root2.right) and helper(root1.right, root2.left)
return helper(root, root)
| true |
1daf2db78044c8a1fcd44d918f5156a06ea9c75d | KartikKannapur/Algorithms | /00_Code/01_LeetCode/559_MaximumDepthofN-aryTree.py | 1,385 | 4.25 | 4 | """
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
"""
Method 1: Recursion
"""
# if not root:
# return 0
# if not root.children:
# return 1
# return max(self.maxDepth(node) for node in root.children) + 1
"""
Method 2: BFS
"""
if not root:
return 0
if not root.children:
return 1
max_depth = 0
queue = [root, 'X']
while queue:
node = queue.pop(0)
if node == 'X':
max_depth += 1
if queue:
queue.append('X')
elif node and node.children:
for ele in node.children:
queue.append(ele)
# print([ele.val if ele != 'X' else ele for ele in queue])
return max_depth
| true |
b4f0f0a2746fe03ceebd1007794f815f4d5c36a1 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/557_ReverseWordsinaStringIII.py | 704 | 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"
# #Note: In the string, each word is separated by single space and
# #there will not be any extra space in the string.
# #Your runtime beats 91.64 % of python submissions.
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# #Method 1
return " ".join([var_word[::-1] for var_word in s.split(" ")])
# #Method 2
return ' '.join(s.split()[::-1])[::-1] | true |
2f883b3bd4645908e4b77ed0ae0669be10e283be | KartikKannapur/Algorithms | /00_Code/01_LeetCode/876_MiddleoftheLinkedList.py | 1,440 | 4.1875 | 4 | """
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
"""
Method 1: Traverse with slowPtr and fastPtr
* Assign slowPtr and fastPtr to head
* Update the slowPtr by 1 and the fastPtr by 2
* When the fastPtr reaches the end, the slowPtr
should have reached the middle of the Linked List.
Your runtime beats 70.93 % of python3 submissions.
"""
slowPtr = fastPtr = head
while fastPtr and fastPtr.next:
slowPtr = slowPtr.next
fastPtr = fastPtr.next.next
return slowPtr | true |
e9a1f7f92c7d888ab70fe09ca91e45d4bda6d162 | KartikKannapur/Algorithms | /00_Code/02_HackerRank/Dynamic_Programming/Fibonacci_Modified.py | 507 | 4.25 | 4 | """
https://www.hackerrank.com/challenges/fibonacci-modified/problem
"""
# !/bin/python3
import sys
def fibonacciModified(t1, t2, n):
# Complete this function
memo = [0] * (n + 1)
memo[0] = t1
memo[1] = t2
for i in range(2, n + 1):
memo[i] = memo[i - 2] + (memo[i - 1] ** 2)
return memo[n - 1]
if __name__ == "__main__":
t1, t2, n = input().strip().split(' ')
t1, t2, n = [int(t1), int(t2), int(n)]
result = fibonacciModified(t1, t2, n)
print(result)
| false |
7b60b68b7fb1f6e0f71f016fee6c1a5fa25289a3 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/239_SlidingWindowMaximum.py | 1,155 | 4.28125 | 4 | """
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
"""
class Solution():
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
"""
Method 1: O(nk)
Your runtime beats 19.88 % of python submissions.
"""
if nums:
return [max(nums[i:i + k]) for i in range(0, len(nums) - k + 1)]
return []
| true |
cd1d5ae088fc786391b2a0ff3c27dd874420d13f | KartikKannapur/Algorithms | /00_Code/01_LeetCode/332_ReconstructItinerary.py | 1,832 | 4.5625 | 5 | """
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
"""
class Solution:
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
"""
Reference: Discussion Forum
"""
d = {}
for ticket in tickets:
if ticket[0] not in d:
d[ticket[0]] = [ticket[1]]
else:
d[ticket[0]].append(ticket[1])
for ticket in d:
d[ticket].sort()
res = ['JFK']
end = []
while d:
if res[-1] not in d:
end.append(res[-1])
res.pop()
continue
fr, to = res[-1], d[res[-1]].pop(0)
res.append(to)
if len(d[fr]) == 0:
d.pop(fr)
if end:
res += end[::-1]
return res | true |
0a1b65a184da3df85610fbe3760ae972c2834db1 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/883_ProjectionAreaof3DShapes.py | 2,987 | 4.5 | 4 | """
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.
Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.
Example 1:
Input: [[2]]
Output: 5
Example 2:
Input: [[1,2],[3,4]]
Output: 17
Explanation:
Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
Example 3:
Input: [[1,0],[0,2]]
Output: 8
Example 4:
Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 14
Example 5:
Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 21
Note:
1 <= grid.length = grid[0].length <= 50
0 <= grid[i][j] <= 50
"""
class Solution(object):
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
"""
Algorithm:
From the top, the shadow made by the shape will be 1 square for each non-zero value.
From the side, the shadow made by the shape will be the largest value for each row in the grid.
From the front, the shadow made by the shape will be the largest value for each column in the grid.
---------------------------------------------------------------
The first iteration of my solution was O(n^2) + O(n^2) + O(n^2)
# #Checking for non-zero values
var_x = sum([1 for ele in grid for sub_ele in ele if sub_ele])
# #Checking for values in each column
var_y = 0
for index in range(len(grid)):
var_y += max([grid[ele][index] for ele in range(len(grid))])
# #Checking for values in each row
var_z = sum([max(ele) for ele in grid])
return var_x+var_y+var_z
---------------------------------------------------------------
---------------------------------------------------------------
Can we do this with one pass?
Code below
Time complexity: O(n^2)
Space complexity: O(1)
---------------------------------------------------------------
Your runtime beats 100.00 % of python submissions.
"""
res = 0
for i in range(len(grid)):
max_row_wise = 0
max_col_wise = 0
for j in range(len(grid)):
# #Check for non-zero values for the
# #view from the top
if grid[i][j]:
res += 1
# #Find the maximum row_wise and col_wise
# #acorss all the lists in the list of lists
max_row_wise = max(max_row_wise, grid[i][j])
max_col_wise = max(max_col_wise, grid[j][i])
res += (max_row_wise + max_col_wise)
return res
| true |
24ea31762444a62ad6d997c484bf624da5cdd2a5 | KartikKannapur/Algorithms | /02_Coursera_Algorithmic_Toolbox/Week_01_MaximumPairwiseProduct.py | 991 | 4.1875 | 4 | # Uses python3
__author__ = "Kartik Kannapur"
# #Import Libraries
import sys
# #Algorithm:
# #Essentially we need to pick the 2 largest elements from the array
# #Method 1: Sort the array and select the two largest elements - Very expensive
# #Method 2: Scan the entire array twice by maintaining two indexes - Max1 and Max 2 -
# #Can this be reduced to one operation?
# #Method 3: Scan the array once, keeping a track of the largest element and the second largest
# #while looping through the array itself.
arr_len = int(sys.stdin.readline())
arr_vals = sys.stdin.readline()
arr = [int(elem) for elem in arr_vals.split()]
max_one = arr[0]
max_two = arr[0]
# #Linear Search
if len(arr) == 2:
max_one = arr[0]
max_two = arr[1]
if len(arr) > 2:
for element in arr:
if element >= max_one:
max_two = max_one
max_one = element
if (element > max_two) and (element < max_one):
max_two = element
# print(max_one, max_two, "Product:", (max_one*max_two))
print((max_one*max_two))
| true |
950e019702f534105369ef8d70380546c910e1dc | testmywork77/WorkspaceAbhi | /Year 8/Casting.py | 812 | 4.28125 | 4 | name = "Bruce"
age = "42"
height = 1.86
highscore = 128
# For this activity you will need to use casting as appropriate.
# Using the data stored in the above variables:
# 1. Use concatenation to output the sentence - "Bruce is 1.86m tall."
print(name + " is " + str(1.86) + "m tall.")
# 2. Use concatenation to output the sentence - "Bruce is 42 years old."
print(name + " is " + age + " years old.")
# 3. Use concatenation to output the sentence - "Bruce has a high score of 128."
print(name + " has a highscore of " + str(128) + ".")
# 4. Create a new variable called half _age and store in it the result of 42/2 as an integer
half_age = int(42/2)
print("half_age: " + str(half_age))
# 5. Use concatenation to output the sentence - "Half Bruce's age is 21."
print("Half " + name + "'s age is " + str(half_age)) | true |
bd3d80133d7780eaacc843d4f7f9a144a6a56802 | testmywork77/WorkspaceAbhi | /Year 8/Concatenation_Practice.py | 1,042 | 4.34375 | 4 | name = "Abhinav"
age = "11"
fav_sport = "Cricket"
fav_colour = "red"
fav_animal = "lion"
# Create the following sentences by using concatenation
# Example: A sentence that says who he is and how old he is
print("My name is " + name + " and I am " + age + " ,I like to play " + fav_sport)
# NOTE: Don't forget about spaces.
# 1. Write a sentence below that includes the variables name and fav_sport.
# 2. Write a sentence below that includes the variables fav_colour and fav_animal.
# 3. Write a sentence below that includes the variables age and fav_sport.
# 4. Write a sentence below that includes all the variables.
print("My name is " + name + " and my favorate sport is " + fav_sport)
print("My favorate colour is " + fav_colour + " and my favorate animal is a " + fav_animal)
print("I am " + age + " years old. My favorate sport is " + fav_sport)
print ("My name is " + name + " I am " + age + " years old. My favorate sport is " + fav_sport + " My favorate colour is " + fav_colour + " and my favorate animal is a " + fav_animal) | true |
d1c7cadba59a9c79cf30df4167483821263c15e5 | krishnaja625/CSPP-1-assignments | /m6/p3/digit_product.py | 416 | 4.125 | 4 | '''
Given a number int_input, find the product of all the digits
example:
input: 123
output: 6
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
N3 = int(input())
N2 = N3
N = abs(N3)
S = 0
K = 0
if N > 0:
S = 1
while N > 0:
N2 = N%10
S = S*N2
N = N//10
if N3 >= 0:
print(S)
else:
K = -1*S
print(K)
if __name__ == "__main__":
main()
| true |
065d5fda40b2c6f28f7736e946076f3b3d709f27 | Santoshi321/PythonPractice | /ListExcercise.txt | 1,866 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 15:06:30 2019
@author: sgandham
"""
abcd = ['nintendo','Spain', 1, 2, 3]
print(abcd)
# Ex1 - Select the third element of the list and print it
abcd[2]
# Ex2 - Type a nested list with the follwing list elements inside list abcd mentioned above and print it
newlist = [54,76]
abcd.append(newlist)
print (abcd)
# Ex3 - Print the 1 and the 4 position element in the following list
nestedlist = ["shail", [11,8, 4, 6], ['toronto'],abcd, "abcd"]
print(nestedlist[1])
print(nestedlist[4])
# Ex4 - add the following 2 lists and create list3 and print - remove string items too
list1= [10, 20, 'company', 40, 50, 100]
list2 = [100, 200, 300, 'orange', 400, 500,1000]
del list1[2]
print(list1)
del list2[3]
list3=list1+list2
print(list3)
# Ex 5 - print the lenght of the list3
print(len(list3))
# Ex 6 Add 320 to list 1 and print
list1.append(320)
print(list1)
#list1+320
#Ex 7 - Add parts of list1 & 2 by tking first 4 elements from list1 and last 2 elements from list2
newlist=list1[:5] + list2[5:]
print(newlist)
#ex 8 check if 99 is in list 1
99 in list1
#ex 9 check if 99 is not in list 1
99 not in list1
# concatenation (+) and replication (*) operators
#ex 10 - CONCATENANTE list 1 and ['cool', 1990]
list1+['cool',1990]
# Ex 11 - triplicate the list 1
list1*3
# ex 12 - find min & max of list2
max(list2)
min(list2)
# append & del
# Ex 13 append 'training' to list 1
list1.append('training')
list1.pop()
# Ex 14 delete 2nd position element from list 2
del list2[1]
# Ex 15 - iterate over list1 and print all elements by adding 10 to each element
# for x in list1:
list1= [10, 65,20, 30,93, 40, 50, 100]
for x in list1:
print(x+10)
#Ex 16 sorting
#sort list1 by ascending order
list1.sort()
#sort list1 by reverse order
list1.sort(reverse=True)
| true |
9996f4b93c4f91733742a6793da400f6b3bab637 | rebecca16/CYPAbigailAD | /funcion_print_el_que_si_es_xd.py | 750 | 4.125 | 4 | # print tiene 4 formas de uso
"""
1.- con comas
2.- con signo '+'
3.- con la funcion format ()
4.- Es con una variante de format ()
"""
# Con comas
#un espacio y haciendo casting de tipo
edad = 10
nombre = "Juan"
estatura = 1.67
print (edad , estatura , nombre )
# con '+' hace lo mismo pero no realiza el casting automático
# no agrega espacio, todo va a aparecer junto
print (str(edad) + str(estatura) + nombre )
# funcion format ()
print("nombre: {} edad: {} ".format(nombre, edad, estatura))
# la la 4.- es con una variante de format() simplificada
print(f"nombre: \"{nombre}\" \nedad:\t{edad} ")
# print y el argumento end
print("Solo hay diez tipos de personas, las que saben binario y las que no",end="------ ")
print("Otra linea")
| false |
3630cc5aeda264cc010df9809a3ef48d809b9cb3 | myNameArnav/dsa-visualizer | /public/codes/que/que.py | 1,771 | 4.25 | 4 | # Python3 program for array implementation of queue
INT_MIN = -32768
# Class Queue to represent a queue
class Queue:
# __init__ function
def __init__(self, capacity):
self.front = self.size = 0
self.rear = capacity - 1
self.array = [None]*capacity
self.capacity = capacity
# Queue is full when size becomes
# equal to the capacity
def isFull(self):
return self.size == self.capacity
# Queue is empty when size is 0
def isEmpty(self):
return self.size == 0
# Function to add an item to the queue.
# It changes rear and size
def enqueue(self, item):
if self.isFull():
return
self.rear = (self.rear + 1) % (self.capacity)
self.array[self.rear] = item
self.size += 1
print(item, "enqueued to queue")
# Function to remove an item from queue.
# It changes front and size
def dequeue(self):
if self.isEmpty():
return INT_MIN
print(self.array[self.front], "dequeued from queue")
self.front = (self.front + 1) % (self.capacity)
self.size -= 1
# Function to get front of queue
def qfront(self):
if self.isEmpty():
return INT_MIN
return self.array[self.front]
# Function to get rear of queue
def qrear(self):
if self.isEmpty():
return INT_MIN
return self.array[self.rear]
# Driver Code
queue = Queue(1000)
queue.enqueue(10)
queue.enqueue(100)
queue.enqueue(-1)
queue.dequeue()
print("Front item is", queue.qfront())
print("Rear item is", queue.qrear())
# Output:
# 10 enqueued to queue
# 100 enqueued to queue
# -1 enqueued to queue
# 10 dequeued from queue
# Front item is 100
# Rear item is -1
| true |
ed57a1ae2c3abd176cf440c00857b411899dd32e | myNameArnav/dsa-visualizer | /public/codes/dfs/dfs.py | 1,868 | 4.28125 | 4 | # Python3 program to implement DFS
# This function adds an edge to the graph.
# It is an undirected graph. So edges
# are added for both the nodes.
def addEdge(g, u, v):
g[u].append(v)
g[v].append(u)
# This function does the Depth First Search
def DFS_Visit(g, s):
# Colour is gray as it is visited partially now
colour[s] = "gray"
global time
time += 1
d[s] = time
print(s, end=" ")
# This loop traverses all the child nodes of u
i = 0
while i < len(g[s]):
# If the colour is white then
# the said node is not traversed.
if (colour[g[s][i]] == "white"):
p[g[s][i]] = s
# Exploring deeper
DFS_Visit(g, g[s][i])
i += 1
time += 1
f[s] = time
# Now the node u is completely traversed
# and colour is changed to black.
colour[s] = "black"
def DFS(g, n):
# Initially all nodes are not traversed.
# Therefore, the colour is white.
# global because the variables in the parent scope needs to be used here
global colour, p, d, f, time
colour = ["white"] * n
p = [-1] * n
d = [0] * n
f = [0] * n
time = 0
# Calling DFS_Visit() for all
# white vertices
print("DFS Order is : ", end="")
for i in range(n):
if (colour[i] == "white"):
DFS_Visit(g, i)
# Driver Code
# Graph with 11 nodes and 11 edges.
n = 11
# Declaring the vectors to store color,predecessor,
# and time stamps d and f
colour = [None] * n
p = [None] * n
d = [None] * n
f = [None] * n
time = 0
# The Graph vector
g = [[] for i in range(n)]
addEdge(g, 0, 1)
addEdge(g, 1, 2)
addEdge(g, 2, 3)
addEdge(g, 1, 4)
addEdge(g, 4, 5)
addEdge(g, 4, 6)
addEdge(g, 4, 7)
addEdge(g, 6, 9)
addEdge(g, 7, 8)
addEdge(g, 7, 9)
addEdge(g, 8, 10)
DFS(g, n)
# Output:
# DFS Order is : 0 1 2 3 4 5 6 9 7 8 10
| true |
d78d4b827bc6013444e4db630cd1261773a0bea8 | Bcdirito/django_udemy_notes | /back_end_notes/python/level_two/object_oriented_notes/oop_part_two.py | 791 | 4.53125 | 5 | # Example
class Dog():
# Class Object Attributes
# Always go up top
species = "Mammal"
# initializing with attributes
def __init__(self, breed, name):
self.breed = breed
self.name = name
# can be done without mass assignment
my_dog = Dog("German Shepherd", "Louis")
# can be done with mass assignment
other_dog = Dog(breed = "Huskie", name="Hughie")
print(my_dog.breed, my_dog.species)
print(other_dog.name)
# Example 2
class Circle():
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
def area(self):
return Circle.pi * self.radius**2
def set_radius(self, new_r):
self.radius = new_r
default_circle = Circle()
print(default_circle.radius)
my_circle = Circle(3)
print(my_circle.area()) | true |
f4ddf222cd4c3d87ffee555eb23937de49298016 | AshurMotlagh/CECS-174 | /Lab 3.13.py | 223 | 4.375 | 4 | ##
# Print the first 3 letters of a string, followed by ..., followed by the last 3 letters of a string.
##
word = input("Enter a word with longer than 8 letters: ")
print("The new word is", word[0:3], "...", word[-3:]) | true |
5b52810c905e0213d4e30a36931640fe503e8f09 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Lists_Advanced_Exercise/01_Which_Are_In.py | 265 | 4.15625 | 4 | first_list = input().split(", ")
second_list = input().split(", ")
result_list =[]
for item in first_list:
for item2 in second_list:
if item in item2:
if item not in result_list:
result_list.append(item)
print(result_list) | true |
fb2a40e552b6bcddefcd8693718848ad87407c26 | ashishihota/learning-Algorithms | /linked_list/linked_list_book.py | 1,123 | 4.15625 | 4 | class node(object):
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def has_next(self):
return self.next != None
class linkedlist(object):
def __init__(self):
self.head = None
def insert_at_begin(self,data):
new_node = node(data)
if self.head == 0:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def insert(self,data):
new_node = node(data)
current = self.head
while current.get_next() != None:
current = current.get_next()
current.set_next(new_node)
def printll(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
new = linkedlist()
new.insert_at_begin('10')
new.insert_at_begin('10')
new.insert_at_begin('10')
new.insert('20')
new.printll()
| false |
0b246053cbffe4fa6a52f10f5a0982052cdebf4f | azdrachak/CS212 | /212/Unit2/HW2-2.py | 1,564 | 4.125 | 4 | #------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a higher floor than does Kay.
# Ritchie does not live on a floor adjacent to Liskov's.
# Liskov does not live on a floor adjacent to Kay's.
#
# Where does everyone live?
#
# Write a function floor_puzzle() that returns a list of
# five floor numbers denoting the floor of Hopper, Kay,
# Liskov, Perlis, and Ritchie.
import itertools
def higher(f1, f2):
"""
Returns True if floor f1 is higher than floor f2
"""
return True if f1 - f2 > 0 else False
def adjacent(f1, f2):
"""
Returns True if floors f1 and f2 are adjacent to each other
"""
return True if abs(f1 - f2) == 1 else False
def floor_puzzle():
"""
Solves Floor puzzle.
Returns a list of
five floor numbers denoting the floor of Hopper, Kay,
Liskov, Perlis, and Ritchie.
"""
floors = [1,2,3,4,5]
c_floors = itertools.permutations(floors)
order = next([Hopper, Kay, Liskov, Perlis, Ritchie]
for Hopper, Kay, Liskov, Perlis, Ritchie in c_floors
if (Hopper != 5)
and (Kay != 1)
and (Liskov != 1 and Liskov != 5)
and (higher(Perlis, Kay))
and (not adjacent(Ritchie, Liskov))
and (not adjacent(Liskov, Kay)))
return order
print floor_puzzle() | true |
75fa0274e9cfd4193bb5d1730caf90b2b0c5b194 | edagotti689/PYTHON-7-REGULAR-EXPRESSIONS | /1_match.py | 508 | 4.15625 | 4 | '''
1. Match is used to find a pattern from starting position
'''
import re
name = 'sriram'
mo = re.match('sri', name)
print(mo.group())
# matching through \w pattern
name = 'sriram'
mo = re.match('\w\w\w', name)
print(mo.group())
# matching numbers through \d pattern
name = 'sriram123'
mo = re.match('\d\d\d', name)
print(mo.group())
'''
Error:1
File "1_match.py", line 18, in <module>
print(mo.group())
AttributeError: 'NoneType' object has no attribute 'group'
''' | true |
a59503d23f606bad8fc8ff6c68001e6ea1783431 | Rd-Feng/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 257 | 4.125 | 4 | #!/usr/bin/python3
"""Define MyList that extends list"""
class MyList(list):
"""add print_sorted instance method that prints the list in sorted order"""
def print_sorted(self):
"""print list in sorted order"""
print(sorted(self))
| true |
62e3752738f77f5c638ecbfcc3451b901338cec3 | vesnushka-sokol/test | /03_try_except/word_count.py | 819 | 4.15625 | 4 | def count_words(filename):
"""" Подсчет приблизительного количества строк в файле """
try:
with open(filename) as f:
content = f.read()
except FileNotFoundError:
with open('missing_files.txt', 'a', encoding='utf-8') as m:
m.write(filename + '\n')
# pass
# print(f'Sorry, the file {filename} does not exist.')
else:
num_words = len(content.split())
oft_count = content.count('the')
print(f'The file {filename} has about {num_words} words.')
print(f'Количество вхождений слова "the" в этом файле - '
f'{oft_count}.\n')
for file in ['alice.txt', 'siddhartha.txt', 'moby_dick.txt']:
count_words(file)
| false |
705cc760876474bc595a7244895ea27ecb875d76 | shrirangmhalgi/Python-Bootcamp | /25. Iterators Generators/iterators.py | 495 | 4.34375 | 4 | # iterator is object which can be iterated upon An object which returns data, one at a time when next() is called on it
name = "Shrirang"
iterator = iter(name)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator)) # StopIteration error is thrown at the end of iterator
# iterable is object which returns a iterator when iter() method is called on it | true |
2302ed436657bca98feffd12477b4294ba12313b | shrirangmhalgi/Python-Bootcamp | /8. Boolean Statements/conditional_statements.py | 789 | 4.125 | 4 | name = input("Enter a name:\n")
if name == "shrirang":
print("Hello Shrirang")
elif name == "suvarna":
print("Hello Suvarna")
elif name == "rajendra":
print("Hello Rajendra")
else:
print("Hello User")
# truthiness and falsiness
# (is) is used to evaluate truthiness and falsiness
# falsiness includes
# None, Empty strings, Empty objecs and zero
# and or not
a = 1
b = 0
if a and b:
print(f"{a} and {b} is true")
else:
print(f"{a} and {b} is false")
if a or b:
print(f"{a} or {b} is true")
else:
print(f"{a} or {b} is false")
if not b:
print(f"not {a} is {not a}")
# is vs ==
# is checks that whether they are stored in same memory address
# == checks the values inside them
# a = [1, 2, 3]
# b = [1, 2, 3]
# a == b gives true
# a is b gives false | true |
d81cadb1c01234f822fab833bc67f06b8c0cfa10 | shrirangmhalgi/Python-Bootcamp | /20. Lambdas and Builtin Functions/builtin_functions.py | 1,851 | 4.125 | 4 | import sys
# 1. all() returns true if ALL elements of iteratable are truthy
print(all(list(range(10))))
print(all(list(range(1, 10))))
# 2. any() returns true if ANY of the element is truthy
print(any(list(range(10))))
print(any(list(range(1, 10))))
# 3. sys.getsizeof
print(sys.getsizeof([x % 2 == 0 for x in range(1000)]))
print(sys.getsizeof((x % 2 == 0 for x in range(1000)))) # (x % 2 == 0 for x in range(1000)) is a generator
# 4. sorted() sorts things
list1 = list(range(10, 0, -1))
dict1 = [dict(name = "shrri"), dict(name = "hrri", last = "rang")]
print(sorted(list1))
print(sorted(list1, reverse = True))
print(sorted(dict1, key = lambda user : user['name'], reverse = True))
# 5. min() finds the minimum element
print(min(list1))
print(min(list1, key = lambda n : n > 5))
# 6. max() finds the maximum element
print(max(list1))
print(max(list1, key = lambda n : n < 2))
# 7. reversed returns a reverse iterator
for i in reversed(list1):
print(i)
print(''.join(list(reversed("hello world"))))
# 8. len
print("hello".__len__())
# 9. abs returns the absolute value of a number
print(abs(-1.2))
print(abs(-1))
print(abs(1.2))
print(abs(1))
# 10. sum returns the sum of the collection
print(sum(list1, 100))
# 11. round rounds off the given number
print(round(1.212121, 2))
print(round(1.5))
# 12. zip is used to bind 2 or more collections together it stops as soon as the shortest iterable is exhausted
list1 = list(range(10, 20))
list2 = list(range(20, 30))
print(dict(zip(list1, list2)))
midterms = [80,91,78]
finals = [98,89,53]
students = ['dan', 'ang', 'kate']
print({pair[0] : max(pair[1], pair[2]) for pair in zip(students, midterms, finals)})
print(dict(zip(students, map(lambda pair: max(pair), zip(midterms, finals)))))
print(dict(zip(students, map(lambda pair: ((pair[0] + pair[1]) / 2), zip(midterms, finals))))) | true |
713b3b42119f727b8e3bc59a09a6f0f27e748339 | shrirangmhalgi/Python-Bootcamp | /12. Lists/lists.py | 1,903 | 4.53125 | 5 | # len() function can be used to find length of anything..
# lists start with [ and end with ] and are csv
task = ["task 1", "task 2", "task 3"]
print(len(task)) # prints the length of the list...
list1 = list(range(1, 10)) # another way to define a list
# accessing data in the lists
# lists are accessed like arrays.. 0, 1, 2 ... and to count it backwards, start with negative -1, -2, -3 ...
print(task[0])
print(task[1])
print(task[2])
# to check if value exists in a list or not use the in operator
print("task 1" in task)
# iterate through lists
for i in task :
print(i)
i = 0
while i != len(task) :
print(f"task {i} : " + str (task[i]))
i += 1
# some list methods
# 1. append(123) -> appends the data in the list
a = []
a.append(1)
print(a)
# 2. extend([list]) -> attaches multiple items to the list
a.extend([2, 3, 4])
print(a)
# 3. insert(position, data)
a.insert(2, "shrirang")
print(a)
# 4. clear() removes all the elements from the list
a.clear()
print(a)
# 5. pop(index number)
a.extend([2, 3, 4])
a.pop() # -> removes last element from the list
a.pop(0) # -> removes the element specified by index number
print(a)
# 6. remove(x) x is a value but remove does not return a value
a.remove(3)
print(a)
# 7. index(value) returns the first index of the value present in the list
a.extend([2, 3, 4])
print(a.index(2))
print(a.index(2, 1)) # -> finds the first index of 2 starting from 1
print(a.index(2, 1, 2)) # -> finds the first index of 2 starting from 1 and ending index of 2
# 8. count() -> returns the count of the number present in the list
print(a.count(2))
# 9. reverse() -> reverses the current list
a.reverse()
print(a)
# 10. sort()
a.sort()
print(a)
# 11. join
" ".join(a)
# tasks = ["task " + str(i) for i in range(1, 4)]
# print(tasks)
# a=[0]*10
# b=[0 for i in range(10)]
# print(a)
# print(b)
# a[2]=9
# b[2]=9
# print(a)
# print(b)
| true |
4a9158546b978eb121262bb114def980bfbc2ca9 | shrirangmhalgi/Python-Bootcamp | /30. File Handling/reading_file.py | 528 | 4.1875 | 4 | file = open("story.txt")
print(file.read())
# After a file is read, the cursor is at the end...
print(file.read())
# seek is used to manipulate the position of the cursor
file.seek(0) # Move the cursor at the specific position
print(file.readline()) # reads the first line of the file
file.seek(0)
print(file.readlines()) # Reads all the contents of the file and stores it in a list
# Make sure you close the files when you are done...
file.close()
# returns a value to check whether the file is closed or not...
file.closed | true |
d7df6511316ed65740cca6f8570f152fad2637fe | chivitc1/python-turtle-learning | /turtle15.py | 552 | 4.15625 | 4 | """
animate1.py
Animates the turtle using the ontimer function.
"""
from turtle import *
def act():
"""Move forward and turn a bit, forever."""
left(2)
forward(2)
ontimer(act, 1)
def main():
"""Start the timer with the move function.
The user’s click exits the program."""
reset()
shape("turtle")
speed(0)
up()
exitonclick() # Quit the program when the user clicks the mouse
listen()
ontimer(act, 1)
return "Done!"
if __name__ == '__main__':
msg = main()
print(msg)
mainloop() | true |
1731be54e0a9905f6f751a97808931ce54e0bec0 | chivitc1/python-turtle-learning | /menuitem_test.py | 1,121 | 4.28125 | 4 | """
menuitem_test.py
A simple tester program for menu items.
"""
from turtle import *
from menuitem import MenuItem
from flag import Flag
INDENT = 30
START_Y = 100
ITEM_SPACE = 30
menuClick = Flag()
def changePenColor(c):
"""Changes the system turtle’s color to c."""
menuClick.value(True)
color(c)
def createMenu(callback):
"""Displays 6 menu items to respond to the given callback function."""
x = -(window_width() / 2) + INDENT
y = START_Y
colors = ("red", "green", "blue", "yellow", "purple", "black")
shape = "circle"
for color in colors:
MenuItem(x, y, shape, color, callback)
y -= ITEM_SPACE
def skip(x, y):
"Moves the pen to the given location without drawing."
if not menuClick.value():
up()
goto(x, y)
down()
else:
menuClick.value(False) # Reset when menu item selected
def main():
"""Creates a menu for selecting colors."""
reset()
shape("triangle")
createMenu(changePenColor)
onscreenclick(skip)
listen()
return "Done"
if __name__ == '__main__':
main()
mainloop() | true |
4dfa7c1f1f9f51b838fcfb7e7d6c9f5f4fad2d42 | chivitc1/python-turtle-learning | /turtle17.py | 1,508 | 4.46875 | 4 | """
testpoly.py
Illustrates the use of begin_poly, end_poly, and get_poly to
create custom turtle shapes.
"""
from turtle import *
def regularPolygon(length, numSides):
"""Draws a regular polygon.
Arguments: the length and number of sides."""
iterationAngle = 360 / numSides
for count in range(numSides):
forward(length)
left(iterationAngle)
def makeShape(length, numSides, shapeName):
"""Creates and registers a new turtle shape with the given name.
The shape is a regular polygon with the given length and number
of sides.
Arguments: the length, number of sides, and shape name."""
up()
goto(0,0)
setheading(0)
begin_poly()
regularPolygon(length, numSides)
end_poly()
shape = get_poly()
addshape(shapeName, shape)
def main():
"""Creates two turtles with custom shapes and allows you
to drag them around the window."""
hideturtle()
speed(0)
makeShape(length=40, numSides=5, shapeName="pentagon")
makeShape(length=20, numSides=8, shapeName="octagon")
turtle1 = Turtle(shape="pentagon")
turtle1.color("brown", "green")
turtle1.up()
turtle1.goto(100, 50)
turtle1.tilt(angle=90)
turtle2 = Turtle(shape="octagon")
turtle2.color("blue", "pink")
turtle2.up()
turtle1.ondrag(lambda x, y: turtle1.goto(x, y))
turtle2.ondrag(lambda x, y: turtle2.goto(x, y))
listen()
return "Done!"
if __name__ == '__main__':
msg = main()
print(msg)
mainloop() | true |
85c90222620112056beeca40bd89fa028eddaa37 | MichaelTennyson/OOP | /lab7(practice).py | 2,775 | 4.21875 | 4 | import string
# converts file into a list of strings
def create_data_list(data_file : string) -> list:
o_file = open(data_file, 'r')
data_list = []
for line_str in o_file:
data_list.append(line_str.strip().split(','))
return data_list
def monthly_averages(data_list : list) -> list:
monthly_average = {}
for i in range(len(data_list)):
try:
y, m, d = data_list[i][0].split("-")
y = int(y)
m = int(m)
d = int(d)
except:
print("Data format wrong!")
if (y, m) in monthly_average.keys():
monthly_average[(y, m)][0] += float(data_list[i][5]) * float(data_list[i][6])
monthly_average[(y, m)][1] += float(data_list[i][5])
else:
monthly_average[(y, m)] = []
monthly_average[(y, m)].append(float(data_list[i][5]) * float(data_list[i][6]))
monthly_average[(y, m)].append(float(data_list[i][5]))
# Append tuple of results in a list
# Tuples are like (average, year, month).
# Final average needs to be calculated since it only contains the numerator and denominator
monthly_average_list = []
for (y, m), value in monthly_average.items():
average = value[0] / value[1]
monthly_average_list.append((average, y, m))
# Sorting first by descending average. In case of ties sort by year and then month
monthly_average_list.sort(reverse=True)
def print_info(monthly_averages_list : list) -> None:
""" Prints sorted list of 6 best and 6 worst average (2 decimals) by months in the format:
Six best months
Average Year Month
---- ---- -----
Six worst months
Average Year Month
---- ---- -----
"""
print('{:^33s}'.format('Six best months'))
print('{:11s}{:11s}{:11s}'.format('Average', 'Year', 'Month'))
# Print six best months assuming list is ordered in descending order
for i in range(6):
average, year, month = monthly_averages_list[i]
print('{:<11.2f}{:<11d}{:<2d}'.format(average, year, month))
print()
print('{:^33s}'.format('Six worst months'))
print('{:11s}{:11s}{:11s}'.format('Average', 'Year', 'Month'))
# Print six worst months assuming list is ordered in descending order
for i in range(1, 7):
average, year, month = monthly_averages_list[-i]
print('{:<11.2f}{:<11d}{:<2d}'.format(average, year, month))
def main():
data_list = create_data_list("GOOG.csv")
monthly_averages_list = monthly_averages(data_list)
print_info(monthly_averages_list)
main()
| false |
dab151fa8d3e2045bd5fab97d96c7ed1e1e9fe7f | MichaelTennyson/OOP | /lab3(practice).py | 516 | 4.5 | 4 | # The following program scrambles a string, leaving the first and last letter be
# the user first inputs their string
# the string is then turned into a list and is split apart
# the list of characters are scrambled and concatenated
import random
print("this program wil take a word and will scramble it \n")
word = input("enter the word\n")
word_list = list(word)
for i in range(len(word_list)):
random.shuffle(word_list[1:-1])
scrambled_word = "".join(word_list)
print(scrambled_word)
| true |
415a67a9d93c18d9794baadf1c50d0eb9e51ae27 | Yvonnexx/code | /binary_search.py | 341 | 4.125 | 4 | #!/usr/bin/python
def binary_search(num, target):
length = len(num)
start = 0
end = length - 1
while start < end:
mid = start + (end-start)/2
if target > num[mid]:
start = mid + 1
else:
end = mid
return start
num = [1,2,3,4,5]
target = 3
print binary_search(num, target)
| false |
4e44b69e698e6f9435bc9e147b473398e8c794e1 | DanielShin2/CP1404_practicals | /prac05/emails.py | 624 | 4.1875 | 4 | def name_from_email(email):
username = email.split("@")[0]
parts = username.split(".")
name = " ".join(parts).title()
return name
def main():
email_name = {}
email = input("Enter your email: ")
while email != "":
name = name_from_email(email)
correct = input("Is your name {}? (Y/N): ".format(name)).upper()
if correct.upper() == "N" or correct != "":
name = input("Enter your name: ")
email = input("Enter your email: ")
email_name[email] = name
for email, name in email_name.items():
print("{} ({})".format(name, email))
main() | true |
7b7ae24c2bf54988394165e6c63c165a84472f0e | mrudulamucherla/Python-Class | /2nd assign/dec to binary,.py | 510 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 16:19:30 2020
@author: mrudula
"""
#write prgm to convert decimal to binary number sysytem using bitwise operator
binary_num=list()
decimal_num=int(input("enter number"))
for i in range(0,8):
shift=decimal_num>>i #code to check value of last bit and append 1 or 0 to list make binary number
if shift&1:
binary_num.append(1)
else:
binary_num.append(0)
for j in range(-1,-9,-1):
print(binary_num[j],end="")
| true |
d99c43ed6e3f8ff9cbd3ee31063216578a3702f5 | mrudulamucherla/Python-Class | /While Loop,134.py | 236 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 14:13:32 2020
@author: mrudula
"""
#Print all 3 multiples from 1 to 100 using for while loop.
while True:
for i in range (1,101):
print(i*3,end=" ")
break | true |
4cf6cf7d66050a5a9a4f2ef8f7ad48b5f20d9dc3 | lilbond/bitis | /day1/exploring.py | 2,508 | 4.53125 | 5 | """
Samples below are intended to get us started with Python.
Did you notice this is a multi-line comment :-) and yes being the first
one and before code, it qualifies to be documentation as well. How Cool!!!
In order to be a docstring it had to be multi-line
"""
# print hello world :-), Hey this is a single line comment
print("Hello, World")
'''
We can define strings using ' (single quotes) or using " (double quotes)
Same goes for comments, did you notice this one.
Assignment
----------
print messages below:
1. You won't be disappointed with Python
2. One day you will say "I love Python"
3. You won't be disappointed with Python. One day you will say "I love Python"
'''
# Getting rid of new line
print("Hello", end='')
print(", World!!!")
# Working with variables is damn easy
an_int = 1
a_string = "We won't work with other types today. Yes, there are many more."
'''
There is no verbosity like - int anInt = 1; or String aString = "Something";
'''
# Programming is all about decision making, is not it?
if an_int == 1:
print(a_string)
# A decision without a negative case is not so useful
if an_int == 2:
print(a_string)
else:
print("Damn it was not true!!!")
# Ah! that was nice but how can I take more than one decisions
if an_int == 2:
print("It is 2 indeed")
elif an_int == 1:
print("It is 1 indeed")
else:
print("I seriously have not idea, what it is")
'''
Do we just keep scripting in Python or can we package snippets and reuse
Did not you realize, what print is? Yes, it is a function.
A callable, reusable and self contained unit of code. Provides a logical grouping and
helps in organizing snippets to perform unit of work.
Disclaimer: I am NOT good at definitions and this one is purely self cooked :-)
'''
def greet_awesome_people():
print("Hello Awesome People. I am a dumb function but teaches a very powerful thing. \nGuess what?")
# Guess what?
greet_awesome_people()
# Same goes for me, guess guess :-)
def i_am_bit_smarter(message):
print(message)
# And same goes for me
def i_am_bit_more_smarter(a, b):
return a + b
i_am_bit_smarter("Custom Message>> Sum of 10 and 2 is : " + str(i_am_bit_more_smarter(10, 2)))
'''
Assignment
----------
Write the smartest calculator which:
- Works only with integer
- Handles add, subtract, mul and divide
client should be able to use your calculator like:
add(10,2), subtract(11, 3) etc.
'''
# Time to evaluate our guess and together try to get a bit of programming Moksha :-). | true |
ab4ad6fb7096a9276d614b2d0b4a97276f1c2512 | cpucortexm/python_IT | /python_interacting _with_os/logfile/parse_log.py | 1,985 | 4.3125 | 4 | #!/usr/bin/env python3
import sys
import os
import re
''' The script parses the input log file and generates an output containing only
relevant logs which the user can enter on command prompt
'''
def error_search(log_file):
error = input("What is the error? ") # input the error string which you want to see in the output
returned_errors = []
with open(log_file, mode='r',encoding='UTF-8') as file:
for log in file.readlines():
error_patterns = ["error"] # default pattern is "error"
for i in range(len(error.split(' '))): # split the input string into a list
error_patterns.append(r"{}".format(error.split(' ')[i].lower())) # keep appending every word of the input string split by space to list of patterns
if all(re.search(error_pattern, log.lower()) for error_pattern in error_patterns): # use regex to compare the list of patterns with each log line
returned_errors.append(log) # append every line which matches to all the patterns in the list
file.close()
return returned_errors
def file_output(returned_errors):
with open(os.path.expanduser('~') + '/Desktop/python-coursera/logfile/errors_found.log', 'w') as file:
for error in returned_errors:
file.write(error)
file.close()
'''
If the python interpreter is running that module (the source file) as the main program,
it sets the special __name__ variable to have a value “__main__”. If this file is being
imported from another module, __name__ will be set to the module’s name.
Every Python module has it’s __name__ defined and if this is ‘__main__’,
it implies that the module is being run as a standalone by the user and we can
do corresponding appropriate actions.
If you import this script as a module in another script, the __name__ is set to the name of the script/module.
'''
if __name__ == "__main__":
log_file = sys.argv[1]
returned_errors = error_search(log_file)
file_output(returned_errors)
sys.exit(0)
| true |
3802612e9ba51aaa8d3307e8ab39d413dc8b6d20 | nguyntony/class | /large_exercises/large_fundamentals/guess2.py | 1,553 | 4.21875 | 4 | import random
on = True
attempts = 5
guess = None
print("Let's play a guessing game!\nGuess a number 1 and 10.")
while on:
# correct = random.randint(1, 10)
while True:
try:
guess = int(input())
break
except ValueError:
print("Please give a number!")
correct = random.randint(1, 10)
print(correct)
if guess < 1 or guess > 10:
print(f"{guess} is not a number between 1 and 10.")
print("Try again.")
elif guess == correct:
print(
f"YES! I was thinking of the number: {correct}\nYou win!")
# I need this to ask if we want to play again
decision = input("Play again? ( Y / N ) ").lower()
if decision == "no" or decision == "n":
print("Goodbye!")
on = False
else:
print("Guess another number!")
else:
if guess < correct:
print("Your guess is too low.")
else:
print("Your guess is too high.")
print("NOPE! Try again.")
attempts -= 1
if attempts != 0:
print(f"You have {attempts} remaining guesses.")
else:
print("You ran out of guesses!")
print("You lose!")
# I need to ask to see if they wanna play again.
decision = input("Play again? ( Y / N ) ").lower()
if decision == "no" or decision == "n":
print("Goodbye!")
on = False
else:
print("Guess another number!")
| true |
9148ba1063ba78923a760707e24d3f3e78a2fab1 | nguyntony/class | /python101/strings.py | 303 | 4.1875 | 4 | # interpolation syntax
first_name = "tony"
last_name = "nguyen"
print("hello %s %s, this is interpolation syntax" % (first_name, last_name))
# f string
print(f"Hi my name is {first_name} {last_name}")
# escape string, you use the back slash \
# \n, \t
# concatenating is joining two things together
| true |
518a262e0db8dc3b9a9645f41f331ee79794dc54 | nguyntony/class | /python102/dict/ex1_dict.py | 458 | 4.21875 | 4 | siblings = {}
# for a list you can not create a new index but in a dictionary you can create a new key with the value at any time.
siblings["name"] = "Misty"
siblings["age"] = 15
siblings["fav_colors"] = ["pink", "yellow"]
siblings["fav_colors"].append("blue")
print(siblings)
# loop
# key
for key in siblings:
print(key)
# values
for key in siblings:
print(siblings[key])
# key and values
for key in siblings:
print(key, siblings[key])
| true |
aa4105b0f27729de85e91b4a106d25509b6a991d | nguyntony/class | /python102/list/ex3_list.py | 1,185 | 4.375 | 4 | # Using the code from exercise 2, prompt the user for which item the user thinks is the most interesting. Tell the user to use numbers to pick. (IE 0-3).
# When the user has entered the value print out the selection that the user chose with some sort of pithy message associated with the choice.
things = ["water bottle", "chapstick", "phone", "headphones"]
index = 0
while index < len(things):
thing = things[index]
print(f"{index}: {thing}")
index += 1
print("What is the most interesting item?")
while True:
try:
choice = int(input("Pick a number between 0 - 3\n"))
break
except ValueError:
print("Please enter an integer!")
try:
if things[choice] == things[0]:
print(f"You chose {things[0]}, you must be thirsty!")
elif things[choice] == things[1]:
print(f"You chose {things[1]}, your lips must be dry!")
elif things[choice] == things[2]:
print(
f"You chose {things[2]}, get off your phone and pay attention in class!")
elif things[choice] == things[3]:
print(f"You chose {things[3]}, great!")
except IndexError:
print("You did not choose a number between 0 - 3!")
| true |
b6817fa9a655b70a7a24bedcfe2ddcad19ac2b4e | Randyedu/python | /知识点/04-LiaoXueFeng-master/06-dict.py | 1,767 | 4.3125 | 4 | '''
dict
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
'''
d = {'Min':95, 'Bob':75, 'Tra':85}
print(d, type(d))
print(d['Min'])
print(d)
# 如果key不存在,dict就会报错
# 要避免key不存在的错误,有两种办法,一是通过in判断key是否存在
print('tra' in d)
print('Tra' in d)
# 二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
print(d.get('Tra'))
print(d.get('Tras'))
print(d.get('Tras', '没有该用户'))
# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除
d.pop('Bob')
print(d)
'''
dict内部存放的顺序和key放入的顺序是没有关系的。
和list比较,dict有以下几个特点:
1、查找和插入的速度极快,不会随着key的增加而增加;
2、需要占用大量的内存,内存浪费多。
而list相反:
1、查找和插入的时间随着元素的增加而增加;
2、占用空间小,浪费内存很少。
所以,dict是用空间来换取时间的一种方法。
'''
'''
dict可以用在需要高速查找的很多地方,在Python代码中几乎无处不在,正确使用dict非常重要,需要牢记的第一条就是dict的key必须是不可变对象。
这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混乱了。这个通过key计算位置的算法称为哈希算法(Hash)。
要保证hash的正确性,作为key的对象就不能变。
在Python中,字符串、整数等都是不可变的,因此,可以放心地作为key。而list是可变的,就不能作为key
''' | false |
280dde835bdd22c44a461955634526aa9bd57faa | cute3954/Solving-Foundations-of-Programming | /problem-solving-with-python/makeBricks.py | 1,302 | 4.3125 | 4 | # https://codingbat.com/prob/p183562
#
# We want to make a row of bricks that is goal inches long.
# We have a number of small bricks (1 inch each) and big bricks (5 inches each).
# Return true if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks
#
# makeBricks(3, 1, 8) → true
# makeBricks(3, 1, 9) → false
# makeBricks(3, 2, 10) → true
class BricksMaker:
def __init__(self):
self.bricks = [
{'small': 3, 'big': 1, 'goal': 8},
{'small': 6, 'big': 0, 'goal': 11},
{'small': 1, 'big': 4, 'goal': 12},
{'small': 43, 'big': 1, 'goal': 46},
{'small': 1000000, 'big': 1000, 'goal': 1000100},
{'small': 2, 'big': 1000000, 'goal': 100003},
{'small': 20, 'big': 4, 'goal': 39}
]
for i in range(len(self.bricks)):
result = self.makeBricks(self.bricks[i])
print(result)
def makeBricks(self, bricks):
small = bricks['small']
big = bricks['big']
goal = bricks['goal']
re = goal - big * 5 if goal >= big * 5 else goal % 5
result = False if re > small else True
return result
BricksMaker() | true |
9a06dd1b4a054f8202f226251f3038002c011d11 | skyaiolos/myshiyanlou | /designPattern/behavioralPattern/templateMethod.py | 1,864 | 4.15625 | 4 | __author__ = "Jianguo Jin (jinjianguosky@hotmail.com)"
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# Created by Jianguo on 2017/6/5
"""
Description:
"""
import abc
class Fishing(object):
"""
钓鱼模板基类
"""
__metaclass__ = abc.ABCMeta
def finishing(self):
"""
钓鱼方法中,确定了要执行哪些操作才能钓鱼
"""
self.prepare_bait()
self.go_to_riverbank()
self.find_location()
print("start fishing")
@abc.abstractmethod
def prepare_bait(self):
pass
@abc.abstractmethod
def go_to_riverbank(self):
pass
@abc.abstractmethod
def find_location(self):
pass
class JohnFishing(Fishing):
"""
John 也想去钓鱼,它必须实现钓鱼三步骤
"""
def prepare_bait(self):
"""
从淘宝购买鱼饵
"""
print("John: buy bait from 淘宝")
def go_to_riverbank(self):
"""
开车去钓鱼
"""
print("John: to river by driving")
def find_location(self):
"""
在岛上选择钓点
"""
print("John: select location on the island")
class SimonFishing(Fishing):
"""
Simon 也想去钓鱼,它也必须实现钓鱼三步骤
"""
def prepare_bait(self):
"""
从京东购买鱼饵
"""
print("Simon: buy bait from 京东")
def go_to_riverbank(self):
"""
骑自行车去钓鱼
"""
print("Simon: to river by biking")
def find_location(self):
"""
在河边选择钓点
"""
print("Simon: select location on the riverbank")
if __name__ == '__main__':
# John 去钓鱼
f = JohnFishing()
f.finishing()
print('-' * 30)
# Simon 去钓鱼
f = SimonFishing()
f.finishing()
| false |
1226a6de159e071159a9aca6f00a4dd2483265ab | daveboat/interview_prep | /coding_practice/binary_tree/populating_next_right_pointers_in_each_node.py | 2,486 | 4.125 | 4 | """
LC116 - Populating Next Right Pointers in Each Node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The
binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be
set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to
its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers,
with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than 4096.
-1000 <= node.val <= 1000
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
# trivial case
if not root:
return None
# since the binary tree is perfect, we can do a breadth-first search with a known number of
# nodes at each level (i.e. 2^i where i is the level, starting from 0). This necessarily
# O(N) time (need to visit every node) and O(N) space (need to store on average N/2 nodes in
# the queue)
curr_level = 0
queue = [root]
level_node_counter = 0
while queue:
# pop node and add children
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# increment counter and do assignment of node.next
level_node_counter += 1
if level_node_counter == 2 ** curr_level: # end of level
node.next = None
curr_level += 1
level_node_counter = 0
else: # otherwise
node.next = queue[0]
return root | true |
49dfa92d60ff280719607b50f9e5a6aa40f76e1e | daveboat/interview_prep | /coding_practice/general/robot_bounded_in_circle.py | 2,663 | 4.15625 | 4 | """
LC1041 - Robot bounded in circle
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Example 2:
Input: "GG"
Output: false
Explanation:
The robot moves north indefinitely.
Example 3:
Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Note:
1 <= instructions.length <= 100
instructions[i] is in {'G', 'L', 'R'}
"""
class Solution(object):
def get_next_orientation(self, current_orientation, instruction):
if instruction == 'R':
return 0 if current_orientation == 3 else current_orientation + 1
elif instruction == 'L':
return 3 if current_orientation == 0 else current_orientation - 1
def isRobotBounded(self, instructions):
"""
:type instructions: str
:rtype: bool
"""
# the robot stays bounded if it returns to its original position OR if its final direction before looping
# is no longer north. In the first case, the robot will return to its original position, and so it's bounded.
# in the second case, the robot will make a multi-cycle loop
# so we follow the instructions to the end, and find the final position and direction
current_position = [0, 0]
current_orientation = 0 # 0 - North, 1 - West, 2 - South, 3 - East
for i in instructions:
if i == 'L' or i == 'R':
current_orientation = self.get_next_orientation(current_orientation, i)
elif i == 'G':
if current_orientation == 0:
current_position[1] += 1
elif current_orientation == 1:
current_position[0] -= 1
elif current_orientation == 2:
current_position[1] -= 1
elif current_orientation == 3:
current_position[0] += 1
if current_position == [0, 0]:
return True
elif current_orientation != 0:
return True
else:
return False
| true |
c38cc560308edabac42c87bec8252bc9f446e39c | momentum-cohort-2019-05/w2d2-palindrome-bhagh | /palindrome.py | 577 | 4.25 | 4 | import re
#grab user input
submission = input("Enter a word or sentence(s): ")
#function to clean up text by user
def cleantext (submission):
submission = (re.sub("[^a-zA-Z0-9]+", '', submission).replace(" ",""))
return submission
print(cleantext(submission))
#create a string that's the reverse of the text by the user
backwards_string = (cleantext(submission)[::-1])
#check if both strings match
if str(cleantext(submission).lower()) == str(backwards_string.lower()):
print(submission, "is a palindrome")
else:
print(submission, "is not a palindrome")
| true |
e74a0ce8b1b2301019f58e51ad1befacaf983a4c | sidmusale97/SE-Project | /Pricing Algorithm/linearRegression.py | 1,113 | 4.28125 | 4 | '''
------------------------------------------------------------------------------------
This function is used to compute the mean squared error of a given data set and also
to find the gradient descent of the theta values and minimize the costfunction.
------------------------------------------------------------------------------------
X="input parameters"
y="required output"
theta="parameters to minimize costfunction"
alpha = "Learning rate"
num_iters="Number of iterations to run"
'''
import numpy as np
def computecost(X, y, theta):
m = y.size
x = np.transpose(X)
hypothesis = x.dot(theta)
sub = np.subtract(hypothesis, y)
cost = (0.5 / m) * np.sum(sub ** 2)
return cost
def gradient(X, y, theta, alpha, num_iters):
m = y.size
x = np.transpose(X)
cost_iter = np.zeros((num_iters, 1))
for i in range(1, num_iters):
hypothesis = x.dot(theta)
theta = theta - ((alpha / m) * (np.dot(X, np.subtract(hypothesis, y))))
cost = computecost(X, y, theta)
cost_iter[i - 1] = cost
return theta, cost_iter | true |
93226ba29c06e18e86531e1c7326ab89082d473c | SAbarber/python-exercises | /ex12.py | 611 | 4.34375 | 4 | #Write a Python class named Circle.
Use the radius as a constructor.
Create two methods which will compute the AREA and the PERIMETER of a circle.
A = π r^2 (pi * r squared)
Perimeter = 2πr
class Circle:
def area(self):
return self.pi * self.radius ** 2
def __init__(self, pi, radius):
self.pi = pi
self.radius = radius
x = Circle(3.14,5)
print('The area is' ,x.area())
class Perimeter():
def perm(self):
return 2 * self.pi * self.radius
def __init__(self, pi, radius):
self.pi = pi
self.radius = radius
i = Perimeter(3.14,5)
print('Ther perimeter is', i.perm())
| true |
153844a39053bf165547a8626a89840a82274f36 | alu0100636857/Grupo1H | /src/src/InterpolacionTaylor.py | 781 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Interpolación: Taylor
# Gabriela Balcedo Acosta y Vanesa Abad Armas
# Curso: 2012/2013
from math import *
from sympy import *
A=0
B=2
def factorial(n):
if (n<2):
return 1
r=1
for i in range(2,n+1):
r*=i
return r
def deriv():
symb_x = Symbol('x')
func = (5**symb_x)
derivada = diff(func, symb_x, a)
x=1.5
if __name__ == "__main__":
a=int(raw_input("¿De cuantos pasos quiere la serie?"))
j=0
for j in range(a):
n=int(raw_input("Introduce el factorial"))
for i in range(a):
taylor=((5**1.5)+(B-A)/factorial(n))*deriv()
j+=1
#print derivada
#print "El resultado de evaluar la derivada {0}-esima en el punto {1} es {2}".format(n, x, eval(str(derivada)))
print "La evaluación es:",taylor
| false |
1cca34bd53ba9d73f844dccf011526deb399cd18 | darkbodhi/Some-python-homeworks | /divN.py | 713 | 4.25 | 4 | minimum = int(input("Please insert the minimal number: "))
maximum = int(input("Please insert the maximal number: "))
divisor = int(input("Please insert the number on which the first one will be divided: "))
x = minimum % divisor
if divisor <= 0:
raise Exception("An error has occurred. The divisor is not a natural positive number.")
elif not maximum > minimum:
raise Exception("Error: the relation between numbers is not minimum-maximum.")
elif x == 0:
while minimum <= maximum:
print(minimum)
minimum += divisor
elif x > 0:
minimum += divisor - x
while minimum <= maximum:
print(minimum)
minimum += divisor
else:
raise Exception("An error has occurred.") | true |
aa0c6a66944e2cef568c401bd7f55e55bca1cec6 | anilkumar-satta-au7/attainu-anilkumar-satta-au7 | /create_a_dictionary_from_a_string.py | 430 | 4.21875 | 4 | #3) Write a Python program to create a dictionary from a string.
# Note: Track the count of the letters from the string.
# Sample string : 'w3resource'
# Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
test_str = "w3resource"
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print (str(all_freq)) | true |
01b0cf471c7e1a3d5ea42bd4e8ce2b44eaaba293 | pyaephyokyaw15/credit-card-validation | /credit-card.py | 1,811 | 4.28125 | 4 | '''
Credit-card Validation
- This script is used to determine whether a certain credit-card is
valid or not.
- It is based on Luhn’s algorithm.
- It also determines the type of Card(eg.MASTER, VISA, AMEX)
'''
def main():
# getting number from user until it is numeric value
while True:
card = input("Number: ")
if card.isnumeric():
break
if (is_valid(card)):
# if card is valid, determine what card it is.
if len(card) == 15 and (card[0:2] == '34' or card[0:2] == '37'):
print('AMEX')
elif len(card) == 16 and card[0:2] in ['51','52','53','54','55']:
print('MASTERCARD')
elif 13 <= len(card) <= 16 and card[0] == '4':
print('VISA')
else:
print("INVALID")
else:
print("INVALID")
def is_valid(card):
odd_pos_digit_sum = 0
even_pos_digit_sum = 0
# In algorithm, digit in card starting LSB
# to get digits from the last digit by 2
for position in range(len(card)-1, -1, -2):
# sum each digit directly
odd_pos_digit_sum += int(card[position])
# to get digits even position started from last digit
for position in range(len(card)-2, -1, -2 ):
# peprocessing before sum due to algorithm
digit = int(card[position])
digit *= 2
# if the result digit contains two digit separate them and sum
if digit > 9:
digit = (digit // 10) + (digit % 10)
# sum each digit
even_pos_digit_sum += digit
check_sum = odd_pos_digit_sum + even_pos_digit_sum
# if check_sum is end in 0 , valid
if (check_sum % 10):
return False
return True
if __name__ =="__main__":
main()
| true |
a36d51210c4062391cca3a8218f990388fc20cca | jenihuang/hb_challenges | /EASY/lazy-lemmings/lemmings.py | 942 | 4.21875 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
>>> furthest(7, [0, 6])
3
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
"""
def furthest(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
# find max distance between all cafes and integer divide by 2
distances = set()
distances.add(cafes[0])
distances.add(num_holes - cafes[-1] - 1)
for i in range(1, len(cafes)):
distances.add((cafes[i] - cafes[i - 1]) // 2)
return max(distances)
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED; GREAT JOB!\n")
| true |
de62ef9fb09f2d10b0813bf727442cb6c282b546 | jenihuang/hb_challenges | /EASY/replace-vowels/replacevowels.py | 946 | 4.34375 | 4 | """Given list of chars, return a new copy, but with vowels replaced by '*'.
For example::
>>> replace_vowels(['h', 'i'])
['h', '*']
>>> replace_vowels([])
[]
>>> replace_vowels(['o', 'o', 'o'])
['*', '*', '*']
>>> replace_vowels(['z', 'z', 'z'])
['z', 'z', 'z']
Make sure to handle uppercase::
>>> replace_vowels(["A", "b"])
['*', 'b']
Do not consider `y` a vowel::
>>> replace_vowels(["y", "a", "y"])
['y', '*', 'y']
"""
def replace_vowels(chars):
"""Given list of chars, return a new copy, but with vowels replaced by '*'."""
replaced = []
vowels = {'a', 'e', 'i', 'o', 'u'}
for char in chars:
if char.lower() in vowels:
replaced.append('*')
else:
replaced.append(char)
return replaced
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YAY!\n")
| true |
6ce8b6c28e28ea4207d7bfbc95fb9ccc0d558602 | jenihuang/hb_challenges | /MEDIUM/balanced-brackets/balancedbrackets.py | 1,935 | 4.15625 | 4 | """Does a given string have balanced pairs of brackets?
Given a string, return True or False depending on whether the string
contains balanced (), {}, [], and/or <>.
Many of the same test cases from Balance Parens apply to the expanded
problem, with the caveat that they must check all types of brackets.
These are fine::
>>> has_balanced_brackets("<ok>")
True
>>> has_balanced_brackets("<{ok}>")
True
>>> has_balanced_brackets("<[{(yay)}]>")
True
These are invalid, since they have too many open brackets::
>>> has_balanced_brackets("(Oops!){")
False
>>> has_balanced_brackets("{[[This has too many open square brackets.]}")
False
These are invalid, as they close brackets that weren't open::
>>> has_balanced_brackets(">")
False
>>> has_balanced_brackets("(This has {too many} ) closers. )")
False
Here's a case where the number of brackets opened matches
the number closed, but in the wrong order::
>>> has_balanced_brackets("<{Not Ok>}")
False
If you receive a string with no brackets, consider it balanced::
>>> has_balanced_brackets("No brackets here!")
True
"""
def has_balanced_brackets(phrase):
"""Does a given string have balanced pairs of brackets?
Given a string as input, return True or False depending on whether the
string contains balanced (), {}, [], and/or <>.
"""
stack = []
opens = {'(', '{', '[', '<'}
matches = {')': '(', '}': '{', ']': '[', '>': '<'}
for char in phrase:
if char in opens:
stack.append(char)
elif char in matches:
if not stack:
return False
else:
out = stack.pop()
opening = matches[char]
if out != opening:
return False
if not stack:
return True
else:
return False
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YOU CAUGHT ALL THE STRAY BRACKETS!\n")
| true |
29c4f36d8bfa47db7391311153a590deeb43216b | jenihuang/hb_challenges | /MEDIUM/maxpath/maxpath.py | 2,844 | 4.125 | 4 | """Given a triangle of values, find highest-scoring path.
For example::
2
5 4
3 4 7
1 6 9 6 = [2,4,7,9] = 22
This works:
>>> triangle = make_triangle([[2], [5, 4], [3, 4, 7], [1, 6, 9, 6]])
>>> triangle
[2, 5, 4, 3, 4, 7, 1, 6, 9, 6]
>>> maxpath(triangle)
22
"""
class Node(object):
"""Basic node class that keeps track fo parents and children.
This allows for multiple parents---so this isn't for trees, where
nodes can only have one children. It is for "directed graphs".
"""
def __init__(self, value):
self.value = value
self.children = []
self.parents = []
def __repr__(self):
return str(self.value)
def make_triangle(levels):
"""Make a triangle given a list of levels.
For example, imagining this triangle::
1
2 3
4 5 6
7 8 9 10
We could create it like this::
>>> triangle = make_triangle([[1], [2,3], [4,5,6], [7,8,9,10]])
>>> triangle
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Let's check to make sure this works::
>>> n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 = triangle
>>> n1.parents
[]
>>> n1.children
[2, 3]
>>> n2.parents
[1]
>>> n2.children
[4, 5]
>>> n3.parents
[1]
>>> n3.children
[5, 6]
>>> n4.parents
[2]
>>> n4.children
[7, 8]
>>> n5.parents
[2, 3]
>>> n5.children
[8, 9]
>>> n6.parents
[3]
>>> n6.children
[9, 10]
"""
nodes = []
for y, row in enumerate(levels):
for x, value in enumerate(row):
node = row[x] = Node(value)
nodes.append(node)
if y == 0:
continue
if x == 0:
parents = [levels[y - 1][0]]
elif x == y: # last in row
parents = [levels[y - 1][x - 1]]
else:
parents = [levels[y - 1][x - 1],
levels[y - 1][x]]
node.parents = parents
for p in parents:
p.children.append(node)
return nodes
def maxpath(nodes):
"""Given list of nodes in triangle, return high-scoring path."""
return maxpath_helper(nodes[0])
def maxpath_helper(node):
if not node.children:
return node.value
else:
highest = 0
for child in node.children:
c_value = maxpath_helper(child)
if c_value > highest:
highest = c_value
highest += node.value
return highest
if __name__ == '__main__':
import doctest
print()
if doctest.testmod().failed == 0:
print("\t*** ALL TESTS PASSED; GOOD WORK!")
print()
| true |
9015d36d969ed1e22d46113064e94a3c26dc0043 | jenihuang/hb_challenges | /EASY/rev-string/revstring.py | 519 | 4.15625 | 4 | """Reverse a string.
For example::
>>> rev_string("")
''
>>> rev_string("a")
'a'
>>> rev_string("porcupine")
'enipucrop'
"""
def rev_string(astring):
"""Return reverse of string.
You may NOT use the reversed() function!
"""
rev_str = ''
for i in range(len(astring)-1, -1, -1):
rev_str += astring[i]
return rev_str
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. !KROW DOOG\n")
| true |
6fdb741e9ccd497a7f6a7ae00604072bbf178262 | jenihuang/hb_challenges | /EASY/missing-number/missing.py | 831 | 4.15625 | 4 | """Given a list of numbers 1...max_num, find which one is missing in a list."""
def missing_number(nums, max_num):
"""Given a list of numbers 1...max_num, find which one is missing.
*nums*: list of numbers 1..[max_num]; exactly one digit will be missing.
*max_num*: Largest potential number in list
>>> missing_number([7, 3, 2, 4, 5, 6, 1, 9, 10], 10)
8
"""
# all_nums = set()
# for i in range(1, max_num + 1):
# all_nums.add(i)
# for num in nums:
# if num not in all_nums:
# return num
sum_n = (max_num * (max_num + 1)) / 2
total = 0
for item in nums:
total += item
return int(sum_n - total)
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASS. NICELY DONE!\n")
| true |
de346421fd9bf36a0113d702ccf6de03620b8198 | Johan-p/learnpythonShizzle | /exercise_36_birthdayplots.py | 1,639 | 4.28125 | 4 | """
In this exercise, use the bokeh Python library to plot a histogram
of which months the scientists have birthdays in!
"""
print(__doc__)
from bokeh.plotting import figure, show, output_file
from collections import Counter
import json
def read_jsonfile():
#global birthday_dictionary
global x
global y
with open("birthday.json", "r") as read_file:
birthday_dictionary = json.load(read_file)
#counting number of times months occur in each entry
numberic_list = []
alphabettic_list = []
for values in birthday_dictionary.values():
nummeric_month = values[3] + values[4]
numberic_list.append(str(nummeric_month))
for num in numberic_list:
alphabettic_list.append(month_dict[num])
c = dict(Counter(alphabettic_list))
x = list(c.keys())
y = list(c.values())
# create a figure
# To make sure bokeh draws the axis correctly,
# you need to specify a special call to figure() to pass an x_range
p = figure(x_range=x_categories)
# create a histogram
p.vbar(x=x, top=y, width=0.5)
# render (show) the plot, this opens the browser
show(p)
# we specify an HTML file where the output will go
output_file("plot.html")
x_categories = ["January","Febuary","March","April",
"May","June","July","August","September","October","November","December"]
x = []
y = []
month_dict = {"01":"January",
"02":"Febuary",
"03":"March",
"04":"April",
"05":"May",
"06":"June",
"07":"July",
"08":"August",
"09":"September",
"10":"October",
"11":"November",
"12":"December"}
if __name__=='__main__':
read_jsonfile() | true |
713ed8035bf707c380e127bab4f0c6b36f6641ce | Johan-p/learnpythonShizzle | /Madlibs.py | 1,517 | 4.46875 | 4 | """
In this project, we'll use Python to write a Mad Libs word game! Mad Libs have short stories with blank spaces that a player can fill in. The result is usually funny (or strange).
Mad Libs require:
A short story with blank spaces (asking for different types of words).
Words from the player to fill in those blanks.
"""
# The template for the story
print "starting Mad Libs"
Name = raw_input("Enter a name: ")
Adjective_1 = raw_input("Adjective One: ")
Adjective_2 = raw_input("Adjective Two: ")
Adjective_3 = raw_input("Adjective Three: ")
Verb = raw_input("verb: ")
Nouns_1 = raw_input("nouns One: ")
Nouns_2 = raw_input("nouns Two: ")
Animal = raw_input("input an animal: ")
Food = raw_input("input a food: ")
Fruit = raw_input("input a fruit: ")
Superhero = raw_input("input a superhero: ")
Country = raw_input("input a country: ")
Dessert = raw_input("input a dessert: ")
Year = raw_input("input a Year: ")
STORY = "This morning %s woke up feeling %s. 'It is going to be a %s day!' Outside, a bunch of %ss were protesting to keep %s in stores. They began to %s to the rhythm of the %s, which made all the %ss very %s. Concerned, %s texted %s, who flew %s to %s and dropped %s in a puddle of frozen %s. %s woke up in the year %s, in a world where %ss ruled the world." % (Name, Adjective_1, Adjective_2, Animal, Food, Verb, Nouns_1, Fruit, Adjective_3, Name, Superhero, Name, Country, Name, Dessert, Name, Year, Nouns_2)
print STORY
| true |
8a8d89f72edd35ccb2928af5b147ad882899c6fe | Johan-p/learnpythonShizzle | /exercise_33_birthdaydictionaries.py | 884 | 4.59375 | 5 | """
or this exercise, we will keep track of when our friends birthdays are,
and be able to find that information based on their name.
Create a dictionary (in your file) of names and birthdays.
When you run your program it should ask the user to enter a name,
and return the birthday of that person back to them.
"""
print(__doc__)
#imports
def var():
pass
birthday_dictionary = {"Albert Einstein":"14/03/1879",
"Benjamin Franklin":"17/01/1706",
"Winston Churchill":"24/01/1965",}
if __name__=='__main__':
print "Welcome to the birthday dictionary. We know the birthdays of:"
for key in birthday_dictionary.keys():
print key
user_input = str(raw_input("Who's birthday do you want to look up? "))
if user_input in birthday_dictionary:
print "%s birthday is %s" % (user_input, birthday_dictionary[user_input])
else:
exit() | true |
c816a4224eeff0e5610176feb5df8eacfe3efcfb | HarrisonWelch/MyHackerRankSolutions | /python/Nested Lists.py | 496 | 4.25 | 4 | # Nested Lists.py
# Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
marksheet = []
for _ in range(0,int(input())):
marksheet.append([raw_input(), float(raw_input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print "second_highest = ", second_highest
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
| true |
fc9d7761b45597c8d3efb6fd81f76f0c96d547b7 | Lenux56/FromZeroToHero | /text_vowelfound.py | 519 | 4.4375 | 4 | '''
Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
'''
import re
def multi_re_find():
'''
search and count vowels
'''
phrase = input('Please, enter a phrase to find vowels and count it: ')
while not phrase:
print('Phrase is empty, please try again')
phrase = input('Enter a phrase to find vowels and count it: ')
print([{pattern:len(re.findall(pattern, phrase))} for pattern in 'aeyuio'])
| true |
2cf324ff75aad67c528a30bc86c29cfa3bfb167f | kojicovski/python | /exercises/ex035.py | 233 | 4.125 | 4 | a = int(input('Value a: '))
b = int(input('Value b: '))
c = int(input('Value c: '))
if a > b-c and a < b+c and b > a-c and b < a+c and c > a-b and c < a+b:
print('You can do a triangle')
else:
print('You cant do a triangle') | false |
6fd37514ac6e3d8425ed3646191bfd539b2947b5 | nurlan5t/python-homeworks | /hw15_queue в ООП варианте.py | 551 | 4.21875 | 4 | ''' Написать queue в ООП варианте. В классе должно быть
состояние хранящее со списком и метод pop()'''
from collections import deque
class My_list():
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued from the queue")
print(q.pop())
print(q.pop())
print(q.pop())
print("\nQueue after removing elements")
print(q)
My_list()
| false |
20e59d6494ba4c87140ccf88af9e846164ce0596 | vikas-ukani/Hacktoberfest_2021 | /Rock_Paper_Scissors.py | 1,368 | 4.28125 | 4 | import random
print("Welcome to rock paper scissors game .....")
print("You have three chances greater the wins in individual game will increase your chance to win")
print("Press 0-->paper , 1-->rock , 2-->scissors")
comp = 0
player = 0
for i in range(3):
player_choice = input("Your turn")
comp_choice=random.randint(0,2)
print(f"you chose\t{player_choice} and computer chose\t{comp_choice}")
if int( player_choice) >2:
print("Enter number between 0,1,2")
break
if comp_choice == player_choice:
print("Its a tie.")
comp = comp + 1
player = player+ 1
if comp_choice == 0:
if player_choice == 1:
print("Computer wins.")
comp = comp + 1
else:
print("You win.")
player = player+ 1
elif comp_choice == 1:
if player_choice == 2:
print("Computer wins.")
comp = comp + 1
else:
print("You win.")
player = player+ 1
elif comp_choice == 2:
if player_choice == 0:
print("Computer wins.")
comp = comp + 1
else:
print("You win.")
player = player+ 1
if int(player) > int(comp):
print("Hurray!!You win!!!")
else:
print("Computer wins!! Better luck next time !!")
| true |
3f7c545c8765583c918074b6c73f4114522a1d2b | emmanuelnaveen/decision-science | /date_format.py | 292 | 4.3125 | 4 | from datetime import date
# Read the current date
current_date = date.today()
# Print the formatted date
print("Today is :%d-%d-%d" % (current_date.day,current_date.month,current_date.year))
# Set the custom date
custom_date = date(2021, 05, 20)
print("The date is:",custom_date) | true |
49c046a92870d3f128849c8ad0452ca7c71c75f1 | SruthiM-10/5th-grade | /Programs/reverseName.py | 275 | 4.21875 | 4 | s=input("What is your first name?")
f=input("What is your middle name if you have one? If you don't have a middle name, just type no")
r=input("What is your last name?")
if f=="no":
print("Your name in reverse is",r,s)
else:
print("Your name in reverse is",r,f,s,)
| true |
8d138c56ac0215a1ea4dabd2ccf7d575b09c6d9c | VDK45/Full_stack | /Lesson_1/Lesson 1 Task 5.py | 1,288 | 4.28125 | 4 | """
5. Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма
(прибыль — выручка больше издержек, или убыток — издержки больше выручки).
Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
Далее запросите численность сотрудников фирмы
и определите прибыль фирмы в расчете на одного сотрудника.
"""
revenue = float(input("Выручки: "))
costs = float(input("Издержек: "))
result = revenue - costs
if result > 0:
print(f'Прибыль компании составляет: {result}')
print(f'Рентабельность выручки: {result / revenue:3f}')
elif result < 0:
print(f'У компании убытки: {-result}')
else:
print(f'Компания работает без прибыли')
| false |
e0c98e27237e12afd4485ef4c188a6fb0bf22479 | VDK45/Full_stack | /Lesson_4/lesson4Task7.py | 1,115 | 4.21875 | 4 | """
7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом:
for el in fact(n). Функция отвечает за получение факториала числа,
а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24.
"""
#------------
def fact(n):
f = 1
for i in range(1, n+1):
f = f * i
yield f
for el in fact(int(input('Enter number: '))):
print(el)
#-------------
from math import factorial
n = int(input('Enter n: '))
def fact(n):
yield factorial(n)
for el in fact(n):
print(el)
| false |
513a9d0167adda155e9f267aab31db2b75f4e441 | dulalsaurab/Graph-algorithm | /plot.py | 418 | 4.1875 | 4 | ''' This file will plot 2-d and 3-d points'''
import numpy as np
import matplotlib.pyplot as plt
# drawing lines between given points iteratively
def draw_line(array):
data = array # array should be of format [(),(),(),()]
# 2D ploting using matplotlib
def plot_2D(array, size):
# array should be of format [(),(),(),()]
data = array
x, y = zip(*data)
plt.scatter(x, y, size)
plt.show()
| true |
7fd8d5fa17e95775f7fe83d7e1259259555bf4e0 | nidjaj/python-basic-codes | /noispositive.py | 503 | 4.15625 | 4 | # if function
x=int(input("enter a no."))
if x>0:
print("%d is positive"%x)
if x<0:
print("%d is negative"%x)
if x==0:
print("%d is zero"%x)
# if else function
x=int(input("enter a no."))
if x>0: #we also use paranthesis'()'
print("%d is positive"%x)
else:
print("%d is negative"%x)
# elif function
x=int(input("Enter a no."))
if x>0:
print("no. is positive")
elif x<0:
print("no. is negative")
else:
print("no. is zero")
| false |
950fb0e048a560043577605d9642d69808f974da | Rohitha92/Python | /Sorting/BubbleSort.py | 774 | 4.1875 | 4 | #Bubble sort implementation
#multiple passes throught the list.
##Ascending order
def bubble_sort(arr):
swapped = True
while(swapped):
swapped = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1]= temp
swapped = True
return arr
#Optimized solution:
#faster since we do not move comparing throughout the array every iteration.
def bubble_sort2(arr):
n= len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j]> arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1]= temp
swapped = True
if swapped == False:
break
return arr
x = [1,5,10,2,5,23,11]
print(bubble_sort2(x)) | true |
7216c73c1532bb08e436447f01903f98e7be6660 | Rohitha92/Python | /StacksQueuesDeques/Queue.py | 578 | 4.21875 | 4 | #Implement Queue
#First in First out
#insert items at the First (zero index)
#delete from first (zero index)
class Queue(object):
def __init__(self):
self.items=[]
def enqueue(self,val): #add to the rear
self.items.insert(0,val)
def size(self):
return len(self.items)
def isempty(self):
return self.items == []
def dequeue(self): #removes from the front
if self.isempty():
return "queue empty"
return self.items.pop()
a = Queue()
a.enqueue(3)
a.enqueue(4)
print(a.dequeue())
print(a.dequeue())
print(a.dequeue()) | true |
dbab87656743bc392657697bd944b8df9e1fea4d | duarte15/exercicioProva4 | /Questão3- Letícia Duarte.py | 353 | 4.125 | 4 | #QUESTAO3
print("Funes recursivas so funes que chamam a si mesma de forma que, para resolver um problema maior, utiliza a recurso para chegar as unidades bsicas do problema em questo e ento calcular o resultado final.\n Exemplo:")
def fatorial(n):
if (n==1):
return (n)
return fatorial(n-1)*n-1
print(fatorial(5))
| false |
2decca9c52862f63ebf355efab54d0446c2147b8 | Shubhamditya36/python-pattern-programs | /a.7.1.py | 267 | 4.40625 | 4 | # PROGRAM TO PRINT FLOYD'S TRIANGLE (PRINTING NUMBERS IN RIGHT TRIANGLE SHAPE)
# EXAMPLE :
#
# 1234
# 567
# 89
# 10
n=int(input("enter a number:"))
num=1
for row in range(n,0,-1):
for col in range(0,row-1):
print(num,end="")
num+=1
print()
| false |
7aeba56b0611f7db71a27daf3cb8f007273cdbc2 | Shubhamditya36/python-pattern-programs | /a13.py | 391 | 4.1875 | 4 | # PROGRAM TO PRINT PATTERN GIVEN BELOW.
# 1
# 2 1 2
# 3 2 1 2 3
# 4 3 2 1 2 3 4
# 5 4 3 2 1 2 3 4 5
num=int(input ("enter a number of rows:"))
for row in range(1,num+1):
for col in range(0,num-row+1):
print(end=" ")
for col in range(row,0,-1):
print(col,end=" ")
for col in range(2,row+1):
print(col,end=" ")
print()
| true |
68d99566855facd7d1fb225b65ec1a72ba804178 | Shubhamditya36/python-pattern-programs | /a22.py | 757 | 4.125 | 4 | # PROGRAM TO PRINT PATTERN GIVEN BELOW.
# 5 5 5 5 5 5 5 5 5
# 5 4 4 4 4 4 4 4 5
# 5 4 3 3 3 3 3 4 5
# 5 4 3 2 2 2 3 4 5
# 5 4 3 2 1 2 3 4 5
# 5 4 3 2 2 2 3 4 5
# 5 4 3 3 3 3 3 4 5
# 5 4 4 4 4 4 4 4 5
# 5 5 5 5 5 5 5 5 5
N=int(input(" enter a number of rows;"))
k=(2*N)-1
low=0
high=k-1
value=N
matrix=[[0 for i in range(k)] for j in range(k)]
for i in range(N):
for j in range (low,high+1):
matrix[i][j]=value
for j in range (low+1,high+1):
matrix [j][i]=value
for j in range (low+1,high+1):
matrix[high][j]=value
for j in range (low+1,high):
matrix [j][high]=value
low=low+1
high=high-1
value=value-1
for i in range(k):
for j in range(k):
print(matrix[i][j],end=" ")
print()
| false |
6539173b858b23d1e0ce6daa4431edc7c0c8761b | svigstol/100-days-of-python | /days-in-a-month.py | 1,522 | 4.21875 | 4 | # 100 Days of Python
# Day 10.2 - Days In A Month
# Enter year and month as inputs. Then, display number of days in that month
# for that year.
# Sarah Vigstol
# 5/31/21
def isLeap(year):
"""Determine whether or not a given year is a leap year."""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def daysInMonth(year, month):
"""Check if the given year is a leap year, then returns the
number of days in the given month."""
monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if isLeap(year) == True and month == 2:
return 29
return monthLength[month - 1]
while True:
year = int(input("Enter a year: "))
month = int(input("Enter a month (1-12): "))
monthNames = {
1:"January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "Novemeber",
12: "December"
}
if month <= 12 and month >= 1:
for key in monthNames:
if key == month:
monthName = monthNames.get(key)
days = daysInMonth(year, month)
print(f"\nThere were {days} days in {monthName} of {year}.")
break
elif month > 12 or month < 1:
print("Invalid month. Try again.\n")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.