blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eac159ff8c50faa733d1ecba742828e1eac76858 | Mr-OMD/bz304-system-programming-midterm | /ikinci.py | 1,355 | 4.28125 | 4 | #1030530259
#ÖMER MERT DEMİREL
print("Çeviriciye Hoşgeldin!")
veri=input("\nLütfen yazınız: ") #takes input from user
print(yazi:="\nverinin uzunluğu", len(veri), "birim") #with help of WALRUS operator we can calculate lenght in print
secenek=input("\nveriyi neye dönüştürmek istersiniz?(LÜTFEN GEÇERLİ VERİ TİPİ SEÇİN)\n1-integer\n2-string\n3-float\n4-complex\nSeçiniz: ")
secenek=int(secenek) #converts type of input according to user`s choice.
if secenek==1: #we need to convert secenek to integer because we cant use comparasion operators
veri=int(veri) #type converting
tip=type(veri) #type verifying
print(veri, "veri tipi:", tip)
elif secenek==2:
print(veri, "zaten bir string tipinde") #since we take it from input func, it is already a string
tip=type(veri)
elif secenek==3:
veri=float(veri) #type converting
tip=type(veri) #type verifying
print(veri, "veri tipi:", tip)
elif secenek==4:
veri=complex(veri) #type converting
tip=type(veri) #type verifying
print(veri, "veri tipi:", tip)
else:
print("\nyanlış secenek seçtiniz!")
tip=type(veri)
kimlik=id(veri) # we can learn our variable`s id number in python
yazi=("\nSonuc: {} verisi {} tipinde ve python 'id' numarası: {}")
print(yazi.format(veri,tip,kimlik)) | false |
561f8099654f1753fcf261095177d7b599aae3ea | bmoretz/Daily-Coding-Problem | /py/dcp/problems/dynamic/staircase.py | 1,115 | 4.4375 | 4 | '''Number of ways to climb a staircase.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
'''
def staircase1(n, X):
def staircase(n, X):
if n < 0:
return 0
elif n == 0:
return 1
else:
return sum(staircase(n - step, X) for step in X)
return staircase(n, X)
def staircase2(n, X):
def staircase(n, X):
if n < 0:
return 0
elif n == 0:
return 1
elif n in X:
return 1 + sum(staircase(n - x, X) for x in X if x < n)
else:
return sum(staircase(n - x, X) for x in X if x < n)
return staircase(n, X) | true |
fd30b62e24e537c9d9aecda7c5684e2a48bae4a6 | bmoretz/Daily-Coding-Problem | /py/dcp/leetcode/linkedlist/deep_copy_random.py | 2,173 | 4.125 | 4 |
'''
138. Copy List with Random Pointer.
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:
Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.
Constraints:
-10000 <= Node.val <= 10000
Node.random is null or pointing to a node in the linked list.
The number of nodes will not exceed 1000.
'''
class ListNode:
def __init__(self, val, nxt : 'ListNode' = None, random : 'ListNode' = None) -> 'ListNode':
self.val = val
self.next = nxt
self.random = random
def build_random_list(values : list[list[int]]) -> ListNode:
sentinel = ListNode(0)
node, nodes = sentinel, {}
for index, val in enumerate(values):
node.next = ListNode(val[0])
node = node.next
nodes[index] = node
for index, val in enumerate(values):
rnd_ptr = val[1]
if rnd_ptr:
nodes[index].random = nodes[rnd_ptr]
return sentinel.next
def copyRandomList(head: ListNode) -> ListNode:
sentinel = ListNode
new_node = sentinel
node, seen = head, {}
while node:
new_node.next = ListNode(node.val)
seen[node] = new_node.next
node, new_node = node.next, new_node.next
node = head
for _ in range(len(seen)):
if node.random:
seen[node].random = seen[node.random]
node = node.next
return sentinel.next | true |
d86beb66b939aef66b3dda13f1c67910396c4284 | bmoretz/Daily-Coding-Problem | /py/dcp/leetcode/matrix/diagonal_traverse.py | 1,070 | 4.125 | 4 |
'''
498. Diagonal Traverse.
Given a matrix of M x N elements (M rows, N columns), return all
elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
'''
def findDiagonalOrder(matrix : list[list[int]]) -> list[int]:
from collections import defaultdict, deque
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
num_rows, num_cols = len(matrix), len(matrix[0])
ht = defaultdict(deque)
for row in range(num_rows):
for col in range(num_cols):
s = row + col
if s % 2:
ht[s].appendleft(matrix[row][col])
else:
ht[s].append(matrix[row][col])
index, result = 0, []
while ht[index]:
while ht[index]:
result.append(ht[index].pop())
index+=1
return result | true |
7f9c125e8e64b1db69cd0725ff1ab8a5d70e385a | bmoretz/Daily-Coding-Problem | /py/dcp/problems/recursion/triple_step.py | 1,034 | 4.28125 | 4 | """
Triple Step.
A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the stairs.
"""
def triple_step1(n):
def triple_step(n):
if n < 0:
return 0
if n == 0:
return 1
else:
return triple_step(n - 3) + triple_step(n - 2) + triple_step(n - 1)
return triple_step(n)
def triple_step2(n):
def triple_step(n, step_counts=[]):
if step_counts == []:
step_counts = [0] * (n + 1)
if n < 0:
return 0
elif n == 0:
return 1
elif step_counts[n] != 0:
return step_counts[n]
else:
total = 0
total += triple_step(n - 3, step_counts)
total += triple_step(n - 2, step_counts)
total += triple_step(n - 1, step_counts)
step_counts[n] = total
return step_counts[n]
return triple_step(n) | true |
b3c7f5e853458690c0528815b3dcf4b763569829 | bmoretz/Daily-Coding-Problem | /py/dcp/problems/math/rand_5n7.py | 1,391 | 4.3125 | 4 | """
Rand7 from Rand5.
Implement a method rand7() given rand5(). That is, given a
method that generates a random number between 0 and 4 (inclusive),
write a method that generates a random number between 0 and 6
(inclusive).
"""
from random import randrange
def rand5():
return randrange(0, 5)
"""
rand7 1
simple / deterministic, does not generate a uniform
distribution though.
"""
def rand7_1():
a, b = rand5(), rand5()
n = (a + b) % 7
return n
"""
rand7 2
somewhat more complicated, and also non-deterministic (unknown loops
before we get a result, but it will complete). we generate a number
between 0-8 using rand5, then scale it by 5. we discard anything >
20 (21 values inc zero), and then mod the result to put it in the
range. Produces uniform range.
"""
def rand7_2():
while True:
a, b = rand5(), rand5()
n = 5 * a + b
if n < 21:
return n % 7
"""
rand7 3
most complicated and also non-deterministic. Generate the even
numbers between 0 and 9 (2*rand5), and then an additional rand
that must be between 0 and 3 (to maintain the distribution),
then mod b to get a 1 or a zero. finally, n will be in range 0-9,
so we discard > 7.
"""
def rand7_3():
while True:
a, b = 2 * rand5(), rand5()
if b != 4:
r = b % 2
n = a + r
if n < 7:
return n | true |
3e2b3173d94ca20e83dadb4dea98d4b181823e5e | bmoretz/Daily-Coding-Problem | /py/dcp/problems/stack_queue/queue_of_stacks.py | 747 | 4.21875 | 4 | """
Queue of Stacks.
Implement a MyQueue class which implements a queue using two stacks.
"""
from .stack import Stack
class my_queue1():
def __init__(self):
self.data = Stack()
self.top = None
def enqueue(self, item):
if item is None: return
self.data.push(item)
if self.top == None:
self.top = item
def dequeue(self):
if self.data.is_empty() : return None
temp = Stack()
while not self.data.is_empty():
temp.push(self.data.pop())
item = temp.pop()
self.top = temp.peek()
while not temp.is_empty():
self.data.push(temp.pop())
return item
def peek(self):
return self.top
def is_empty(self):
return self.data.is_empty() | true |
38a0300e0534dafcde09dbb4aadc78d83aa3f576 | astikagupta/HW04 | /HW04_ex08_12.py | 442 | 4.25 | 4 | # Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 12 for guidance
# Please do provide function calls that test/demonstrate your function
def rotate_word(x,y):
for i in x:
z = ord(i)
w = z+y
print chr(w),
def main():
x = raw_input("enter the string:")
y = int(raw_input("enter the count by which you want to rotate the letters"))
rotate_word(x,y)
if __name__ == '__main__':
main() | true |
f7c7428ea359a51853286191f0a33900cfcb1a98 | marshall159/travelling-Salesman | /cities.py | 2,514 | 4.1875 | 4 | def read_cities(file_name):
# no unit tests
"""
Read in the cities from the given `file_name`, and return
them as a list of four-tuples:
[(state, city, latitude, longitude), ...]
Use this as your initial `road_map`, that is, the cycle
Alabama -> Alaska -> Arizona -> ... -> Wyoming -> Alabama.
"""
fin = open(file_name)
cities_list = []
for line in fin:
#print(line)
cities_list.append(line.split('\t'))
for city in cities_list:
print(city)
def print_cities(road_map):
# no unit tests
"""
Prints a list of cities, along with their locations.
Print only one or two digits after the decimal point.
"""
pass
def compute_total_distance(road_map):
"""
Returns, as a floating point number, the sum of the distances of all
the connections in the `road_map`. Remember that it's a cycle, so that
(for example) in the initial `road_map`, Wyoming connects to Alabama...
"""
pass
def swap_adjacent_cities(road_map, index):
"""
Take the city at location `index` in the `road_map`, and the city at
location `index+1` (or at `0`, if `index` refers to the last element
in the list), swap their positions in the `road_map`, compute the
new total distance, and return the tuple
(new_road_map, new_total_distance)
"""
pass
def swap_cities(road_map, index1, index2):
"""
Take the city at location `index` in the `road_map`, and the
city at location `index2`, swap their positions in the `road_map`,
compute the new total distance, and return the tuple
(new_road_map, new_total_distance)
Allow for the possibility that `index1=index2`,
and handle this case correctly.
"""
pass
def find_best_cycle(road_map):
"""
Using a combination of `swap_cities` and `swap_adjacent_cities`,
try `10000` swaps, and each time keep the best cycle found so far.
After `10000` swaps, return the best cycle found so far.
"""
pass
def print_map(road_map):
# no unit tests
"""
Prints, in an easily understandable format, the cities and
their connections, along with the cost for each connection
and the total cost.
"""
pass
def main():
# no unit tests
"""
Reads in, and prints out, the city data, then creates the "best"
cycle and prints it out.
"""
read_cities('city-data-test-file-4-cities.txt')
if __name__ == "__main__":
main()
| true |
247d50c60eaf082d50dc124c9383cf8ed3af9be0 | 1666202295/test | /knowledge/python_map.py | 1,635 | 4.28125 | 4 | # python 中的字典 相当于java中的map 数据结构为key-values
# 保存加菲猫的信息并进行存取操作
# 数组使用大括号声明 格式为{"key":"value","key":"value"...} 相当于json
myCat = {"name": "Garfield", "color": "orange", "size": "fat"}
# 取值使用 中括号 包裹key的形式
print("My cat's name is :", myCat["name"])
# 通过 中括号 包裹key = value 进行字典的赋值
myCat["city"] = "Xiamen"
print(myCat)
# 修改字典中的值同添加相同
myCat["color"] = "orange tabby"
print(myCat)
# 获取字典中的所有Values 值
print(myCat.values())
# for 循环遍历Values
for v in myCat.values():
print(v, end=",")
print()
# 获取字典的所有key
print(myCat.keys())
# for 循环遍历key
for k in myCat.keys():
print(k, end=", ")
print()
# 获取字典的条目
print(myCat.items())
# 循环打印字典的所有条目
for i in myCat.items():
print(i, end=", ")
print()
# 判断字典是否包含某个key in
print("Is there a city:", "city" in myCat.keys())
print("Is there a city:", "city" in myCat)
# 判断字典是否包含某个value
print("Is there a city:", "Xiamen" in myCat.values())
# 字典取值缺省值 如果字典中包含标识的key值,则返回key对应的Value
# 如果不存在 则返回缺省值
print(myCat.get("sex", "not find"))
print(myCat.get("city", "not find"))
# 删除 字典中 的某个key
del myCat["city"]
print(myCat)
# setdefault 方法 如果数组中没有这个key,则添加,如果有则保留原值
myCat.setdefault("age", "3")
myCat.setdefault("age", "5")
print(myCat)
# 清除字典
myCat.clear()
print(myCat)
| false |
408fe1cb12b633f09f4a21b8801c678c5f3b021c | verilogtester/pyalgo_love | /TREE_traversal_Iterative_approach.py | 2,371 | 4.34375 | 4 | # Python program to for tree traversals (This is Iterative Approach)
# A class that represents an individual node in a
# Binary Tree
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
# A function to do inorder tree traversal
#
def iter_printInorder(root):
if root == None:
return
result = []
stack = []
node = root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
result.append(node.val)
node = node.right
print (result)
# A function to do preorder tree traversal
# The nodes values are appended to the result list in traversal order
def iter_printPreorder(root):
if root is None:
return
result = []
stack = []
stack.append(root)
while stack:
node = stack.pop()
result.append(node.val)
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
print (result)
# A function to do postorder tree traversal
# each node is visited twice. we use a previous variable to keep track
# of the earlier traversed node
def iter_printPostorder(root):
if root == None:
return
result = []
visited = set()
stack = []
node = root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
if node.right and not node.right in visited:
stack.append(node)
node = node.right
else:
visited.add(node)
result.append(node.val)
node = None
print (result)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
'''
Input:
1(ROOT)
2 3
4 5
Output:
Preorder traversal of binary tree is
[1, 2, 4, 5, 3]
Inorder traversal of binary tree is
[4, 2, 5, 1, 3]
Postorder traversal of binary tree is
[4, 5, 2, 3, 1]
'''
print ("Preorder traversal of binary tree is")
iter_printPreorder(root)
print ("\nInorder traversal of binary tree is")
iter_printInorder(root)
print ("\nPostorder traversal of binary tree is")
iter_printPostorder(root)
| true |
0bd775286b5335f1ff414be9f32c36cb95a08a89 | gopinathrajamanickam/PythonDS | /isAnagram.py | 940 | 4.125 | 4 | # Validate Anagram
# given two strings as input Check if they can be considered anagrams
# i.e the letters in those stringss to be rearranged to form the other
def isAnagram(str1,str2):
# if the letter freq count is same for given strings it can be called anagrams
result = 'Not Anagrams'
freq_dict = {}
s1 = set(str1)
s2 = set(str2)
if len(str1) == len(str2) and len(s1) == len(s2):
for char in s1:
freq_dict[char] = str1.count(char)
for char in s2:
if char in s1 and freq_dict[char] == str2.count(char):
result = 'Anagrams'
else:
result = 'Not Anagrams'
break
return result
if __name__ == "__main__":
inp_list = [('a','a'),('abb','baa'),('abc','cbwa'),('s','a')]
for inp in inp_list:
# print(inp[0])
print(" {0} and {1} are {2}.".format(inp[0], inp[1] , isAnagram(inp[0],inp[1])))
| true |
a45e3ad473e925a83e631efb7890d5b952de5120 | njgupta23/LeetCode-Challenges | /array/rotate-arr.py | 601 | 4.125 | 4 | # Rotate Array
# Given an array, rotate the array to the right by k steps, where k is non-negative.
# Example 1:
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
def rotate(nums, k):
if len(nums) == 1:
return
for i in range(k):
save = nums[0]
nums[0] = nums[-1]
for j in range(len(nums)-1, 1, -1):
nums[j] = nums[j-1]
nums[1] = save
| true |
2d3f1e2d5077308ba207b3a2334863a3a97240e7 | hostjbm/py_gl | /T2. OOP/Class decorator/func_decoratoration_by_class.py | 508 | 4.21875 | 4 | # Basic example of decorator defined by class
class decorator():
def __init__(self, func):
print(10)
self.func = func
def __call__(self, *args):
print('Called {func} with args: {args}'.format(
func=self.func.__name__, args=args))
print(self, args)
return self.func(*args)
@decorator
def my_func(x, y):
print('Function called')
return x, y
if __name__ == '__main__':
# Basic example of decorator defined by class
my_func(1, 2)
| true |
efadbaf73428bcfd21f780a19e642b166187c8d7 | Maulik5041/PythonDS-Algo | /Recursion/power_of_a_number.py | 219 | 4.375 | 4 | """Power of a number using Recursion"""
def power(base, exponent):
if exponent == 0:
return 1
else:
return base * power(base, exponent - 1)
if __name__ == '__main__':
print(power(2, 3))
| true |
2669d1f73ba380e65ae02213e498b1c4933325c7 | Maulik5041/PythonDS-Algo | /Interview Prep 1/Stacks, Queues and Deques/queue_implementation.py | 731 | 4.3125 | 4 | """Implement a Queue"""
class Queue:
def __init__(self):
self.queue = []
def size(self):
return len(self.queue)
def is_empty(self):
return self.size() == 0
def enqueue(self, data):
self.queue.insert(0, data)
def dequeue(self):
if self.is_empty():
return
return self.queue.pop()
q = Queue()
print(f"Size = {q.size()}")
q.enqueue(-1)
q.enqueue(78)
q.enqueue(0)
q.enqueue(34)
print(f"Dequeue = {q.dequeue()}")
print(f"Dequeue = {q.dequeue()}")
q.enqueue(100)
q.enqueue(-45)
print(f"Dequeue = {q.dequeue()}")
print(f"Dequeue = {q.dequeue()}")
print(f"Dequeue = {q.dequeue()}")
print(f"Dequeue = {q.dequeue()}")
print(f"Size = {q.size()}")
| false |
7d9d43833516f1d63cac72274c64df2f2eed1a53 | poojamadan96/code | /function/factUsingRecursive.py | 219 | 4.375 | 4 | #factorial using recursive function = Fucntion which calls itself
num=int(input("Enter no. to get factorial "))
def fact(num):
if num==1:
return 1
else:
return num*fact(num-1)
factorial=fact(num)
print(factorial) | true |
4c674205b17034de9aceb8207607ad0e06e4ac6a | ssilverch/study | /pythonProject/day7/test4.py | 666 | 4.1875 | 4 | def main():
list1 = ['orange','apple','zoo','internationalizetion','blueberry']
list2 = sorted(list1)
#sorted函数返回列表排序后的拷贝不会修改传入的列表
#函数的设计就应该想sorted函数一样尽可能不产生副作用
list3 = sorted(list1,reverse=True)
#通过key关键字参数指定根据字符串长度进行排序而不是默认的字母表顺序
list4 = sorted(list1,key=len)
print(list1)
print(list2)
print(list3)
print(list4)
#给列表对象发出排序消息直接在列表对象上进行排序
list1.sort(reverse=True)
print(list1)
if __name__ == '__main__':
main()
| false |
8488fe451236b0a386f4a6b27d9908d5ecd27f74 | VPoint/PythonExperiments | /Labs/Labo2.py | 1,461 | 4.125 | 4 | from math import sqrt
#################### Excercise 1 ##########################
print ("*************Division des entiers*************")
x = int(input("Taper un nombre: "))
y = int(input("Et un autre: "))
print("Le division de", x, "par", y, "est", x//y, "avec", x%y,"qui reste.")
#################### Excercise 2 ##########################
print ("*************Changer le temperature*************")
celsius = float(input("Mettre un temperature en celsius: "))
def deCenF(cel):
far = (cel)*9.0/5.0 + 32
return far
farenheit = deCenF(celsius)
print(celsius, "celsius egal", farenheit,"farenheit.")
#################### Excercise 3 ##########################
print ("*************Calculer ton note*************")
devoirsMoyenne = float(input("Devoirs: "))
partiel = float(input("Partiel: "))
examen = float(input("Examen: "))
def calculNote(devoir, part, exam):
note = devoir*(25.0/100.0) + part*(25.0/100.0) + exam*(50.0/100.0)
return note
print ("Note: " + str(calculNote(devoirsMoyenne, partiel, examen)))
#################### Excercise 4 ##########################
print ("*************Calculer la surface d'un triangle*************")
côté_1 = float(input("Côté 1: "))
côté_2 = float(input("Côté 2: "))
côté_3 = float(input("Côté 3: "))
def calculeSurface(A, B, C):
p = A + B + C
s = sqrt(p*(p-2*A)*(p-2*B)*(p-2*C))/4
return s
aire = calculeSurface(côté_1,côté_2,côté_3)
print("Aire: " + str(aire))
| false |
89e7001639f286cbf0b2548e6d9f305014c34da7 | Sammybams/30-days-of-code-Intermediate-May | /Day 7.py | 1,409 | 4.34375 | 4 | def my_cars(array):
"""
You come to the garage and you see different cars parked there in a straight line.
All the cars are of different worth.
You are allowed to choose any amount of cars and they will be yours.
The only condition is that you can't select 2 cars that are parked beside each other.
i.e There must be at least one car between any 2 cars you choose.
Given an array where the elements are arranged in order of the cars and the magnitude of each element is the worth of the car,
the function 'my_cars' takes in the array and returns the maximum worth of cars you can get from the GeekTutor.
"""
if isinstance(array,list):
#This checks for errors with input.
for i in array:
if not isinstance(i,int):
raise AssertionError("Invalid input.")
array1,array2,total = ([] for i in range(3))
#Checks for numbers that are not side by side and appends them to their correspoding list.
for i in range(len(array)):
if i%2==0:
array1.append(array[i])
else:
array2.append(array[i])
#Adds the two lists to a new list as sublists.
total.append(array1)
total.append(array2)
else:
raise AssertionError("Invalid input.")
return sum(max(total, key=sum)) #Returns the sum of the list with the maximum worth.
| true |
f247b7b39e29eb00ccec00eff7350942bce88bbf | lucianahb/marketplace-tech-start | /.vscode/20.12.04/poo-basico.py | 1,054 | 4.15625 | 4 | class Pessoa:
nome = 'luciana'
sobrenome = 'barbosa'
idade = 25
#quando quero que outras pessoas usem minha classe
#devo criar uma variável pra ela
p = Pessoa()
print(p)
#só que assim só vai pegar onde tá na memória, então:
print(p.nome)
print('...............\n')
#Maaaas, por padrão, não defino valores pra classe, pra proteger ela
#(type hinting) = dica de tipo, não é obrigatório o tipo
class PessoaCerta:
__nome : str
sobrenome : str
idade : int
#Funções em python: e uso o self pq ele tá dentro do escopo
def nome_completo(self) -> None:
print(self.nome + ' ' + self.sobrenome)
def get_idade(self)->int:
return self.idade
def set_idade(self, idade:int)-> None:
self.idade = idade
p1 = PessoaCerta()
p1.nome = 'LUCIANA'
p1.sobrenome = 'HEIT'
p1.set_idade(25)
print(p1.nome_completo())
print(p1.get_idade())
#um underline antes da variável é protegido: _nome
#2 underline antes da variável é privado: __nome
p = Pessoa()
p.set_idade(10)
print(p.ge) | false |
f981a1ee2c36b151e2834ec47d8d97069c536991 | rithwikgokhale/SimpleCalculator | /PA1_Question1.py.py | 1,042 | 4.1875 | 4 | #Python Script to solve quadratic equations and give the solutions
print ("Quadratic Equations: ax^2+bx+c = 0")
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # this is the discriminant for the entered quadratic equation
e = str(a)+("x^2+")+str(b)+("x+")+str(c) #This is the quadratic equation
from math import sqrt
if d < 0: #Applicable only if the discriminant is less than zero
print ("The equation: "), e, ("has no real solution.")
elif d == 0: #Applicable only if the discriminant is equal to zero
x = (-b+sqrt(b**2-4*a*c))/2*a
print ("The equation: "), e, ("has one solution. ")
print ("Solution 1: "), x
else: #Applicable only if the discriminant is greater than zero
x1 = (-b+sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-sqrt((b**2)-(4*(a*c))))/(2*a)
print ("The equation: "), e, ("has two solutions. ")
print ("Solution 1: "), x1
print ("Solution 2: "), x2
| true |
28c4462f2efdd143096fb430d96ac12ba94af4f0 | JoshKallagunta/ITEC-2905-Lab-1 | /Lab1.py | 276 | 4.28125 | 4 |
name = input("What is your name? ")
birthMonth = input("What month were you born?")
print("Hello " + name + "!")
count = len(str(name))
print("There are " + str(count) + " characters in your name!")
if birthMonth == "August":
print("Happy birthday month!")
else: ""
| true |
74f94a7bdd8d2ab3d45348c299f6cd1f0aa97e50 | carpepraedam/data_structures | /sorting/Bubble_Sort/python/bubble.py | 1,256 | 4.15625 | 4 | def comparator(val_a, val_b):
"""
Default comparator, checks if val_a > val_b
@param {number} val_a
@param {number} val_b
@return {bool} : True if val_a > val_b else False
"""
return val_a > val_b
def bubble(l, comparator=comparator):
"""
Bubble sort a given list
@param {list} l - the list to sort
@param {function(arg_a, arg_b)} - comparator
function reference
If return value is True, indices with values arg_a and arg_b will be swapped
Default:
comparator(val_a, val_b):
return val_a > val_b
@return {tuple(list, number)} - (sorted list, number of iterations)
"""
# outer bubble
sweeps = 0
for i in range(len(l) - 1, 0, -1):
sweeps += 1
is_sorted = True
for j in range(i):
if(comparator(l[j], l[j+1])):
is_sorted = False
swap(l, j, j+1)
if is_sorted:
break
return (l, sweeps)
def swap(l, index_a, index_b):
"""
Swaps two index in a list
@param {list} l - the list
@param {number} index_a - The first index
@param {number} index_b - The second index
"""
tmp = l[index_a]
l[index_a] = l[index_b]
l[index_b] = tmp
| true |
db56a2db15dd354a3e2b832f7be1887d2b139433 | Donal-Murphy/EP305-Computational-Physics-I | /Labwork/cone_area(5_3_19)/cone_area.py | 1,493 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 14:04:56 2019
@author: Donal Murphy
Description: returns the surface area of a cone given its height and radius
"""
#this program calculates the surface area of a cone given the radius and height
import numpy as np #needed for pi
#-----------------------------------------------------------------------------#
#define the function cone_area()
def cone_area(r_value, h_value):
#slant legth = sqrt(r**2 + h**2)
return (np.pi*r_value*((r_value**2 + h_value**2)**(1/2)) +np.pi*r_value**2)
#-----------------------------------------------------------------------------#
#main program starts here
#inform the user what is happening
print('\nThis programme calcuates the surface area of a cone of radius, r, \
and height, h. \
\nIt uses a USER DEFINED function')
ans = 'Y' #use the program at least once
while ans == 'Y':
#prompt the user for the radius
c_radius = float(input('\nEnter the radius of the cone in meters \
(e.g., 2.1) : '))
#and height
c_height = float(input('Enter the height of the cone in meters \
(e.g., 3.4) : '))
#call the function cylinder_vol
c_area = cone_area(c_radius, c_height)
#output the results
print('\nThe surface area of the cone is', \
'{0:10.3f}'.format(c_area), 'meters\xb2')
ans = input('\nDo you want to try another cone? (Y/N) ') | true |
06e04411c77035b2330f2a17f7ad5e17a3f04a33 | mfjimenezmoreno/eLOAD_Bipotentiostat | /Python app/SortingTuples.py | 268 | 4.21875 | 4 | c = {'a':10,'b':1,'c':22}
#A supercompressed way to sort a dictionary by highest values
#items returns keys and values as tuples, then the for iteration flips the tuples value/key, and finally sorted function takes place
print(sorted([ (v,k) for k,v in c.items() ]))
| true |
6c933cbcfe6e2d9906565bf68e69e89c1cb4c5dd | k8thedinosaur/labs | /weather.py | 2,410 | 4.25 | 4 | # # Lab: PyWeather
#
# Create a program that will prompt a user for city name or zip code.
# Use that information to get the current weather. Display that information
# to the user in a clean way.
# ## Advanced
#
# * Also ask the user if they would like to see the results in C or F.
import requests
package = {
"APPID": "848e9a71a4b1c90877841baf319c1b68",
}
# K to F conversion
def k_to_f(temp):
ans = temp * 9/5 - 459.67
ans = int(ans)
return ans
def k_to_c(temp):
ans = temp - 273.15
ans = int(ans)
return ans
def get_weather():
# ask city or zip
city_zip = input("Would you like to search by (city) or (zip)? ")
# conditional loop for either instance
# if city ...
if city_zip == "city":
city_name = input("Enter your city: ")
package["q"] = city_name
# pull from api and write params to local dictionary package
r = requests.post("http://api.openweathermap.org/data/2.5/weather", params=package)
# convert from js object to python dict or maybe the other way around idk
data = r.json()
# pull temp data from package
temp = (data["main"]["temp"])
area = (data["name"])
# give option to display in different units
units = input("Would you like it displayed in (K), (C), or (F)? ")
if units == "F":
# apply k to f and display
print("It is {} degrees F in {}.".format(k_to_f(temp), area))
# apply k to c
elif units == "C":
print("It is {} degrees C in {}.".format(k_to_c(temp), area))
# default is k
else:
print("It is {} degrees K in {}.".format(int(temp), area))
# if zip ...
elif city_zip == "zip":
zipcode = input("Enter your zipcode: ")
package["zip"] = zipcode
r = requests.post("http://api.openweathermap.org/data/2.5/weather", params=package)
data = r.json()
temp = (data["main"]["temp"])
units = input("Would you like it displayed in (K), (C), or (F)? ")
if units == "F":
print("It is {} degrees F in {}.".format(k_to_f(temp), zipcode))
elif units == "C":
print("It is {} degrees C in {}.".format(k_to_c(temp), zipcode))
else:
print("It is {} degrees K in {}.".format(int(temp), zipcode))
else:
print("Invalid response.")
get_weather()
| true |
982dec507c2d8ca14d0ed5f664c84cd716642019 | k8thedinosaur/labs | /dice.py | 1,414 | 4.53125 | 5 | # # Lab: Dice
# ##### Goal
# Write a simple program that, when run, prompts the user for input then prints a result.
# ##### Instructions
# Program should ask the user for the number of dice they want to roll as well as the number of sides per die.
# #### Documentation
# 1. [Compound statements](https://docs.python.org/3/reference/compound_stmts.html)
# 1. [Python Std. Library: Random Module random.randint()](https://docs.python.org/3/library/random.html#random.randint)
# #### Key Concepts
# - Importing
# - The Random Module
# - `for` looping
# - `input()` function
# - programmatic logic
# randint is randrange + 1
# print(randint(1, 10))
# print(randrange(1, 10))
from random import randrange
# testing version
def dice_roll():
while True:
# ask for number of dice
dice = int(input("How many dice would you like to roll? "))
# ask for number of sides
sides = int(input("How many sides do the dice have? "))
# for loop to roll
for i in range(dice):
answer = randrange(1, sides)
print(str(answer))
dice_roll()
# useful version
# dice = int(input("How many dice would you like to roll? "))
# sides = int(input("How many sides do the dice have? "))
#
# def dice_roll():
# # for loop to roll
# for i in range(dice):
# i + 1
# answer = randrange(1, sides)
# return (str(answer))
#
# dice_roll() | true |
ab8e9333def4ba513e483f127020ff6941a8afcb | bj1570saber/muke_Python_July | /chapter_4_data_structure/4-1-basic_list_tuple.py | 1,496 | 4.3125 | 4 | #List example:
students= ['Jerry','Tom','Adm',10, True]
print(students)
print('students[0]:%s' %(students[0])) # Jerry
print('students[-1]:%s' %(students[-1]))#True
print('students[-2]:%s' %(students[-2]))#10
students.append('Jack')#append()
print('students[-2]:%s' %(students[-2]))#True
print(students)# ['Jerry', 'Tom', 'Adm', 10, True, 'Jack']
students.insert(1, 'Bob')#insert()
print(students)#['Jerry', 'Bob', 'Tom', 'Adm', 10, True, 'Jack']
students.pop()#pop
print(students)#['Jerry', 'Bob', 'Tom', 'Adm', 10, True]
students.pop(0)
print(students)#['Bob', 'Tom', 'Adm', 10, True]
print('length: %d' %len(students))#5
students.insert(2,['asp', 'php'])
print(students)#['Bob', 'Tom', ['asp', 'php'], 'Adm', 10, True]
print(students[2][1])#php
sentence = 'I love Python.'
print(sentence[0])#I
print(sentence[-3:])#on.
a = 'a'
b = 'b'
a = a + b
print(a)#ab
print(a*3)
students= ['Jerry','Tom','Adm',10, True]
print(students[0])#Jerry this is a element
print(students[-1:])#[True] this is a list
c = ['c']
d = ['d']
c = c + d
print(c)#['c', 'd']
print(d)#['d']
print(d*3)#['d', 'd', 'd']
#Tuple Example: can not change after create.
print('\nTuple example:')
tuple_1 = (1,2,'string',True)
print(tuple_1) # (1, 2, 'string', True)
# tuple_1[2] = 10 # can not assign
print(tuple_1[2]) # string
print(tuple_1[-1]) # True
tuple_2 = (1) # a variable
print(tuple_2)# output:1
tuple_2 = (1,)# one element tuple
print(tuple_2)# output:(1,)
tuple_3 = () # empty tuple
print(tuple_3)# output:()
| false |
4d3032fabf76ce4f7fc4eb1b7467b811ec879d8b | wendeel-lima/Logica-de-Programacao | /15-06/listas.py | 2,642 | 4.5 | 4 | # Lista é uma variável composta assim como as tuplas, porém com algumas diferenças, vamos ver as caracteristicas de uma lista em python:
# Ao invés de serem representadas com (), são representadas com []
lista = [1,2,3,4]
print(lista)
# Para criar uma lista vazia, faça:
vazia_um = []
# ou
vazia_dois = list()
# As listas podem ser modificadas:
lista[3] = 5
print(lista)
# Para adicionar um novo elemento na lista, eu preciso usar o seguinte comando:
lista.append(6) #Vai adicionar o 6 no final da lista
print(lista)
# Para adicionar um novo elemento em qualquer lugar da lista, utilizo o seguinte comando:
lista.insert(0, 4) # 0 é a posição que vou inserir o 4, aqui ele irá empurar minha lista para frente.
print(lista)
# Para apagar um item da lista, use o comando abaixo:
del lista[3] # Excluir o elemento da posição 3
# ou
lista.pop(3) # Excluir o elemento da posição 3, se eu não colocar a posição ele apaga o ultimo elemento
print(lista)
# Podemos eliminar também pelo valor da posição com o comando:
lista.remove(4) # Vai remover o VALOR 4 que está na posição 0, mas só remove a primeira ocorrência do valor 4.
print(lista)
# SE você remover um valor ou posição que não existe na lista, você irá recber um erro do Pytho, mas para mitigar esse erro, podemos utilizar o IF e o operador IN para verificar se o elemento existe na lista antes de remover:
if 4 in lista: # Se o 4 estiver dentro(in) da lista, faça...
lista.remove(4)
print(lista)
else:
print('Esse elemento não existe na lista')
# Podemos criar uma lista a partir de outro comando, o range:
lista_dois = list(range(4, 11)) # Cria uma lista com numeros de 4 até 10
print(lista_dois)
# Para colocar os itens de uma lista em ordem crescente, utilize o seguinte comando:
crescente = [3,6,2,8,4,9]
crescente.sort()
print(crescente)
# Para colocar em ordem decrescente, utilize:
crescente.reverse()
print(crescente)
#Para saber o tamanho de uma lista, use:
print(len(crescente))
#Ligação de listas:
a = [3,5,7]
b = a #Esse comando liga as listas, então tudo o que eu modificar em uma será modificado em outra
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}')
#Cópia de listas:
a = [3,5,7]
b = a[:] #Esse comando copia todos os elementos da lista a para a b
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}')
# Exemplos extras:
for position, c in enumerate(lista): #Mostrar a posição e o valor da lista
print(f'A posição de {c} é {position}', end = '-')
# end='' substitui o \n implicito do print, colocando todos os elementos na mesma linha, seguido de algum caractere
| false |
5ab59ee03b72e01cfea5efdd98fe3afce1e7594e | wendeel-lima/Logica-de-Programacao | /16-06/ex01lista.py | 1,758 | 4.375 | 4 | # 01 - Dada a lista l = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações:
#l = [5, 7, 2, 9, 4, 1, 3]
# # a) tamanho da lista.
# print(f"O tamano da lista é de {len(l)} posições")
# # b) maior valor da lista.
# print(f"O Maior valor da lista é: {max(l)} ")
# # c) menor valor da lista.
# print(f"O Menor valor da lista é: {min(l)} ")
# # d) soma de todos os elementos da lista.
# print(f" A soma dos valores da lista é {sum(l)}")
# # e) lista em ordem crescente.
# l.sort()
# print(l)
# # f) lista em ordem decrescente.
# l.reverse()
# print(l)
# Desafio da noite:
# Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no final emitir uma classificação sobre a participação da pessoa no crime.
# Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita",
# entre 3 e 4 como "Cúmplice" e 5 como "Assassino".
# Caso contrário, ele será classificado como "Inocente".
# Detetive
perguntas = ["Telefonou para a vítima?", "Esteve no local do crime?", "Mora perto da vítima?", "Devia para a vítima?", "Já trabalhou com a vítima?"]
resp = soma = 0
for p,r in enumerate(perguntas):
resp = input(f"{r}: ").strip().upper()[0]
if resp == "Y":
alg1 = int((resp.replace("Y","1")))
soma += alg1
else:
alg1 = int((resp.replace("N","0")))
soma -= alg1
if soma < 2:
print("Inocente")
elif soma == 2 or soma < 3:
print("Suspeito")
elif soma == 3 or soma < 5:
print("Cumplice")
else:
print("Assassino") | false |
3a028d9759a1129eac81d21d78ed4e753487763e | yenext1/python-bootcamp-september-2020 | /lab5/exercise_5.py | 1,059 | 4.21875 | 4 | print("Lets make a Arithmetic Progression!")
a1 = int(input("Choose the first number (a1)"))
d = int(input("Great! choose the number you and to add (d)"))
n = int(input("How many numbers should we sum? (n)"))
sum = (n/2)*(2*a1+(n-1)*d)
print(f" The sum of the numbers in the serie is {sum}")
"""
Uri's comments:
==============
* Very good! This code works.
* This is sub-exercise 6.
* "choose the number you and to add" is not the correct way to write in English.
* The input is done in int, but the result is in float. Maybe it's better to
convert it to int (it can't be a non-integer number).
You can also do the whole calculation in int to reserve precision (you lose
precision after the first ~15 digits when you convert an int to a float).
* sum is a built-in function in Python and although you can, it's not recommended
to use it as a name of a variable.
PyCharm warns about it (you can see a line under "sum" which you can hover and
see the full warning).
* There are 6 sub-exercises in exercise 5, and you only did 5 of them.
"""
| true |
ebc1c450857f3035e6129f58627a982dfffa224f | JaromPD/Robot-Finds-Kitten-Project | /rfk/game/shared/point.py | 1,943 | 4.4375 | 4 | class Point:
"""A distance from a relative origin (0, 0).
The responsibility of Point is to hold and provide information about itself. Point has a few
convenience methods for adding, scaling, and comparing them.
Attributes:
_x (integer): The horizontal distance from the origin.
_y (integer): The vertical distance from the origin.
"""
def __init__(self, x, y):
"""Constructs a new Point using the specified x and y values.
Args:
x (int): The specified x value.
y (int): The specified y value.
"""
self._x = x
self._y = y
def add(self, other):
"""Gets a new point that is the sum of this and the given one.
Args:
other (Point): The Point to add.
Returns:
Point: A new Point that is the sum.
"""
x = self._x + other.get_x()
y = self._y + other.get_y()
return Point(x, y)
def equals(self, other):
"""Whether or not this Point is equal to the given one.
Args:
other (Point): The Point to compare.
Returns:
boolean: True if both x and y are equal; false if otherwise.
"""
return self._x == other.get_x() and self._y == other.get_y()
def get_x(self):
"""Gets the horizontal distance.
Returns:
integer: The horizontal distance.
"""
return self._x
def get_y(self):
"""Gets the vertical distance.
Returns:
integer: The vertical distance.
"""
return self._y
def scale(self, factor):
"""
Scales the point by the provided factor.
Args:
factor (int): The amount to scale.
Returns:
Point: A new Point that is scaled.
"""
return Point(self._x * factor, self._y * factor) | true |
af932265190463ccbfc52464566f72485309411f | patvdc/python | /01-basics/06-functions/10_lambda.py | 442 | 4.46875 | 4 | print("lambda +")
x = lambda a : a + 10
print(x(5))
print("lambda *")
x = lambda a, b : a * b
print(x(5, 6))
print("lambda +")
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
# usage in another function (nested function)
print("nested lambda using lambda double")
def multiply(n):
return lambda a: a * n
double=multiply(2)
print("double -> ",double)
print(double(10))
triple=multiply(3)
print("triple -> ",triple)
print(triple(10))
| true |
d56e4c53f4e447580df9fef8b4316aeee3b89148 | liugongfeng/CS61A | /mentor03.py | 834 | 4.25 | 4 | ### Question 3
"""Given some list lst, possibly a deep list, mutate lst to have the accumulated sum of
all elements so far in the list. If there is a nested list, mutate it to similarly reflect the
accumulated sum of all elements so far in the nested list. Return the total sum of lst.
Hint: The isinstance function returns True for isinstance(l, list) if l is a
list and False otherwise """
def accumulate(lst):
"""
>>> l = [1, 5, 13, 4]
>>> accumulate(l)
23
>>> l
[1, 6, 19, 23]
>>> deep_l = [3, 7, [2, 5, 6], 9]
>>> accumulate(deep_l)
32
>>> deep_l
[3, 10, [2, 7, 13], 32]
"""
sum_so_far = 0
for i in range(len(lst)):
item = lst[i]
if isinstance(item, list):
inside = accumulate(item)
sum_so_far += inside
else:
sum_so_far += item
lst[i] = sum_so_far
return sum_so_far | true |
98ca46e5fe4de5e72d047032373e0399f89c3c4a | lcc19941214/python-playground | /src/basic/character.py | 1,252 | 4.15625 | 4 | # coding=utf-8
# Normal Input
print(100)
print(3.1415926897)
print('100')
print('hello')
print('你好')
print(u'你好'.encode('utf8'))
print('line 1\nline 2')
print(r'line 1\n line 2')
# method `u` means to describe an unicode symbol
# method `r` means not to excape the code
# ASCII
print(ord('A'))
print(chr(65))
# length of string
print(len('abc')) # 3
print(len(u'abc')) # 3
print(len(u'中文')) # 2
print(len('\xe4\xb8\xad\xe6\x96\x87')) # 6
# encode & decode
print('abc'.encode('utf-8')) # 'abc
print('abc'.decode('utf-8'))
print(u'中文'.encode('utf-8')) # '\xe4\xb8\xad\xe6\x96\x87'
# format with placeholder
# %s string this will always work
# %d digit 是否在数字前面padStart:%xnd x代表需要pad的字符,可以省略,默认补充空格;n代表字符总长度
# %f float 小数点后位数: %.nf n 代表需要显示的长度,默认6个
# %x 16 radix
print('hello %s' % 'world')
print('%s is now %d year\'s old' % ('Lily', 25))
print('PI is start with %f(with default to 6 digit)' % (3.141592653897))
print('PI is start with %.10f(with up to 10 digit)' % (3.141592653897))
print('The constant E is start with %d' % (2.71828))
print('Success Rate: %s%%' % 7.5)
print('My favorite movie is %03d' % 7) # 007
| false |
694a88042531009e706c7524edf0d5aa33152b3d | lcc19941214/python-playground | /src/features/iteration.py | 1,372 | 4.21875 | 4 | # coding=utf-8
from collections import Iterable
'''
list这种数据类型虽然有下标,但很多其他数据类型是没有下标的\
但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代
'''
# iterate a dict
print('\n# iterate a dict')
d = {'name': 'Lily', 'age': 25}
for key in d:
print('dict d has a property %s and its value is %s' % (key, d.get(key)))
# detect wether an object is iterable
print('\n# detect wether an object is iterable')
print(isinstance('abc', Iterable))
print(isinstance([], Iterable))
print(isinstance({}, Iterable))
print(isinstance(25, Iterable))
print(isinstance((1,), Iterable))
# iterate with index
print('\n# iterate with index')
'''
Python内置的enumerate函数可以把一个list变成索引-元素对,
这样就可以在for循环中同时迭代索引和元素本身
'''
alphabet = ['a', 'b', 'c']
print('using enumerate:')
for index, value in enumerate(alphabet):
print('index: %d; value: %s' % (index, value))
'''
也可以只用 range + len 实现 index
'''
print('using range and len:')
for index in range(len(alphabet)):
print('index: %d; value: %s' % (index, alphabet[index]))
# interate with multiple variables
print('\n# interate with multiple variables')
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
print('x: %s, y: %s' % (x, y))
| false |
54d5983b9ea33ecd84e16af3e5f41bcd569bd798 | devmohit-live/Prep | /Maths/prime_numbers_inRange.py | 951 | 4.1875 | 4 | import math
def primeNumer(n) -> list:
''' Sieve Of Erathosthenes Algorithm to find numers within the range are prime or not, here we just jump to the next multiples of the current number
in an array and make it False, we explicitly make the 0 and 1 False, this alogorithm help us to solve this O(N) task in
O(n^1/2) '''
# i = 2 # in python we have to first initialized the loop variables manually if we want to use them in loopupdate
# j = i*2
primeArray = [True]*(n+1) # 0 to n
primeArray[0], primeArray[1] = False, False
# for i in range(2, n+1, i*i): # until i*i <=n
for i in range(2, math.floor(math.sqrt(n+1))):
for j in range(2*i, n+1, i):
primeArray[j] = False # make the nth multiple False
return primeArray
t = int(input())
for _ in range(t):
n = int(input())
for i, j in enumerate(primeNumer(n)):
print("{} : {}".format(i, j))
# print(primeNumer(n))
| true |
2bc921e8e92091742cadfd34d86a0d9ad01a57f2 | sonalgupta06cs/Python_Projects | /PythonBasicsProject/listExercises.py | 816 | 4.28125 | 4 | # find the largest number in a list
numbers = [3, 6, 11, 2, 8, 4, 10]
maxNum = numbers[0]
for number in numbers:
if number > maxNum:
maxNum = number
else:
continue
print("max number is ", maxNum)
# Remove the duplicates from the list - 1
numbersList1 = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
counter = 0;
for number in numbersList1:
if number not in uniques:
uniques.insert(counter, number)
counter += 1
else:
continue
print("unique list of elements in the list 1 are ", uniques)
# Remove the duplicates from the list - 2
numbersList2 = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbersList2:
if number not in uniques:
uniques.append(number)
else:
continue
print("unique list of elements in the list 2 are ", uniques)
| true |
631a1183574d0d8a6cef80da7a8edf209052b24c | sonalgupta06cs/Python_Projects | /PythonProjectBasics2/loopsExcercises.py | 741 | 4.125 | 4 | print("-----------ForLoopExercise----------------")
# add the price and sum the total amount
prices = [10, 20, 30]
total = 0
for price in prices:
total += price
print(f'total is {total}')
print("----------ForLoopExerciseToPrint'F'-----------------")
numbers = [5, 2, 5, 2, 2]
for number in numbers:
print(number * "*")
print("----------NestedLoopExerciseToPrint'F'-----------------")
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ""
for y_count in range(x_count):
output += "*"
print(output)
print("----------NestedLoopExerciseToPrint'L'-----------------")
numbers = [1, 1, 1, 1, 5]
for x_count in numbers:
output = ""
for y_count in range(x_count):
output += "*"
print(output) | true |
033054b27f059ea4a505bf79329116aa692b78f3 | millenagena/Python-Scripts | /aula06 - desafio 004 analise, numeros, letras etc.py | 499 | 4.15625 | 4 | a = input('Type something: ')
print('The primitive type of this value is: {}'.format(type(a)))
print('Does it have only numbers? {}'.format(a.isnumeric()))
print('Does it have only letters? {}'.format(a.isalpha()))
print('Does it have only numbers and letters? {}'.format(a.isalnum()))
print('Does it have only spaces? {}'.format(a.isspace()))
print('Is it in capital letters? {}'.format(a.isupper()))
print('Is it in lowercase? {}'.format(a.islower()))
print(f'Is it capitalized? {a.istitle()}')
| true |
8a6b2a226d1188f7b9ab30d192d843bdbdad0e78 | leandromjunior/Codewars | /duplicate encoder/duplicateEncoder.py | 611 | 4.1875 | 4 | # The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character
# appears only once in the original string, or ")" if that character appears more than once in the original string.
# Ignore capitalization when determining if a character is a duplicate.
def duplicate_encode(word):
word = word.lower()
parentheses = ""
for i in word:
qtd = word.count(i)
if qtd > 1:
parentheses += ")"
else:
parentheses += "("
return parentheses
n = duplicate_encode('Success')
print(n) | true |
37008caf6079ac122daf822f483f3cdc26420a38 | mfcust/operators_comments | /operators_comments.py | 1,360 | 4.6875 | 5 | ###Operators and comments###
###You can write comments like this!!###
'''Or if your comments span multiple lines,
like this
and this
and this, you can use three single quotes to comment out large blocks of code.'''
#1) Write a comment below by using the '#' symbol.
#2) Write a multi-line comment below by using three single quotes on each side ('''like this, but multiple lines''')
#### These are the most common arithmetic operators in python: +(addition), -(subtraction), /(division), *(multiplication)####
#3) Calculate 100 divided by 2 and print to the console
#4) Calculate 3 multiplied by 1,000 and print to the console
#5) Calculate 50 minus 75 and print to the console
#6) Calculate 100.5 plus 32.17864532983764862 and print to the console
#7) Calculate 32 plus 8, then multiply by 6 and print to the console
#Bonus problems
#1) Calculate 2 to the power of 6 and print to the console
#2) Calculate 40 divided by "Hello" and print to the console
#Hint: If you get an error, why does that happen???
#3) What is the % operator? Perform a calculation with it below
#4) What is the // operator? Perform a calculation with it below
#5) Use the % operator and the // operator to divide 10 by -3. Do you notice something unusual about the output when compared to dividing 10 by 3? Why is it different?
| true |
85fb92186a54ee75f8d14ca7ede685782bc3fdc6 | gkl1107/Python-algorithm | /alice_words.py | 1,189 | 4.25 | 4 | '''
Write a program that creates a text file named alice_words.txt containing an alphabetical listing of all the words, and the number of times each occurs.
'''
word_dict = {}
with open("alice_in_wonderland.txt") as file:
line = file.readline()
while line:
no_punct = "".join([char for char in line if char.isalpha() or char.isspace() or char == '-' or char == "'"])
no_doubleHyphen = no_punct.replace("--", " ")
no_astro = no_doubleHyphen.replace("'s", " ")
clean_line = no_astro.lower()
words = clean_line.split()
for word in words:
if word_dict.get(word) == None:
word_dict[word] = 1
else:
word_dict[word] = word_dict[word] + 1
line = file.readline()
# write the wordlist result into a new file called "alice_words.txt"
sorted_words = sorted(word_dict.keys())
outfile = open("alice_words.txt","w")
for word in sorted_words:
outfile.write(word + "," + str(word_dict[word]) + "\n")
# find the longest word in the wordlist
word_length = {}
for word in word_dict.keys():
word_length[word] = len(word)
max_length = max(v for v in word_length.values())
for k,v in word_length.items():
if v == max_length:
print("longest word is: ", k, v)
| true |
23751a9b31c21edd67b5b54342f3a8dfb299c517 | gkl1107/Python-algorithm | /alphabet_cipher.py | 867 | 4.625 | 5 | #!/usr/bin/python
'''
A function that implements a substitution cipher.
the function takea two parameters, the message you want to encrypt,
and a string that represents the mapping of the 26 letters in the alphabet.
'''
import string
def cipher(message, str_mapping):
upperCase_mapping = str_mapping.upper()
encrypt = []
for c in message:
if c in string.ascii_uppercase:
sub = str_mapping.upper()[string.ascii_uppercase.index(c)]
encrypt.append(sub)
elif c in string.ascii_lowercase:
sub = str_mapping[string.ascii_lowercase.index(c)]
encrypt.append(sub)
else:
encrypt.append(c)
result = "".join(encrypt)
return result
r = cipher("Write a function that implements a substitution cipher.","efghijklmnopqrstuvwxyzabcd")
print(r) | true |
8e6a6b7a3f5f3fd341079d6e0435ffb0e4f2e477 | weikuochen/LeetCode | /LeetCode_000009.py | 937 | 4.21875 | 4 | """
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string,
note the restriction of using extra space.
You could also try reversing an integer.
However, if you have solved the problem "Reverse Integer",
you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
"""
class Solution(object):
def isPalindrome(self, x):
result = False
if x < 0:
pass
elif x >= 0 and x < 10:
result = True
else:
for i in range(len(str(x)) / 2):
if str(x)[i] != str(x)[-(i + 1)]:
break
else:
result = True
return result
x = int(input())
print(isPalindrome(0, x)) | true |
4a841929d8277ce9ebdc78055bf26752aea6e4b2 | yarosmar/beetroot-test-repo | /calculator.py | 667 | 4.1875 | 4 | def calculate():
operation = input()
number_1 = int(input())
number_2 = int(input())
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please try the program again.') | true |
f988f37a28f4994bcb69f3db84cb3f5777c249c4 | BabaYegha/pythonExercises | /week-02/unique.py | 315 | 4.15625 | 4 |
def unique(uniqList):
unique_list = []
for x in uniqList:
if x not in unique_list:
unique_list.append(x)
for x in unique_list:
print(x)
numbers = [1, 11, 34, 11, 52, 61, 1, 34]
print("Original list: [1, 11, 34, 11, 52, 61, 1, 34]")
print("Unique list: ")
unique(numbers) | true |
f88b4c5f5238bb699783ef2b678e4d7f0ff5dedd | jilesingh/LearnPythonTheHardWay | /chapter1/ex20.py | 1,096 | 4.3125 | 4 | # -*- coding utf-8 -*-
# This code is written and run using Python Version 3.6.8
from sys import argv
script, input_file = argv
def print_all(f):
print (f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print (line_count, f.readline())
current_file = open(input_file)
print ("First let's print the whole file:\n")
print_all(current_file)
print ("Now let's rewind, kind of like a tape.")
rewind(current_file)
print ("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
# Here is output as observed from the terminal:
'''
First let's print the whole file:
Weather the file was erased really
This is agin to test your programming skills
Now it will be written agin to the file
Now let's rewind, kind of like a tape.
Let's print three lines:
1 Weather the file was erased really
2 This is agin to test your programming skills
3 Now it will be written agin to the file
''' | true |
f48ca78c0c9e5b0d8b91d87f757ea0cf57e462f4 | jilesingh/LearnPythonTheHardWay | /chapter1/ex16.py | 1,194 | 4.3125 | 4 | # -*- coding utf-8 -*-
# This code is written and run using Python Version 3.6.8
from sys import argv
script, filename = argv
print ("We are going to erase %r." % filename)
print ("If you don't want that, hit CTRL+C")
print ("If you do want that, hit Return")
input("?")
print ("Openeing the file.....")
target = open(filename, 'w')
print ("Truncating the file. Goodbye!")
target.truncate()
print ("Now I'm going to ask you three lines.")
line1 = input ("line1: ")
line2 = input ("line2: ")
line3 = input ("line3: ")
print ("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally we close it.")
target.close()
# Here is the output we get from the console
'''
We are going to erase 'ex15.txt'.
If you don't want that, hit CTRL+C
If you do want that, hit Return
?
Openeing the file.....
Truncating the file. Goodbye!
Now I'm going to ask you three lines.
line1: Weather the file was erased really
line2: This is agin to test your programming skills
line3: Now it will be written agin to the file
I'm going to write these to the file.
And finally we close it.
'''
| true |
43e02df282c080a98b9ce55772a3e1ef9ea403d3 | Kushalchg/Rock-Paper-and-Scissors-game | /rock_paper_scissors.py | 1,215 | 4.1875 | 4 |
import random
choice_list = ['rock','scissors','paper']
computer_input = random.choice(choice_list)
user_input = (input("enter your choice: "))
if (computer_input=="rock" and user_input=="scissors"):
print("computer choice: "+computer_input)
print("you loose")
elif(computer_input =="paper" and user_input=="rock"):
print("computer choice: " + computer_input)
print("you loose")
elif(computer_input=="scissors" and user_input=="paper"):
print("computer choice: " + computer_input)
print("you loose")
elif(computer_input == "rock" and user_input == "rock"):
print("computer choice: " + computer_input)
print("you draw")
elif (computer_input == "paper" and user_input == "paper"):
print("computer choice: " + computer_input)
print("you draw")
elif (computer_input == "scissors" and user_input == "scissors"):
print("computer choice: " + computer_input)
print("you draw")
else:
if(user_input != 'scissors' and user_input!='rock' and user_input!='paper'):
print("you entered wrong word please check spelling")
else:
print("computer choice: " + computer_input)
print("you win")
| false |
111c6397fbda31698130e27bdfe8a30565a50d95 | shivamkalra111/Tkinter-GUI | /buttons.py | 379 | 4.15625 | 4 | from tkinter import *
root = Tk()
def click():
mylabel = Label(root, text = "Clicked the button!!")
mylabel.pack()
#click the button again and again the text comes up multiple times
#can also use x color codes
mybutton = Button(root, text = "Click me", padx = 50, pady = 50, command = click, fg = 'yellow', bg = '#000000')
mybutton.pack()
root.mainloop() | true |
2c9fd4e0e74f12b7c7da6595cae99190eaa597e2 | Marklar9197/Python-Project | /game.py | 1,166 | 4.1875 | 4 | #This program takes a random number between 1 and 10 and asks the user to guess it.
import random
random_num = random.randint(1,10)
print(random_num) # Being used for testing purposes
guess = int(input("What is my number? > "))
small_num = int(input('Lower > '))
large_num = int(input('Higher > '))
replay = input("Would you like to play again? > ")
my_num = "I'm thinking of a number between 1 and 10"
# Here we define the initial greeting to the user that asks them to guess the number
def greeting():
print(my_num)
print(guess)
if type(guess) == int:
user_choice()
else:
print('Please enter a number')
greeting()
# Here we have our if statements to compare the user's guess to the value of the random number
def user_choice():
if guess < random_num:
print(large_num)
user_choice()
elif guess > random_num:
print(small_num)
user_choice()
elif guess == random_num:
print "You got it!"
play_again()
if type(guess) == int:
user_choice()
else:
print('Please enter a number')
user_choice()
def play_again():
print(replay)
if replay == 'yes'.lower():
greeting()
else:
print('Thanks for playing :)')
| true |
3679332415ce1d8a521b3521ceeb59298d0d1aab | eightweb/LifeisShort | /2分支,循环,条件,枚举/条件控制.py | 667 | 4.3125 | 4 | """
条件控制 if else
循环控制 for
分支 while
"""
# 如果是真 执行代码块 python中 无{}包裹这代码块, 是通过缩进来控制代码块
# 例子1:
# mood = True
# if mood:
# print('是True')
# else:
# print('是False')
# 例子2:
# userName = 'taowang'
# password = '123'
# print('please input Name and pass')
# user_Name = input() # 请输入的功能 返回的类型是str
# user_pass = input()
# if userName == user_Name and password == user_pass:
# print('恭喜登录成功!')
# else:
# print('账号密码有误, 请重新输入')
# 例子3
if '':
pass # 占位语句/空语句
elif '1':
pass
else:
pass | false |
abd61a3dfe88daaa4391d938ee532666d0b85701 | eightweb/LifeisShort | /5函数/c4.py | 1,583 | 4.28125 | 4 | '''
函数参数:
必须参数
关键字参数: 不比关心函数的形参的顺序, 调用时, 指定实参对应的是形参的哪个
'''
def Summation(num1, num2):
return num1 + num2
c = Summation(num2 = 10, num1 = 30) # 使用的是关键字参数, 不比考虑形参的顺序位置
'''
默认参数
'''
def defaultDef(num1, num2 = 10):
return num1 + num2
c = defaultDef(2) # 当不传的时候 num2 默认是10
'''
可变参数: 随便传 不用管形参的多少 (也可以不传)
比如print(1,2,4,5,6,6) 可以传递无数的参数
实际实现方式: 形参处理成tuple类型 永远是看成一个参数
所以我们可以自己调用的时候 传个tuple就行了
demo((1,2,3,4,5,6))
'''
def demo(*params):
print(params)
print(type(params))
demo(10,2,4,5,'22')
'''
如果: 我就想传入个元组到函数里面
实参加上*
'''
def demo1(*params):
print(params)
demo1(*(1,2,3,4))
'''
必须参数, 可变参数, 默认参数 共同组成的函数
一般不要设计这种函数, 太麻烦了
'''
def Form(params, *params1, params2 = 2):
print(params)
print(params1)
print(params2)
Form(2, 1,2,4, params2='22') # 指定 params2为新的参数, 要不然永远都是在可变参数中 应为是元组类型
'''
打印字典的key value值 items()函数
values()函数 专门打印value值
keys()函数 专门打印key值
'''
def city_temp(**param):
for item,value in param.items():
print(item, ":", value)
city_temp(bj='32c', sh='21c', hf='23c') | false |
438f7cc6adcccec59265e134a0392a68b1068b22 | saharul/csa-ver-1.0 | /getfuturedate.py | 346 | 4.15625 | 4 | from datetime import date
import datetime
from dateutil.relativedelta import relativedelta
def main():
today = date.today()
threemonths = datetime.datetime.now() + relativedelta(months=3)
print("Today's date is ", today)
print("3 months from today ", threemonths.strftime("%Y-%m-%d"))
if __name__ == "__main__":
main()
| false |
1eda22930e4ea80cce1894da1b9ffdf3f3a71fab | ranjithmanda/solaris | /B1/solaris_samples/count_words.py | 585 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 09:16:38 2020
@author: gupta
count number of times each word occurred in given string.
find count of each digits in given number.
find specific digit found in given number.
"""
# this program is incomplete. need to explain further.
given_str = "this is a good day , this is a great day"
def count_words(given):
words = given.split()
for word in words:
print(word)
#print(*words)
#print(words[0], words[1], words[2], words[3], words[4])
count_words(given_str) #, 1,2,3,4,5, "dfsd", "the", 500)
| true |
ca59919a9b447c2d7b0db5cf2bde7257a684d3b9 | mattdix27/miniprojects | /dijkstra.py | 2,055 | 4.125 | 4 | import sys
'''
Graph with multiple nodes as well as edges with lengths
Find the shortest distance to any node
'''
graph = {
'a':[{'b':4},{'c':8},{'d':7}],
'b':[{'a':4},{'e':12}],
'c':[{'a':8},{'d':2},{'e':3}],
'd':[{'a':7},{'c':2},{'f':10}],
'e':[{'b':12},{'c':3},{'g':18}],
'f':[{'d':10},{'g':20}],
'g':[{'e':18},{'f':20}]
}
def minimum_distance(distances, visited): # find the node with the shortest distance
min_distance = sys.maxsize
for node in distances:
if node in visited:
continue
if distances[node] < min_distance:
min_distance = distances[node]
min_node = node
return min_node # return the key for the node/node identifier
def visiting(node,distances,visited): # process for visiting each node
for edge in graph[node]:
edge_key=list(edge.keys())[0] # letter of the other end of the edge
edge_value=list(edge.values())[0] # length of the edge to reach the other end
new_total = distances[node] + edge_value # adding the distance of current node to the length of the edge to visit
if edge_key not in visited:
if new_total < distances[edge_key]: # replace if distances value is greater than new total
distances.update({edge_key:new_total})
visited.append(node) # add the current node to the visited list
def shortest(graph):
distances = {} # this will be a dictionary of shortest distances to each node
visited = [] # this is all nodes that have been completely visited
for node in graph: # iterate through all nodes to make distance infinity
distances.update({node:sys.maxsize})
distances.update({next(iter(graph)):0}) # set distance of source to 0
while len(visited) != len(graph):
closest = minimum_distance(distances, visited)
visiting(closest,distances,visited)
print(visited)
print(distances)
shortest(graph) | true |
0daa638eb46824a06007d0d220b3763f0450c926 | Disha-Shivale/Exceptionhandling | /regex1.py | 483 | 4.53125 | 5 | import re
s = "Hello from Python, This is Reg Expression"
i = re.search("^Hello", s)
# ^Starts with
if (i):
print("String Match!")
else:
print("No match")
#Example 2
i = "Hello from Python"
print()
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-z]", i)
print(x)
print()
#Example 3
s = "hello from python"
#Check if the string ends with 'world':
i = re.findall("on$", s)
if (i):
print("String Match")
else:
print("No match") | true |
d23c30395aa9e2fa29c169e4f3313d2204fae50d | fmcooley/TTA_Projects | /Python/item_62_datetime_drill/FC_Datetime_Drill_rev1.py | 1,075 | 4.125 | 4 | #!/usr/bin/python2.7
# Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59)
# Student: Freeman Cooley
# Python Course Item 62
# Drill: Pydrill_Datetime_27_idle
# http://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones
# http://www.guru99.com/date-time-and-datetime-classes-in-python.html
# importing modules
import time
import datetime
from datetime import timedelta
# Determining time
Portland = datetime.datetime.now()
London = datetime.datetime.now() + timedelta(hours=8)
NYC = datetime.datetime.now() + timedelta(hours=3)
# Printing Current time at all 3 locations
print "Portland Time: ", Portland
print "London Time: ", London
print "New York City Time: ", NYC
# Printing out "Open" or "Closed" depending on time comparison
if London.time() > datetime.time(9,0,0,0) and London.time() < datetime.time(21,0,0,0):
print ("London Branch is Open")
else:
print ("London Branch is Closed")
if NYC.time() > datetime.time(9,0,0,0) and NYC.time() < datetime.time(21,0,0,0):
print ("NYC Branch is Open")
else:
print ("NYC Branch is Closed")
| false |
d6e502c150a837f17610cfdc88ef536c99363e1c | mohammadasim/python-course | /Errors _and_exceptions/homework.py | 1,354 | 4.15625 | 4 | # Problem 1
# Handle the exception thrown by the code below by using try and except blocks
def square_root():
for i in ['a','b','c']:
try:
print(i**2)
except TypeError as wrong_list_items:
print('Wrong list items provided. Please provide either int or floating point')
finally:
print('Thanks for using the function')
#square_root()
#Problem 2
# Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done'
def division_by_zero():
x = 5
y = 0
z = 0
try:
z = x/y
except ZeroDivisionError as divided_by_zero_error:
print('You are dividing the value by zero')
finally:
print('All Done')
#division_by_zero()
# Problem 3
# Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to
# account for incorrect inputs.
def ask():
x = 0
while True:
try:
x = int(input('Input an integer: '))
except ValueError as wrong_input:
print('An error occured! Please try again!')
continue
else:
print('Input an integer: {}'.format(x))
break
finally:
print('Thank you, your number squared is: {}'.format(x**2))
ask() | true |
ede487fdcd22575b67b235343dd5c69bc8a094e8 | mohammadasim/python-course | /while_loops.py | 396 | 4.15625 | 4 | x = 0
while x < 5:
print('The value of x is {}'.format(x))
x += 1
else:
print( 'X is not less than 5')
# break, continue, pass
# We can use break, continue and pass statements in our loops to add additional functionality for various cases
# break: Breaks out of the current closest enclosing loop.
# continue: Goes to the top of the closest enclosing loop
# pass: Does nothing at all | true |
1c0844e3c04f201687718b037286e60a567a7cc0 | mohammadasim/python-course | /python_generators/generator.py | 2,410 | 4.71875 | 5 | '''
We have learned how to cerate functions with def and the return statement. Generator functions allow us to write a
function that can send back a value and then later resume to pick up where it left off.
This type of function is a generator in Python, allowing us to generate a sequence of values over time.
The main difference in syntax will be the use of a yield statement.
When a generator function is compiled they become an object that supports an iteration protocol.
That means when they are called in your code they don't actually return a value and then exit.
Instead generator function will automatically suspend and resume their execution and state around the last point
of value generation.
The advantage is that instead of having to compute an entire series of values up front, the generator computes
one value waits until the next value is called for.
For example the range() function doesn't produce a list in memory of all the values from stat to stop, instead
it just keeps track of the last number and the step size to provide a flow of numbers.
If the user did need the list, they have to transform the generator to a list with list(range(0,10))
'''
def create_cubes(n):
result = []
for x in range(n):
result.append(n**3)
return result
print(create_cubes(10))
'''
The above function can be transformed into a generator in the following way.
'''
def create_cubes_gen(n):
for x in range(n):
yield x**3
for kube in create_cubes_gen(10):
print(kube)
def gen_fibon(n):
a = 1
b = 1
for x in range(n):
yield a
# This part of the calculation is for creating the fibon and the next step.
a,b = b, a+b
'''
Important point to note is that in order to print the output of generator
we have to iterate through it using a for loop.
'''
for number in gen_fibon(10):
print(number)
def simple_gen():
for x in range(3):
yield x
g = simple_gen()
print(next(g))
print(next(g))
print(next(g))
#print(next(g))
'''
As you can see that an error is being thrown, as we try to get the next generator using next() method.
In for loop behind the back this error is thrown and cuaght and we don't know about it.
'''
s = 'hello'
for letter in s:
print(letter)
#next(s)
# The above method will throw error as string is not iterable. But we can can change it to interable
s_iter = iter(s)
print(next(s_iter)) | true |
31981e597b9583b5423ca38a8e78c3ac5012e239 | mohammadasim/python-course | /variables.py | 622 | 4.3125 | 4 | # Python is dynamically typed, it means that we can assign any type of value to a variable.
# Unlike Java which is statically typed. Which means we have to declare the type of the variable and can only
# assign that type of value to it.
a = 5
print a
a = a + a
print a
a = 'b'
# We can use the type function to determine the type of the variable a in the following example.
# We will get string as a currently have the value 'b'. If however we will change it to an int then the type() function
# will return the type as int
print type (a)
my_income = 100
my_tax_rate = 0.40
my_tax = my_income * my_tax_rate
print my_tax | true |
e3caadd4da05454be2fc7540c9374bb8689ab210 | mohammadasim/python-course | /ood_class_object_attributes.py | 1,413 | 4.1875 | 4 | class Dog():
# Class Objject Attributes
# These are the same for all instances of a Class
# These are identical to Static attributes in Java
species = 'mammal'
# Constructor of the class with three arguments
# We can provide default values for these attributes and they will be overwritten if the values is provided
# at the time of instantiating the object
# e.g name = 'Frankie'
# def __init__(self, breek,name='Frankies',spots)
def __init__ (self, breed,name,spots):
self.breed = breed
self.name = name
# Expects boolean True/False
self.spots = spots
self.short_intro = breed + ' ' + name
# Methods of Dog class
# The main difference between method is Java and Python is the use of self key word
def bark(self):
print("WOOF!")
# Using attributes of the class in a method
# Remember to use the keyword self when referencing attributes of the class
def introduce(self):
print('I am {}, my breed if {} and do you think I have spots or not \nI say {} but my species is {}'.format(self.name,self.breed,self.spots,Dog.species))
# Methods with attributes that are passed to a method
def affection_to_master(self,master_name):
print('woof ' + master_name)
my_dog = Dog('lab','Sam',False)
my_dog.bark()
my_dog.introduce()
my_dog.affection_to_master('Donald')
print(my_dog.short_intro) | true |
fe51c43cf891d8ab1ade5c71756e538d392ba738 | beckytrantham/PythonI | /lab3.py | 297 | 4.125 | 4 | #Reads the temperature in F from the keyboard, then prints the equivalent in C.
#Formula C = 5 / 9 * (F - 32)
temp = raw_input('What is the temperature in degrees Fahrenheit? ')
ftemp = float(temp)
ctemp = 5.0 / 9.0 * (ftemp - 32)
print 'The temperature is {} degrees Centigrade.' .format(ctemp)
| true |
3736232377d04f29abb3edd4c3cbf1f592f01ed2 | YektaAkhalili/Practice_Python | /Ex2.py | 707 | 4.125 | 4 | num = int(input("Give me a number, and I'll tell you if it's even or odd: "))
def decision(n):
if n % 2 == 0:
if n % 4 == 0:
print("Even & Divisble by 4.")
else:
print("Even number.")
else:
print("Odd number.")
decision(num)
print("Now let's check if two number are divisable.")
n1 = int(input("1st number: "))
n2 = int(input("2nd number: "))
def devisable(n1,n2):
if n1 % n2 == 0:
print(str(n1) + " is divisable by " + str(n2))
if n2 % n1 == 0:
print(str(n2) + " is divisable by " + str(n1))
if n1 % n2 != 0 and n2 % n1 != 0:
print("Not divisable.")
devisable(n1,n2) | false |
3447720ec6cde0cfe9f375462a2c4d69f0488775 | theLoFix/30DOP | /Day24/Day24_Excercise02.py | 457 | 4.25 | 4 | # Below you'll find a divide function. Write exception handling so that we catch ZeroDivisionError exceptions, TypeError exceptions, and other kinds of ArithmeticError.
def divide(a, b)
try:
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Both values must be numbers. Cannot divide {a} and {b}")
except ArithmeticError:
print("Could not complete the division. The numbers were likely too large")
| true |
9bbe017ba0c1efb455de424cb1a234a408bb5bfa | theLoFix/30DOP | /Day10/Day10_Excercise01.py | 778 | 4.3125 | 4 | # Inside the tuple we have the album name, the artist (in this case, the band), the year of release, and then another tuple containing the track list.
# Convert this outer tuple to a dictionary with four keys.
tuple1 = (
"The Dark Side of the Moon",
"Pink Floyd",
1973,
(
"Speak to Me",
"Breathe",
"On the Run",
"Time",
"The Great Gig in the Sky",
"Money",
"Us and Them",
"Any Colour You Like",
"Brain Damage",
"Eclipse"
)
)
print(tuple1)
album = {
"album": "The Dark Side of the Moon",
"artist":"Pink Floyd",
"year": 1973,
"track": (
"Speak to Me",
"Breathe",
"On the Run",
"Time",
"The Great Gig in the Sky",
"Money",
"Us and Them",
"Any Colour You Like",
"Brain Damage",
"Eclipse"
)
}
print(album)
| true |
525bc17db7c6eae600218137c3c8586e5d5dc78f | theLoFix/30DOP | /Day07/Day07_Excercise1.py | 464 | 4.25 | 4 | # Ask the user to enter their given name and surname in response to a single prompt. Use split to extract the names, and then assign each name to a different variable. For this exercise, you can assume that the user has a single given name and a single surname.
answer = (input("Please provide your first and last name... ")).split()
print(answer)
first_name = answer[0]
last_name = answer[1]
print(f"First name: {first_name}")
print(f"Last name: {last_name}")
| true |
dd3c094d86d37d4ced4dfcf7c89f057547ab04f4 | vinayvarm/programs | /venv/LeapYear.py | 683 | 4.25 | 4 | # year = int(input('enter year'))
#
# def checkleap():
#
# if year%4==0 and(year%100!=0 or year%400==0) :
# print('leap year')
# else:
# print('not leap year')
#
# checkleap()
month= input('enter month')
month = month.strip().lower()
def checkdaysformonth():
if month=='jan' or month=='march' or month=='may' or month=='july' or month=='august' or month=='oct' or month=='dec':
print('days for this month are',31)
elif month=='apr' or month =='june' or month=='sep':
print('days for this month are',30)
elif month=='feb':
print('leap year month', 28 or 29)
else:
print('invalid month')
checkdaysformonth()
| false |
630f6ca3b741a9ee4a9dc01b3cbabc122927e93c | esinayyildiz/linear_nonlinear_regression | /ps0_1_a.py | 1,177 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def main(): #my main method
#variable for regression
x = np.array([31,33,31,49,53,69,101,99,143,132,109])
y = np.array([705,540,650,840,890,850,1200,1150,1700,900,1550])
x=x[:,np.newaxis]
y=y[:,np.newaxis]
# size of the dataset
num = np.size(x)
meanof_X = np.mean(x)
meanof_Y = np.mean(y)
# calculate the cross-deviation
cross_y=np.sum(y*x)-(num*meanof_Y*meanof_X)
cross_x=np.sum(x*x)-(num*meanof_X*meanof_X)
# calculating regression coefficients
b1 = cross_y / cross_x
b0 = meanof_Y - b1*meanof_X
print("Estimated coefficient values:\n1) {} \n2) {}".format(b0, b1))
w = np.matmul(np.linalg.pinv(x),y) #calculate of the w value
print("w is =" ,w)
y_prediction = b1*x + b0 # predicted response
# plotting the points
plt.scatter(x, y, marker='*' , color='black')
plt.plot(x, y_prediction) # plot the regression line
plt.xlabel('house size (sqm)')
plt.title("Linear Regression")
plt.ylabel(' rent')
plt.show()
if __name__ == "__main__":
main() | false |
7d760eb55f99e40f16d5264b5be50fb5cb2b2e6b | league-python/Level0-Module1 | /_03_if_else/_3_tasty_tomato/tasty_tomato.py | 665 | 4.375 | 4 | from tkinter import *
import tkinter as tk
window_width = 600
window_height = 600
root = tk.Tk()
canvas = tk.Canvas(root, width=window_width, height=window_height, bg="#DDDDDD")
canvas.grid()
# 1. Ask the user what color tomato they would like and save their response
# You can give them up to three choices
# 2. Use if-else statements to draw the tomato in the color that they chose
# You can modify the code below or draw your own tomato
canvas.create_oval(75, 200, 400, 450, fill="red", outline="")
canvas.create_oval(200, 200, 525, 450, fill="red", outline="")
canvas.create_rectangle(275, 100, 325, 230, fill="green", outline="")
root.mainloop()
| true |
2e5cb49890b56e5253d1e61b494dce3b18b61d52 | azegun/python_study | /chap05/lamda/lamda3.py | 496 | 4.21875 | 4 | """
def power(item):
return item * item
"""
"""
여러번 사용할 시, 선언해서 사용
power =lambda x :x * x
under_3 = lambda x: x < 3
"""
"""
def under_3(item):
return item < 3
"""
list_input_a = [1, 2, 3, 4, 5]
#map 함수
#1번 사용할 시, 람다 바로 수식
output_a = map(lambda x :x * x, list_input_a)
print(list(output_a))
#filter
output_b = filter(lambda x: x < 3, list_input_a)
print(list(output_b))
output_c = lambda x, y: x * y
res = output_c(5,3)
print(res) | false |
d28e288c8f8bda49d0291861c5bfaea407761818 | wenyan666/wenyan-python | /ex18.py | 930 | 4.40625 | 4 | # -*- coding:UTF-8 -*-
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1:%r, arg2: %r." % (arg1, arg2)
# OK, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1:%r, arg2:%r" % (arg1, arg2)
# or just type one argument
def print_one(arg1):
print "arg1:%r" % arg1
# this is none argument
def print_none():
print "I got nothin'."
print_two("zed", "shaw")
print_two_again("zed", "shaw")
print_one("first")
print_none()
'''
加分习题
def one(who, why, where):
print "I love %r,becouse he is %r, I meet him in %r." % (who, why, where)
def two(what, how):
print "I'd like learning %r, by %r." % (what, how)
one("Manger", "smart", "book")
two("Python", "following the big bug.")
已运行成功。
‘运行函数(run)’、‘调用函数(call)’、和 ‘使用函数(use)’是同一个意思
'''
| true |
d746b68a08610c3e5ddc4b953ca0335c248a3b59 | PRai0409/code1 | /first.py | 2,271 | 4.28125 | 4 | #PROGRAM 1
print("PROGRAM 1")
fname =input("Enter any filename :")
print("Output :")
op=fname.split(".")
#print(type(op))
print("filename : ",op[0])
print("extension : ",op[1])
#PROGRAM 2
print("\nPROGRAM 2")
fnum = int(input("Enter first number :"))
#print(type(fnum))
snum = int(input("Enter second number :"))
total=sum([fnum,snum])
print("Sum of numbers :",total)
#PROGRAM 3
print("\nPROGRAM 3")
alist=[10,20,30,10,35,20,67,89,20,10]
print("Unique list:",list(set(alist)))
#PROGRAM 4
print("\nPROGRAM 4")
fname =input("Enter the string : ")
#1.uppercase 2.count of p 3.replace python to ruby 4.count number of words
#5. count number of char 6.remove spaces --Python is general purpose interpreted cross platform programming language--
print("Uppercase:",fname.upper())
print("Count of p:",fname.count("p"))
print("Replace:",fname.replace("Python","Perl"))
print("Number of words:",len(fname.split(" ")))
print("Number of characters:",len(fname))
print("Removed spaces",fname.strip())
#PROGRAM 5
print("\nPROGRAM 5")
alist=list()
alist.append(10)
alist.append(20)
alist.append(50)
alist.extend([90,20,45,32,645,32,90,65,43,23,55,4,32,50])
print("First list:",alist)
blist=list(set(alist))
print("Unique list:",blist)
blist.remove(50)
blist.sort(reverse=True)
print("Desc sort:",blist)
print("Tuple",tuple(blist))
'''
----------------------OUTPUT--------------------
PROGRAM 1
Enter any filename :hello.py
Output :
filename : hello
extension : py
PROGRAM 2
Enter first number :78
Enter second number :87
Sum of numbers : 165
PROGRAM 3
Unique list: [67, 35, 10, 20, 89, 30]
PROGRAM 4
Enter the string : Python is general purpose interpreted cross platform programming language
Uppercase: PYTHON IS GENERAL PURPOSE INTERPRETED CROSS PLATFORM PROGRAMMING LANGUAGE
Count of p: 5
Replace: Perl is general purpose interpreted cross platform programming language
Number of words: 9
Number of characters: 73
Removed spaces Python is general purpose interpreted cross platform programming language
PROGRAM 5
First list: [10, 20, 50, 90, 20, 45, 32, 645, 32, 90, 65, 43, 23, 55, 4, 32, 50]
Unique list: [32, 65, 4, 645, 10, 43, 45, 50, 20, 55, 23, 90]
Desc sort: [645, 90, 65, 55, 45, 43, 32, 23, 20, 10, 4]
Tuple (645, 90, 65, 55, 45, 43, 32, 23, 20, 10, 4)
''' | true |
29eaffb27ed811d9e2ebc82927281793be6f2b7e | shubham-ricky/Python-Programming---Beginners | /Vowels.py | 1,404 | 4.125 | 4 | """
a) Write a function getVowels that takes in an utterance as argument and returns the vowels (A, E, I, O, U) in uppercase. Sort your list according to the sequence of the alphabets in your vowels.
b) Write the function countChars that takes in an utterance and a character as arguments, and call the function to return the number of occurrence of the character value in the utterance.
"""
def getVowels(text): # Part a)
text = text.upper()
text_len = len(text)
new_list =[]
for x in range(0,text_len):
if text[x] =="A" or text[x] =="E" or text[x] =="I" or text[x] =="O" or text[x] =="U":
new_list.append(text[x])
new_list.sort()
return (new_list)
print(getVowels("machine learning"))
print(getVowels("image classification"))
def countChars(utterance, character): # Part b)
tot_char = utterance.count(character)
return(tot_char)
print()
print(countChars("It's going to be interesting to see how society deals with artificial intelligence, but it will definitely be cool.", "a"))
print(countChars("Some people call this artificial intelligence, but the reality is this technology will enhance us. So instead of artificial intelligence, I think we'll augment our intelligence.", "i"))
| true |
d514c8d421a394644d686512f387f5ca2e54ddd8 | Robert-Siberry/IntroToGit | /numberguess2.py | 492 | 4.21875 | 4 | print("The Guessing Game")
import random
number=random.randint(1,9)
guess=0
counter=0
while guess!=number and guess!="exit":
guess=input("Please guess a number between 1 and 9: ")
if guess == "exit":
break
guess = int(guess)
counter=counter+1
if guess < number:
print("Thats too low!")
elif guess > number:
print("Thats too high!")
else:
print("Thats right the number was",number,"and it only took you",counter,"guesses!")
input()
| true |
98f6a84e85c8e12b4c2fdba7a0560dcc53ce0fae | zhane98/studying | /lesson21.py | 310 | 4.40625 | 4 | # string formatting/interpolation = %s inside of a string to mark where we want other strings inserted.
# E.g:
name = 'Calvin'
place = 'KFC'
time = '8 pm' # how to add pm
food = 'chicken'
print("Hello %s, you are invited to a party at %s at %s. Please bring %s." %(name, place, time, food)) | true |
f6e1ed77f1e44b905af6895e212f34c3ec828a14 | zhane98/studying | /codewars2.py | 998 | 4.3125 | 4 | # RETURNING STRINGS
# Make a function that will return a greeting statement that uses an input;
# your program should return, "Hello, <name> how are you doing today?".
def greet(name):
#Good Luck (like you need it)
return "Hello, " + name + " how are you doing today?"
print(greet('Zhané')) #calling the function and passing the parameter 'zhané'
print(greet('Calvin'))
print(greet('Mum'))
# "Hello, Zhané how are you doing today?"
def temp(integ):
print(f"You are {integ} years old") # f-strings let's us do String Interpolation
temp(39)
#IS n DIVISIBLE BY x and y?
def is_divisible(n,x,y):
if n % x == 0 and n % y == 0:
return True
else:
return False
is_divisible(3, 3, 4) # False
is_divisible(12, 3, 4) # True
# Calvin Solution
def is_divisible1(n,x,y):
return n % x == 0 and n % y == 0
print(is_divisible1(3, 3, 4)) # False
print(is_divisible1(12, 3, 4)) # True
# True == True = True
# False == True = False
# False == False = False | true |
4047d09aecce5353fe31ce6586ddd951731b4ece | papan36125/python_exercises | /concepts/Exercises/dictionary_examples.py | 778 | 4.25 | 4 | # empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
| false |
cff7967a402d750c2faa69b8a61ccff2c1952e4f | papan36125/python_exercises | /concepts/Exercises/implicit_type_conversion.py | 237 | 4.15625 | 4 | num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
| false |
80920c05b76e207f324ac356382c239a1975d48f | papan36125/python_exercises | /concepts/Exercises/tuples_example_2.py | 930 | 4.28125 | 4 | my_tuple = (4, 2, 3, [6, 5])
# we cannot change an element
# If you uncomment line 8
# you will get an error:
# TypeError: 'tuple' object does not support item assignment
#my_tuple[1] = 9
# but item of mutable element can be changed
# Output: (4, 2, 3, [9, 5])
my_tuple[3][0] = 9
print(my_tuple)
# tuples can be reassigned
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple)
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
my_tuple = ('p','r','o','g','r','a','m','i','z')
# can't delete items
# if you uncomment line 8,
# you will get an error:
# TypeError: 'tuple' object doesn't support item deletion
#del my_tuple[3]
# can delete entire tuple
# NameError: name 'my_tuple' is not defined
del my_tuple
my_tuple
| false |
9b1e159cf387cbf25cf0950cdd8194a21d45bea3 | nayan-pradhan/python | /stack.py | 2,154 | 4.1875 | 4 | # Nayan Man Singh Pradhan
# Stack Class
class Stack:
# initialize stack
def __init__(self, stack_size):
self.array = [None] * stack_size
self.stack_size = stack_size
self.top = 0
# bool to check if stack is empty or not
def isEmpty (self):
print("Stack is empty? -> ", end = '')
return self.top == 0
# add elements to stack
def push(self, elem):
if self.top == self.stack_size:
return "stack overflow! unable to push {}!".format(elem)
self.array[self.top] = elem
self.top = self.top + 1
return ("{} pushed to stack!".format(elem))
# remove elements from stack
def pop(self):
if self.top == 0:
return "stack underflow! nothing to pop!"
temp = self.array[self.top - 1]
del self.array[self.top - 1]
self.top = self.top - 1
return ("popping {}".format(temp)) # printing what is popped
def topElem(self):
if self.top != 0:
print ("top elem is", end = ' ')
return self.array[self.top-1]
else:
return "stack underflow! no top element!"
# print stack
def print(self):
if self.top == 0:
print ("nothing to print!")
else:
for elem in self.array:
if elem != None:
print("{}".format(elem), end = ' ')
print()
# stack1
myStack1 = Stack(2)
print(myStack1.isEmpty())
print(myStack1.push(1))
print(myStack1.isEmpty())
print(myStack1.push(2))
print(myStack1.push(3))
print(myStack1.isEmpty())
myStack1.print()
print(myStack1.topElem())
print(myStack1.pop())
myStack1.print()
print(myStack1.pop())
print(myStack1.pop())
myStack1.print()
print(myStack1.isEmpty())
# stack2
myStack2 = Stack(5)
print(myStack2.isEmpty())
print(myStack2.push(1))
print(myStack2.isEmpty())
print(myStack2.push(2))
myStack2.print()
print(myStack2.push(3))
print(myStack2.push(4))
print(myStack2.isEmpty())
myStack2.print()
print(myStack2.topElem())
print(myStack2.pop())
myStack2.print()
print(myStack2.pop())
print(myStack2.pop())
myStack2.print()
print(myStack2.isEmpty()) | true |
262c8c4d6e135d5e7c18bea7efe5f5ad968006c0 | kauserahmed/rock_paper_scissors_game | /rock_paper_scissors_game.py | 1,282 | 4.1875 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
game_img = [rock, paper, scissors]
user_choice = int(input("What do you choose? Type 0 for Rock, 1 for paper or 2 for Scissors.\n"))
if user_choice == 0:
print("Your choice Rock: " + rock)
elif user_choice == 1:
print("Your choice paper" + paper)
elif user_choice == 2:
print("Your choice scissors" + scissors)
computer_chose = random.randint(0, 2)
print("computer_chose: " + game_img[computer_chose])
if user_choice >= 3 or user_choice <0 :
print("You insert invalid number. You lose.")
if user_choice == 0 and computer_chose == 2:
print("You win")
if user_choice == 1 and computer_chose == 0:
print("You win")
if user_choice == 2 and computer_chose == 1:
print("You win")
if user_choice == 0 and computer_chose == 1:
print("You lose")
if user_choice == 1 and computer_chose == 2:
print("You lose")
if user_choice == 2 and computer_chose == 0:
print("You lose")
if user_choice == computer_chose:
print("Game draw")
| false |
5ee0fc5ac97c785c83ae956918ac9b85b66f1f0e | BryantLuu/daily-coding-problems | /15 - pick a random number from a stream given limited memory space.py | 1,088 | 4.15625 | 4 | """
Good morning. Here's your coding interview problem for today.
This problem was asked by Facebook.
Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
Upgrade to premium and get in-depth solutions to every problem.
If you liked this problem, feel free to forward it along! As always, shoot us an email if there's anything we can help with!
"""
def generator_function():
for i in range(10):
yield i
random_select_if_known_size(stream, size):
count = 1
random_int = random.randint(1, size)
for item in stream:
if count == random_int:
return item
count += 1
def random_select_if_unknown_size(stream):
count = 1
selected_item = None
for item in stream:
random_int = random.randint(1, count)
# Initial value and then pick every value in the stream with a 1/n chance
if selected_item == None or random_int != count:
selected_item = item
return selected_item
random_select_if_unknown_size(generator_function())
| true |
846a9d273b15a562439a612c84ea911381a3d446 | BryantLuu/daily-coding-problems | /12 - N steps generic fib.py | 1,088 | 4.21875 | 4 | """
Good morning. Here's your coding interview problem for today.
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
Upgrade to premium and get in-depth solutions to every problem.
If you liked this problem, feel free to forward it along! As always, shoot us an email if there's anything we can help with!
"""
"""
Solution:
General fibonacci sequence
"""
def staircase(n, X):
cache = [0 for _ in range(n + 1)]
cache[0] = 1
for i in range(n + 1):
cache[i] += sum(cache[i - x] for x in X if i - x > 0)
cache[i] += 1 if i in X else 0
return cache[-1]
| true |
fe1e91d58da2d16bb07a1cacc30639f60d250bc6 | vishnuster/python | /guess the number.py | 320 | 4.125 | 4 | #This program will ask you to guess a number
import random
a=random.randint(1,20)
while True:
b=int(input("Guess the number"))
if (b < a):
print("You have entered less")
elif(b > a):
print("You have entered greater")
else:
print("You have guessed it right. It's",b)
continue
| true |
cbe00582a3809efa45860c4cec2cc93f16cc25a7 | vishnuster/python | /Validating_Postal_Codes.py | 698 | 4.1875 | 4 |
"""A postal code must be a number in the range of (100000,999999).
A postal code must not contain more than one alternating repetitive digit pair.
Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them."""
for i in range (100000,999999):
a=list(str(i))
count=0
if(a[0]==a[2]):
count=count+1
if(a[1]==a[3]):
count=count+1
if(a[2]==a[4]):
count=count+1
if(a[3]==a[5]):
count=count+1
if(count > 1):
print(i,"is not valid")
else:
print(i,"is valid")
| true |
b0cd6913d7348dae9d6ac6decd54597410edc4ae | MrAnonymous5635/ICS-201d | /quiz_answers.py | 528 | 4.3125 | 4 |
name = "Dave"
print(f"Hello, {name}")
print("Hello, {}!".format(name))
print("Hello, " + name + "!")
# --------2-----------
m = 1
x = 2
b = 3
y = m * x + b
print(f"When x is {x}, y is {y}")
# ----3-----
length = 2
width = 3
area = length * width
perimeter = length * 2 + width * 2
print(f"Area: {area}, Perimeter: {perimeter}")
# ------4--------
people = 2
avg_slices = 3
slices_per_pizza = 8
slices_needed = people * avg_slices
pizzas_needed = slices_needed / slices_per_pizza
print(f"You need {pizzas_needed} pizzas")
| false |
28064a9d6b548dcbafbfa320f92f8ed73a089749 | abhinavramkumar/basic-python-programs | /divisors.py | 465 | 4.25 | 4 | # Create a program that asks the user for a number and then prints out a list
# of all the divisors of that number. (If you don’t know what a divisor is,
# it is a number that divides evenly into another number.
# For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
number = int(input("Find divisors for "))
numbers_list = list(range(1, number + 1))
res = []
for n in numbers_list:
if number % n == 0:
res.append(n)
print(res)
| true |
c510831fdef3482c6394535297180366c2d7741a | Did-you-eat-my-burrito/employee_class_homework | /main.py | 2,344 | 4.25 | 4 | from employee_class import Employee
print("*==================================*")
print("* 1. show employee list *")
print("* 2. add employee *")
print("* 3. update employee *")
print("* 4. delete employee *")
print("* 5. quit app *")
print("*==================================*")
employees = []
while True:
input_number = int(input("insert number >>>> "))
if input_number == 1:
number = 0
for info in employees:
print(number," :Name: ",info.name)
number += 1
elif input_number == 2:
add_employee_name = input("insert employee's name >>>> ")
add_employee_age = int(input("insert age >>>> "))
add_employee_phone_number = int(input("insert phone number >>>> "))
add_employee_id = int(input("insert id >>>> "))
employee = Employee(add_employee_name,add_employee_age,add_employee_phone_number,add_employee_id)
employees.append(employee)
print("new employee added >>>> {}".format(employee.name))
elif input_number == 3:
number = 0
for info in employees:
print(number," :Name: ",info.name)
number += 1
before_employee = int(input("insert number of employee to change"))
add_employee_name = input("insert new employee's name >>>> ")
add_employee_age = int(input("insert age >>>> "))
add_employee_phone_number = int(input("insert phone number >>>> "))
add_employee_id = int(input("insert id >>>> "))
employee = Employee(add_employee_name,add_employee_age,add_employee_phone_number,add_employee_id)
employees[before_employee] = employee
print("[] is a added".format(add_employee_name))
elif input_number == 4:
number = 0
for info in employees:
print(number," :Name: ",info.name)
number += 1
delete_employees = int(input("insert the number of employee to delete >>>> "))
print("{} is deleted ".format(employees[delete_employees]))
employees.pop(delete_employees)
elif input_number == 5:
break
else:
print("this number does not exist")
print("exit")
| true |
4b3ba75135a3c8bcdb993db2b2f7bdd946aa6916 | sol83/python-simple_programs_5 | /Parameters & Return/print_multiple.py | 807 | 4.6875 | 5 | """
Print multiple
Fill out print_multiple(message, repeats), which takes as parameters a string message to print, and an integer repeats number of times to print message. We've written the main() function for you, which prompts the user for a message and a number of repeats.
Here's a sample run of the program:
$ python print_multiple.py
Please type a message: Hello!
Enter a number of times to repeat your message: 6
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
"""
def print_multiple(message, repeats):
# write your code below!
for i in range(repeats):
print(message)
def main():
message = input("Please type a message: ")
repeats = int(input("Enter a number of times to repeat your message: "))
print_multiple(message, repeats)
if __name__ == "__main__":
main()
| true |
b78d609b110056b35c2273ef9c9324a650e4be75 | ashishvista/geeks | /geekforgeeks/merge_sort.py | 1,106 | 4.125 | 4 | # User function Template for python3
def mergeSort(arr):
new_arr = divide(arr, 0, len(arr) - 1)
for i in range(len(new_arr)):
arr[i] = new_arr[i]
def divide(arr, low, high):
if low == high:
return [arr[low]]
mid = int((low + high) / 2)
sub1 = divide(arr, low, mid)
sub2 = divide(arr, mid + 1, high)
sub3 = []
sub1_len = len(sub1)
sub2_len = len(sub2)
i = j = 0
while i < sub1_len and j < sub2_len:
if sub1[i] <= sub2[j]:
sub3.append(sub1[i])
i += 1
else:
sub3.append(sub2[j])
j += 1
while i < sub1_len:
sub3.append(sub1[i])
i += 1
while j < sub2_len:
sub3.append(sub2[j])
j += 1
return sub3
# add code here
# {
# Driver Code Starts
# Initial Template for Python 3
if __name__ == "__main__":
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
mergeSort(arr)
for i in range(n):
print(arr[i], end=" ")
print()
# } Driver Code Ends
| false |
2f61edad23612fdfe7e9a3194f4dfc035f934db8 | Yehuda1977/DI_Bootcamp | /Week9/Day2/Exercises.py | 1,809 | 4.1875 | 4 | # Exercise 1 : Built-In Functions
# Python has many built-in functions, and if you do not know how to use it, you can read document online.
# But Python has a built-in document function for every built-in functions.
# Write a program to print some Python built-in functions documents, such as abs(), int(), raw_input().
# And add documentation for your own function
def print_docs(function):
documents = eval(function + '.__doc__')
return documents
function = input('Which function do you want documentation for?')
print(print_docs(function))
# Exercise 2: Currencies
# Recreate these results
# Hint : When you add 2 currencies, if they don’t have the same label raise an error
# >>> c1 = Currency('dollar', 5)
# >>> c2 = Currency('dollar', 10)
# >>> c4 = Currency('shekel', 1)
# >>> c3 = Currency('shekel', 10)
# >>> str(c1)
# '5 dollars'
# >>> int(c1)
# 5
# >>> repr(c1)
# '5 dollars'
# >>> c1 + 5
# 10
# >>> c1 + c2
# 15
# >>> c1
# 5 dollars
# >>> c1 += 5
# >>> c1
# 10 dollars
# >>> c1 += c2
# >>> c1
# 20 dollars
# >>> c1 + c3
# TypeError: Cannot add between Currency type <dollar> and <shekel>
class Currency():
def __init__(self, kind, value):
self.kind = kind
self.value = value
def __str__(self):
return self.kind
# def __int__(self):
# return self.value
def __add__(self, other):
if isinstance(other, Currency):
return self.value + other.value
else:
return self.value + other
def __iadd__(self, other):
self.value = self.value + other
return self.value
def __repr__(self):
return str(self.value)
c1 = Currency('dollar', 5)
c2 = Currency('dollar', 10)
# print(str(c1))
# print(int(c1))
# print(int(c1))
# sum = c1 + 1
# print(sum)
# c1 += 5
# print(c1)
| true |
0a4ef8ad261499611af95096cc162f3cea0b6d9d | Yehuda1977/DI_Bootcamp | /Week7Python/Day2Feb15/dailychallengematrix.py | 1,766 | 4.59375 | 5 | # Hint: Look at the remote learning “Matrix” videos
# The matrix is a grid of strings (alphanumeric characters and spaces) with a hidden message in it.
# To decrypt the matrix, Neo reads each column from top to bottom, starting from the leftmost column, select only the alpha characters and connect them, then he replaces every group of symbols between two alpha characters by a space.
# Using his technique, try to decode this matrix:
# 7i3
# Tsi
# h%x
# i #
# sM
# $a
# #t%
# ^r!
def read_matrix(matrix):
# the matrix of arrays is reformatted based on reading each column from top to bottom,
# one new array needs to be created that contains all the characters
# a while loop is used to control which index of the array is being added in the for loop
columns = []
index = 0
while index < 3:
for element in matrix:
columns.append(element[index])
index += 1
decoded_matrix = ''
for char in columns:
# Only alphabetic characters are added to the decoded_matrix
if char.isalpha():
decoded_matrix += char
# Non alphabetic characters are replaced with a space
else:
decoded_matrix += ' '
# In order to remove extra whitespace the decoded_matrix string is split into
# an array of words (by default split splits along the space) and then joined again with only one space
decoded_matrix = ' '.join(decoded_matrix.split())
print(columns)
print(decoded_matrix)
matrix = [
['7', 'i', '3'],
['T', 's', 'i'],
['h', '%', 'x'],
['i', ' ', '#'],
['s', 'M', ' '],
['$', 'a', ' '],
['#', 't', '%'],
['^', 'r', '!'],
]
read_matrix(matrix) | true |
0ac723f1b6026fb1b19cedad93ebeda3ceb2ab3c | Yehuda1977/DI_Bootcamp | /Week6Python/Day2Feb8/dailychallenge.py | 1,348 | 4.59375 | 5 | # 1. Using the input function, ask the user for a string. The string must be 10 characters long.
# If it’s less than 10 characters, print a message which states “string not long enough”
# If it’s more than 10 characters, print a message which states “string too long”
# 2. Then, print the first and last characters of the given text
# 3. Construct the string character by character: Print the first character, then the second, then the third, until the full string is printed
# Example:
# The user enters “Hello Word”
# Then, you have to construct the string character by character
# H
# He
# Hel
# … etc
# Hello World
# 4. Swap some characters around then print the newly jumbled string (hint: look into the shuffle method)
# Example:
# Hlrolelwod
import random
string = input('Please enter a string: ')
if len(string) < 10:
print(f'The string "{string}" is not long enough')
elif len(string) > 10:
print(f'The string "{string}" is too long')
print(string[0], string[-1])
index = 1
while index <= len(string):
print(string[0:index])
index += index
print(string)
string_array = [char for char in string]
random.shuffle(string_array)
shuffled_string = ''
for char in string_array:
shuffled_string += char
print(shuffled_string)
| true |
7cd999d480f77e97259a6da7716217ca42dac450 | cdt-data-science/cdt-tea-slides | /2015/theo/optimisation/cost_functions/Cost_Function.py | 2,685 | 4.40625 | 4 | __author__ = 'theopavlakou'
class Cost_Function(object):
"""
An abstract class that provides the interface for cost
functions. In this context, a cost function is not a
function of the data points or the targets. It is purely
a function of the parameters passed to it. Therefore,
a cost function will have the data points stored and
the targets and will assume that these are constant.
We assume that a cost function is composed as such:
mean( f(w) ) + l/2 * norm(w)**2
where f(w) is a list of functions, one for each data
point and each takes an input of dimension d and outputs
a scalar.
NOTE: This could easily be extended to vector functions.
"""
def __init__(self, X, y, l):
"""
Initialises the cost function.
:param X: An (N, d) matrix, with N being the number of
data points and d being the dimension of each.
These are the data points provided.
:param y: A (N, ) vector, where N is the number of data
points. These are the targets.
:param l: The regularisation constant which is a scalar.
"""
self.X = X
self.y = y
self.l = l
# 1/N where N is the number of data points
self.inverse_n = 1.0/self.X.shape[0]
# The number of data points
self.num = self.X.shape[0]
# The dimension of each input
self.dimension = self.X.shape[1]
def loss(self, w, indices=[]):
"""
An abstract method. This describes what is needed
to get the loss, but not how the loss is calculated.
:param w: A (self.dimension, ) vector. These are the
parameters.
:param indices: A list of indices for the data points
which are to be considered for the loss.
:return: The loss which is a scalar.
"""
pass
def derivative(self, w, indices=[]):
"""
An abstract method. This describes what is needed
to get the gradient of the loss function, but not
how the gradient of the loss function is calculated.
:param w: A (self.dimension, ) vector. These are the
parameters.
:param indices: A list of indices for the data points
which are to be considered for the
gradient of the loss function.
:return: The gradient of the loss with respect
to w for the functions specified by
indices. This is a (self.dimension, )
vector.
"""
pass
| true |
7c2886dc4ba552d982ff8e3883ad142ade94bed6 | prayasshrivastava/Python-Programming | /Name&age.py | 382 | 4.21875 | 4 | # Create a program that asks the user to enter their name and their age
#Print out a message that will tell them the year that they will turn 95 years old.
#!/usr/bin/python3
import datetime
name=input("Enter your name: ")
age =int(input("Enter your age: "))
z=95-age
x=datetime.datetime.now()
y=(x.year)
p=y+z
print(name)
print(age)
print("Year, when your age will be 95: " , p)
| true |
76d67af4f0e2a8874364d84b659a70a0771c67fb | Greesha1337/python_basic_11.05.2020 | /hw5/hw5_task5/task5.py | 890 | 4.15625 | 4 | # Lesson 5 HomeWork - Task 5
"""
Создать (программно) текстовый файл,
записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
while True:
try:
with open('numbers.txt', 'w+') as file:
numbers = input('Введите числа через пробел для записи в файл: ')
file.writelines(numbers)
user_number = numbers.split()
print(f'Сумма чисел в файле: {sum(map(float, user_number))}')
break
except ValueError:
print('Неправильный ввод')
except IOError:
print('Ошибка ввода-вывода')
file.close()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.