blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
1d8b1bac521dfdfd75d71fb04dfc72af0ec84147 | brendon977/programas_Python | /conversão_números.py | 730 | 4.34375 | 4 | #Escreva um programa que leia um numero inteiro qualquer
#e peça para o usuario escolher qual será a base de conversão.
#-1 para binário
#-2 para octal
#-3 para hexadecimal
num= int(input("Digite um número inteiro: "))
print('''Escolha uma das bases para conversão:
[1] converter para BINÁRIO
[2] converter para OCTAL
[3] converter para HEXADECIMAL''')
opcao = int(input('Sua opção: '))
if opcao == 1:
print('{} convertido para BINÁRIO é igual a {}'.format(num,bin(num)))
elif opcao == 2:
print("{} convertido para OCTAL é igual a {}".format(num,oct(num)))
elif opcao == 3:
print("{} convertido para HEXADECIMAL é igual a {}".format(num,hex((num))))
else:
print('Opção inválida. Tente novamente')
|
9a4cfbfe012515eeba7d803fe42cb55bfa451a24 | YordanPetrovDS/Python_Fundamentals | /_5_BASIC SYNTAX, CONDITIONAL STATEMENTS AND LOOPS/_4_Number_Between_1_and_100.py | 240 | 4 | 4 | number = float(input())
# while number not in (range(1, 101)):
# number = float(input())
# else:
# print(number)
while number < 1 or number > 100:
number = float(input())
print(f'The number {number:.0f} is between 1 and 100')
|
c62f85784072398e38232c9d866c58c1af2ebb4f | alephist/edabit-coding-challenges | /python/test/test_lowercase_uppercase_map.py | 682 | 3.828125 | 4 | import unittest
from typing import Dict, List, Tuple
from lowercase_uppercase_map import mapping
test_values: Tuple[Tuple[List[str], Dict[str, str]]] = (
(["a", "b", "c"], {"a": "A", "b": "B", "c": "C"}),
(["p", "s", "t"], {"p": "P", "s": "S", "t": "T"}),
(["a", "v", "y", "z"], {"a": "A", "v": "V", "y": "Y", "z": "Z"})
)
class LowercaseUppercaseMapTestCase(unittest.TestCase):
def test_return_dictionary_of_lowercase_uppercase_pair_of_letters_from_list(self):
for letters, expected_dict in test_values:
with self.subTest():
self.assertEqual(mapping(letters), expected_dict)
if __name__ == '__main__':
unittest.main()
|
505c4002f9c64f409dfca66aa86c35f511848d56 | haoccheng/pegasus | /leetcode/bst_lca.py | 582 | 3.609375 | 4 | # LCA of BST.
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
def lca(root, p, q):
if root is None:
return None
small = p.val if p.val < q.val else q.val
large = p.val if p.val > q.val else q.val
pcurr = root
while pcurr is not None:
if (small < pcurr.val) and (pcurr.val < large):
return pcurr
elif (pcurr.val == small) or (pcurr.val == large):
return pcurr
elif (large < pcurr.val):
pcurr = pcurr.left
elif (small > pcurr.val):
pcurr = pcurr.right
else:
pcurr = None
return pcurr
|
a69179a59508b2292e0b986c423257f7c494e970 | andrew-yt-wong/ITP115 | /ITP 115 .py/Assignments/ITP115_A1_Wong_Andrew.py | 1,155 | 4.15625 | 4 | # Andrew Wong, [email protected]
# ITP 115, Spring 2020
# Assignment 1
# Description:
# This program creates a Mad Libs story.
# It gets input from the user and prints output.
def main():
# Read in each word individually
animal = input("Enter an animal: ")
adj = input("Enter an adjective: ")
adj2 = input("Enter another adjective: ")
verb = input("Enter a verb: ")
ing = input("Enter a verb that ends with 'ing': ")
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a second number: "))
num3 = int(input("Enter a third number: "))
dec = float(input("Enter a number with a decimal: "))
# print out the story with quotes around the words
print("\nToday, Ricky the \"" + adj + "\" \"" + animal + "\"",
"plans to \"" + verb + "\" for \"" + str(dec) + "\"",
"hours.\nHe did it for \"" + str(num1) + "\" hours the day before yesterday",
"and \"" + str(num2) + "\" hours\nyesterday with a current",
"total of \"" + str(num1+num2) + "\" hours.",
"Tomorrow he is \"" + ing + "\"\nfor \"" + str(num3) + "\" hours,",
"how \"" + adj2 + "\" right?")
main()
|
3f611464bcaf3903390e6805299ccd4cc2c7805c | Cbkhare/Codes | /IB_Linked_List_Swap_Pair.py | 603 | 3.609375 | 4 | class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def swapPairs(self, A):
swap = False
old = None
told = None
head = None
while A:
nxt = A.next
if swap:
if told: told.next = A
A.next = old
old.next = nxt
if not head:
head = A
swap = False
told = old
else:
old = A
swap = True
A = nxt
return head |
00d31adfac08c34e575b0a66cab50636ef43083e | ansoncoding/CTCI | /Python/01_Strings_Arrays/CompressString.py | 882 | 3.796875 | 4 | def compress(string):
length = len(string)
if (length < 2):
return string
result = ""
i = 0
while i < length:
count = 0
char = string[i]
result += char
while ((i < length) and (char == string[i])):
count += 1
i += 1
result += str(count)
if (len(result) > length):
return string
return result
def compress_efficient(string):
result_list = []
length = len(string)
if (length < 2):
return string
i = 0
while i < length:
count = 0
char = string[i]
result_list.append(char)
while ((i < length) and (char == string[i])):
count += 1
i += 1
result_list.append(str(count))
result = ''.join(result_list)
if (len(result) > length):
return string
return result
|
982cbde5707b3e740ef329acd31a288c55b609e1 | lapatka-py/mipt_course_ap | /homework5/ex_4_w5.py | 415 | 3.8125 | 4 | class Shape():
def __init__(self, number_1, number_2):
self.height = int(number_1)
self.wide = int(number_2)
class Triangle(Shape):
def area(self):
return 0.5 * self.height * self.wide
class Rectangle(Shape):
def area(self):
return self.height * self.wide
area1 = Triangle(5, 5)
area2 = Rectangle(5, 5)
print(area1.area())
print(area2.area())
|
19ab29a46e6f58045323d02bde897c7d21a58aab | pengyuhou/git_test1 | /leetcode/147. 对链表进行插入排序.py | 885 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
cur1 = head
ret = []
while cur1:
ret.append(cur1.val)
cur1 = cur1.next
for i in range(1, len(ret)):
key = ret[i]
j = i - 1
while j >= 0 and key < ret[j]:
ret[j + 1], ret[j] = ret[j], key
j -= 1
a = ListNode(-1)
tmp = a
while a:
a.next = ListNode(ret.pop(0))
a = a.next
return tmp.next
a = [4,3,1]
print(len(a))
print(a)
index = 0
l = len(a)
for i in range(1, l):
key = a[i]
j = i - 1
while j >= 0 and key < a[j]:
a[j + 1],a[j] = a[j],key
j -= 1
print(len(a))
print(a)
|
c3e690c68704c30d71d6cfa2ea1b38bc3970fcc8 | hz336/Algorithm | /LintCode/Binary Tree/Tweaked Identical Binary Tree.py | 1,359 | 4.03125 | 4 | """
Check two given binary trees are identical or not. Assuming any number of tweaks are allowed. A tweak is defined as a swap of the children of one
node in the tree.
Notice
There is no two nodes with the same value in the tree.
Example
1 1
/ \ / \
2 3 and 3 2
/ \
4 4
are identical.
1 1
/ \ / \
2 3 and 3 2
/ /
4 4
are not identical.
"""
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
class Solution:
"""
@param: a: the root of binary tree a.
@param: b: the root of binary tree b.
@return: true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
# write your code here
if a is None and b is None:
return True
if a is None and b is not None:
return False
if a is not None and b is None:
return False
if a.val != b.val:
return False
return self.isTweakedIdentical(a.right, b.right) and self.isTweakedIdentical(a.left, b.left) or \
self.isTweakedIdentical(a.right, b.left) and self.isTweakedIdentical(a.left, b.right)
|
8d1ef27c358fa79247a38d318a5edb7f2b3ad7cc | pravallika231980/python_fullstack | /PythonFiles/prime.py | 328 | 4.15625 | 4 | num=int(input("enter the value:"))
if num>1:
if num==2:
print("number is prime")
for i in range(2,num):
if num%i==0:
print("Given number is not prime")
break
else:
print("it is prime number")
break
else:
print("Given number is not prime number")
|
472cc1dd14550479022ba75e76b5c764677cd1dc | marceloFA/grafos | /graph.py | 8,510 | 3.921875 | 4 | from vertice import Vertice
from operator import itemgetter
from random import choice
class Graph:
''' Represents a graph through python's dictionaries'''
def __init__(self,vertices=[]):
''' Creates a graph
Arguments:
vertices: A list of vertices to be added to the graph. Can be empty
'''
#Instance variable to represent a graph:
self.vertices_dict = {}
# If there are vertices to be added, add them:
if vertices:
for key in vertices:
self.vertices_dict[key] = Vertice(key)
self.n_vertices = len(vertices)
self.n_edges = 0
def add_vertice(self,vertice):
''' Adds a new vertice
Arguements:
key: name of vertice to be added
TODO:
-chck to see if there's already a vertice named key before adding it, and throw exeption if it happens
'''
#if vertice is not int
if not isinstance(vertice,int):
raise ValueError("Vertice must be an int")
return
#if vertice already exists:
if vertice in self.vertices_dict.keys():
raise ValueError('Vertice {} already exists in graph'.format(vertice))
return
self.vertices_dict[vertice] = Vertice(vertice)
self.n_vertices = self.n_vertices + 1
def add_edge(self,edge,cost=0):
''' Adds a edge to the graph
Arguments:
edge: a tuple containing the origin and destiation vertices of the edge
TODO:
'''
if len(edge) != 2:
raise ValueError('Edge must have exactly 2 vertices')
return
#unpack tuple:
origin, destination = edge
#If one of the vertices in edge is not in graph:
if origin not in self.vertices_dict:
self.add_vertice(origin)
if destination not in self.vertices_dict:
self.add_vertice(destination)
if origin != destination:
self.get_vertice(origin).new_adjacency(self.get_vertice(destination))
self.get_vertice(destination).new_adjacency(self.get_vertice(origin))
else:
self.get_vertice(origin).new_adjacency(self.get_vertice(destination))
self.n_edges += 1
def get_vertice(self,n):
''' Retrieve a single vertice named 'n'
Arguements:
n: name of the vertice to be returned
TODO:
-validate that vertice is in graph
and throw exeption if not
'''
if n in self.vertices_dict:
return self.vertices_dict[n]
else:
raise ValueError('Graph has no vertice named {}'.format(n))
def has_edge(self,edge):
'''check if edge (origin,destination) exist '''
origin, destination = edge
if origin in self.get_vertices_list():
vertice = self.get_vertice(origin)
if destination in vertice.get_adjacencies_list():
return True
return False
def get_vertices_list(self):
''' Return a list of all the graph's vertices '''
return list(self.vertices_dict.keys())
def get_vertices_dict(self):
''' Return whole vertices dictionary '''
return self.vertices_dict
def n_edges(self):
''' Return all edges contained in the graph'''
return self.n_edges
def get_adjacent_vertices(self,v):
''' Returns a list of all vertices adjacent to vertice 'v' '''
pass
def __str__(self):
pass
def has(self,n):
''' Check if the graph contains a vertice named n
Arguments:
n: vertice to be found in graph
'''
return n in self.vertices_dict
def get_degrees_list(self):
''' return a degrees list'''
return [vertice.get_degree() for key,vertice in self.vertices_dict.items()]
def get_degrees_dict(self):
''' Return a degree list containing tuples represeting (vertice_name, vertice_degree)'''
return dict([(vertice.get_name() , vertice.get_degree()) for key, vertice in self.vertices_dict.items()])
def max_degree_vertice(self):
''' Return tuple containing (vertice_name,degree_of_vertice)
TODO: must check if therse 2 vertices with same max degree
'''
degrees_dict = self.get_degrees_dict()
filter_ = lambda k: k[1]
highest_degree = max(degrees_dict.items(), key=filter_)
return highest_degree
def n_loops(self):
''' return number of loops present in the graph'''
n_loops = 0
for v in self.get_vertices_list():
#if there's a loop edge in this vertice:
if self.has_edge((v,v)):
n_loops += 1
return n_loops
def is_eulerian(self):
''' Verify if graph is eulerian (all vertices must have even degrees)'''
return all([True if degree %2 == 0 else False for degree in self.get_degrees_list()])
def has_open_eulerian_path(self):
''' Check if graph contains an open eulerian path'''
pass
def simple_represented(self):
''' Return a simple represetation of the graph'''
simple_represented = {}
for vertice in self.get_vertices_list():
simple_represented[vertice] = set(self.get_vertice(vertice).get_adjacencies_list())
return simple_represented
def dfs_search(self,start):
''' Perform a deep first search on the graph '''
graph = self.simple_represented()
time = {}
stack = [start] # Vertices to be visited
visited = set() # Vertices already visited
while stack:
vertice = stack.pop()
time[vertice] = 0
if vertice not in visited:
visited.add(vertice)
#print("Visited: "+str(visited))
stack.extend(graph[vertice] - visited)
#print('Stack: '+str(stack)+'\n')
return visited
def cormen_dfs(self):
'''Perform a deeep first search on the graph
based on Cormen algorithm for this task '''
graph = self.simple_represented()
color = {vertice: 'white' for vertice in self.get_vertices_list()}
discovery_time = {vertice: None for vertice in self.get_vertices_list()}
finish_time = {vertice: None for vertice in self.get_vertices_list()}
previous_vertice = {vertice: None for vertice in self.get_vertices_list()}
current_time = 0
for vertice in graph.keys():
if color[vertice] == 'white':
self.visit(vertice,graph,color,discovery_time,finish_time,previous_vertice,current_time)
return color,discovery_time,finish_time
def visit(self,vertice,graph,color,discovery_time,finish_time,previous_vertice,current_time):
''' Cormen's DFS helper function for visiting a vertice'''
color[vertice] = 'grey'
current_time += 1
discovery_time[vertice] = current_time
for adjacency in graph[vertice]:
if color[adjacency] == 'white':
previous_vertice[adjacency] = vertice
self.visit(adjacency,graph,color,discovery_time,finish_time,previous_vertice,current_time)
color[vertice] = 'black'
current_time += 1
finish_time[vertice] = current_time
def cormen_bfs(self,start=None):
''' Implements Cormen's BFS algorithm
start (int): optional arguement
'''
#Data structures needed:
graph = self.simple_represented()
color = {vertice: 'white' for vertice in self.get_vertices_list()}
distance_from_start = {vertice: 0 for vertice in self.get_vertices_list()} # must be changed to distance
previous_vertice = {vertice: None for vertice in self.get_vertices_list()}
queue = [] # only operations allowed are append (add to queue) and pop (remove form queue)
#BFS starts from the first vertice present in the graph definiton:
if not start:
start = next(iter(graph))
queue.append(start)
while queue:
vertice = queue.pop()
for adjacency in graph[vertice]:
if color[adjacency] == 'white':
color[adjacency] == 'grey'
distance_from_start[adjacency] = distance_from_start[vertice] + 1
previous_vertice[adjacency] = vertice
queue.append(adjacency)
color[vertice] = 'black'
return start, color, distance_from_start
def connected_components(self):
'''Finds all connected components of a graph, based on the DFS search algorithm'''
graph = self.simple_represented()
id = 0
ids = {vertice: None for vertice in self.get_vertices_list()}
for vertice in graph.keys():
#faz uma busca começando pelo vértice:
_, colors, _ = self.cormen_bfs(vertice)
#verifica quais foram marcados como preto, adiciona eles como um id novo:
for v in graph.keys():
if colors[v] == 'black' and not ids[v]:
ids[v] = id
flag = True
if flag:
id += 1
flag = False
return ids
|
af147450919f42199fc9a22d3bfd6f6ef8bf5778 | kayartaya-vinod/2020_SEP_ABB_ADV_PYTHON | /Day3/ex05.py | 663 | 3.515625 | 4 | class MyMetaClass(type):
def __new__(mcs, *args): # <-- args is always a tuple consisting of class_name, bases, attrs
# print(f'args is {args}')
class_name, bases, attrs = args
if '__str__' not in attrs:
raise Exception(f'__str__ is missing in {class_name} class, but required.')
return type(class_name, bases, attrs)
class Person(metaclass=MyMetaClass):
def __str__(self):
return ''
class Employee(Person, metaclass=MyMetaClass):
def __str__(self):
return ''
def main():
p1 = Person()
print(p1)
print(type(p1))
print(dir(p1))
if __name__ == '__main__':
main()
|
b50205b56be000aa798192fe8f96188c15b5fbdb | AndongWen/cs2019 | /07排序/05归并.py | 2,449 | 3.5 | 4 | def merge(old, new, low, mid, high):
'''用于相邻的两个子序列的归并'''
''' old:原来的列表
new:用来转移用的新列表
low, mid, high:两个子序列的下标,采用左开右闭'''
i, j, k = low, mid, low
while i < mid and j < high:
if old[i] <= old[j]:
new[k] = old[i]
i += 1
else:
new[k] = old[j]
j += 1
k += 1
# 上述循环结束时,两个子序列必有一个其中的元素没有全部转移完,此时只要
# 将剩余部分复制过去即可
while i < mid:
new[k] = old[i]
i += 1
k += 1
while j < high:
new[k] = old[j]
j += 1
k += 1
def merge_pass(old, new, slen, flen):
'''用于对原列表的遍历,依次对相邻的子序列做归并,考虑不规则的情况'''
''' old:原来的列表
new:用来转移用的新列表
slen:子序列的长度
flen:原序列的长度'''
i = 0 # 用于标记未归并的第一个元素
while i + slen*2 < flen:
merge(old, new, i, i+slen, i+slen*2)
i += slen*2
# 处理不规则的情况
if i + slen < flen: # 仍然有两个子序列,只是第二个子序列长度不到slen
merge(old, new, i, i+slen, flen)
else: # 只有一个子序列
for j in range(i, flen):
new[j] = old[j]
def merge_sort(a):
''' 将一个序列看成n个有序的子序列组成,然后让相邻的两个子序列依次归并
子序列长度翻倍,原序列中子序列的数目减半,直到子序列的数目为1,
归并才结束'''
flen = len(a)
slen = 1
b = [None] * flen # 构造一个新的与原来序列等长的序列
while slen < flen:
merge_pass(a, b, slen, flen)
slen *= 2
merge_pass(b, a, slen, flen) # 调换两个表的角色 同时如果在上一次遍历过程中,序列已经达到有序,此次遍历就是将结果存回原位
slen *= 2
def merge_sort1(list):
'''第二种版本'''
n = len(list)
if n <= 1:
return
mid = n//2
left_li = merge_sort1(list[:mid])
right_li = merge_sort1(list[mid:])
left_p = right_p = 0
result = []
while left_p < len(left_li) and right_p < len(right_li):
if left_li[left_p] <= right_li[right_p]:
result.append(left_li[left_p])
left_p += 1
else:
result.append(right_li[right_p])
right_p += 1
result += left_li[left_p:]
result += right_li[right_p:]
return result
def main():
a = [1,0,2,9,3,8,7,4,6,5]
merge_sort(a)
# merge_sort(a)
for i in a:
print(i, end = ' ')
print('')
if __name__ == "__main__":
main()
|
592ea7171b293c5948bdef3bb27f370260989c01 | sprax/1337 | /python3/test_l0280_wiggle_sort.py | 444 | 3.546875 | 4 | import unittest
from l0280_wiggle_sort import Solution
class Test(unittest.TestCase):
def test_solution(self):
l = [3, 5, 2, 1, 6, 4]
Solution().wiggleSort(l)
self.assertTrue(l[0] <= l[1] and l[1] >= l[2] and l[2] <= l[3])
self.assertTrue(l[3] >= l[4] and l[4] <= l[5])
l = [1, 2, 3, 4]
Solution().wiggleSort(l)
self.assertTrue(l[0] <= l[1] and l[1] >= l[2] and l[2] <= l[3])
|
fd4fbfc4f52b214957336dcef1d2f69026bb1047 | NoxDineen/Hangman | /Hangman.py | 602 | 3.703125 | 4 | class Hangman:
def __init__(self):
pass
def setPhrase(self, phrase):
'''set the phrase for this game'''
pass
def realPhrase(self):
'''return the real phrase without modification'''
pass
def hiddenPhrase(self):
'''return the phrase with letters replaced with the underscore character to hide them'''
pass
def hasLetter(self, letter):
'''return true if the guess exists in the phrase'''
pass
def makeGuess(self, letter):
'''Return a list of letters that have been guessed so far'''
pass
|
b2f9be19276fcc89f338bd2873d71fd441992977 | amit-jaisinghani/PythonAssignments | /lab3/polygons.py | 4,750 | 3.859375 | 4 | import sys
__author__ = 'asj8139,ass7436'
"""
Assignment 3: Polygons
Author: Amit Shyam Jaisinghani, Aditi Shailendra Singhai
This program draws polygons of decreasing sides, recursively until the shape is a triangle. It also calculates sum of
all sides of the polygons drawn.
"""
import turtle
# global constants for window dimensions
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 800
FIGURE_START_POSITION = (-100, -180)
NAME_1_START_POSITION = (600, 350)
NAME_2_START_POSITION = (600, 400)
SIDE_LENGTH = 150
SUM_OF_ALL_ANGLES_OF_POLYGON = 360
OFFSET_OF_POLYGON = 180
FILL_PEN_WIDTH = 2
STATUS_FILL = 'fill'
STATUS_UNFILL = 'unfill'
COLORS = 'purple', 'grey', 'pink', '#f9e611', '#f9104a', 'orange', 'green', '#990109', '#d8c9ca'
PEN_COLOR = 'black'
def init():
"""
Initialize for drawing. (-400, -400) is in the lower left and
(400, 400) is in the upper right.
:pre: pos (0,0), heading (east), up
:post: pos (-100,-180), heading (east), up
:return: None
"""
turtle.setworldcoordinates(-WINDOW_WIDTH / 2, -WINDOW_WIDTH / 2,
WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
turtle.up()
turtle.setheading(0)
turtle.setpos(FIGURE_START_POSITION)
turtle.title('Polygons')
write_name()
def take_input_from_the_user():
"""
Reads number of sides and status for drawing polygon from command line argument. If empty or incorrect, program exits.
:return: number of sides, status - fill, unfill
"""
if len(sys.argv) != 3:
print("Usage: You need to run program in format given below : ")
print("$ python3 polygons.py #_sides [fill|unfill]")
sys.exit(1)
sides = int(sys.argv[1])
if 3>sides or sides>8 :
print("Usage: the value of side should be between 3 and 8.")
sys.exit(1)
status = (sys.argv[2])
if status != STATUS_FILL and status != STATUS_UNFILL:
print('Usage: enter valid status [', STATUS_FILL, ' | ', STATUS_UNFILL, '].')
sys.exit(1)
return sides, status
def draw_polygon(length, sides, status):
"""
Recursively draws polygons on the vertices of main figure drawn at the heading of the vertices until the shape
is a triangle.
:pre: (relative) pos (0,0), heading (east), up
:post: (relative) pos (0,0), heading (east), up
:return: sum of length of all sides of polygon
"""
vertices, headings, sum = draw_figure(length, sides, status)
if sides == 3:
return sum
sides = sides - 1
for x in range(len(headings)):
turtle.setposition(vertices[x][0], vertices[x][1])
turtle.setheading(headings[x])
sum += draw_polygon(length/2, sides, status)
turtle.setpos(FIGURE_START_POSITION)
return sum
def draw_figure(length, sides, status):
"""
Draws polygon of sides and length specified in arguments and fills polygon with color based on value of status.
:pre: (relative) pos (0,0), heading (east), up
:post: (relative) pos (0,length), heading (east), up
:return: vertices of polygon, headings of the vertices, sum of length of all sides of polygon
"""
sum = 0
vertices = []
headings = []
turtle.down()
if status == STATUS_FILL:
turtle.pensize(FILL_PEN_WIDTH)
turtle.color(PEN_COLOR, COLORS[sides])
turtle.begin_fill()
elif status == STATUS_UNFILL:
turtle.color(COLORS[sides])
angle = (SUM_OF_ALL_ANGLES_OF_POLYGON / sides)
for x in range(sides):
vertices.append(turtle.position())
headings.append(turtle.heading() + OFFSET_OF_POLYGON)
turtle.forward(length)
sum += length
turtle.left(angle)
if status == STATUS_FILL:
turtle.end_fill()
turtle.up()
return vertices, headings, sum
def write_name():
"""
Writes authors name using turtle.write() function.
:pre: pos (0, 0), heading (east), up
:post: pos (0, 0), heading (east), up
:return: None
"""
turtle.color(PEN_COLOR)
turtle.up()
turtle.setpos(NAME_1_START_POSITION)
turtle.down()
turtle.write("Aditi Shailendra Singhai")
turtle.up()
turtle.setpos(NAME_2_START_POSITION)
turtle.down()
turtle.write("Amit Shyam Jaisinghani")
turtle.up()
turtle.setpos(FIGURE_START_POSITION)
pass
def main():
"""
The main function.
:pre: (relative) pos (0,0), heading (east), up
:post: (relative) pos (0,0), heading (east), up
:return: None
"""
sides, status = take_input_from_the_user()
init()
turtle.tracer(0, 0)
print('Sum: ', draw_polygon(SIDE_LENGTH, sides, status))
turtle.ht()
turtle.update()
turtle.mainloop()
if __name__ == '__main__':
main()
|
c5fb97b11240d4d4d1352f3e585c8e4f0ffcd279 | weirdwizardthomas/bi-zum-b182 | /state-space-search-maze/src/navigator/navigator.py | 4,386 | 4.1875 | 4 | from abc import abstractmethod
from src.exception.no_path_found_exception import NoPathFoundException
from src.maze import Maze
class Navigator:
"""
A class that handles finding a path from start to finish
Attributes
----------
maze: Maze
The maze to navigate
edges: dict
Edges between nodes, signifying that nodes are adjacent and traversable
history: list
List of all nodes visited in order
path: dict
Dictionary of all nodes on the found way from start to finish
closed: set
Set of all nodes that were visited
open: None
Collection specific to the algorithm used that contains nodes that were opened, but not visited yet
"""
def __init__(self, maze: Maze):
# data
self.maze = maze
self.edges = {}
# adapt vertices for use, i.e. extract from class to key = vertex, value = neighbours
for key in maze.vertices:
vertex = maze.vertices[key]
for neighbour in vertex.neighbours:
if key not in self.edges:
self.edges[key] = []
self.edges[key].append(neighbour)
# searching collections
self.history = [] # all visited nodes in examination order
self.path = {} # all nodes on the path from start to end
self.closed = set() # all visited nodes
self.open = None
def solve(self):
"""
Finds a path from start to finish
:raise: NoPathFoundException if no path is found from start to finish
:return: None
"""
# place the starting node
self.open_node(str(self.get_start()))
while self.open:
# fetch current node
current = self.fetch_node()
# check if node has not been visited yet
if current not in self.closed:
# save to history
self.__add_to_history(current)
# check for target
if current == str(self.__get_end()):
return self.__trace(), self.history
self.__expand(current)
# mark node as closed
self.__close_node(current)
raise NoPathFoundException(self.history)
def __add_to_history(self, current):
self.history.append(current)
def __close_node(self, current):
self.closed.add(current)
def __trace(self):
"""
Constructs a path from start to finish
:return: Sequence of nodes from start to finish
"""
path = []
start = str(self.get_start())
end = str(self.__get_end())
while start != end:
path.append(end)
end = self.path[end]
path.append(start)
return path[::-1]
def __expand(self, current):
"""
Expands a node by adding all its neighbours to open nodes
"""
neighbours = self.edges[current] if current in self.edges else []
for neighbour in neighbours:
if neighbour not in self.closed:
# save parent (path)
self.path[neighbour] = current
# add non-visited nodes
self.open_node(neighbour)
def get_start(self):
return self.maze.start
def __get_end(self):
return self.maze.end
def __get_walls(self):
return self.maze.walls.keys()
@abstractmethod
def open_node(self, node):
"""
Algorithm specific way of opening a node
"""
pass
@abstractmethod
def fetch_node(self):
"""
Algorithm specific way of retrieving a node
"""
pass
def get_solver(mode: str) -> Navigator:
from src.navigator.bfs import BFS
from src.navigator.dfs import DFS
from src.navigator.random_search import RandomSearch
from src.navigator.greedy_search import GreedySearch
from src.navigator.dijkstra import Dijkstra
from src.navigator.a_star import AStar
if mode == 'BFS':
solver = BFS
elif mode == 'DFS':
solver = DFS
elif mode == 'Random':
solver = RandomSearch
elif mode == 'Greedy':
solver = GreedySearch
elif mode == 'Dijkstra':
solver = Dijkstra
elif mode == 'A*':
solver = AStar
else:
solver = None
return solver
|
34805aa6f086d475e128d146aa8c4b7b6057914b | varshajoshi36/practice | /leetcode/python/medium/searchRange.py | 2,100 | 4.0625 | 4 | """
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]
Its a weird problem. It can be solved using just two python functions.
"""
def searchRange(nums, target):
if target in nums:
return [nums.index(target), len(nums)-1-nums[::-1].index(target)]
else:
return [-1, -1]
'''start = 0
end = len(nums) - 1
if len(nums) == 0:
return [-1, -1]
if target < nums[0] or target > nums[-1]:
return [-1, -1]
range_start = start
range_end = end
while start < end:
mid = (start + end)/2
print start, end
print 'mid', mid
if nums[mid] == target:
print "in == target"
if mid != 0 and mid != len(nums) - 1:
if nums[mid + 1] == target:
return [mid, mid + 1]
elif nums[mid - 1] == target:
return [mid -1, mid]
else:
return [mid, mid]
if mid == 0:
if nums[1] == target:
return [0, 1]
else:
return [0, 0]
if mid == len(nums) - 1:
if nums[mid - 1] == target:
return [mid -1, mid]
else:
return [mid, mid]
if nums[mid] < target:
range_start = mid
start = mid + 1
else:
if range_start < range_end - 1:
if nums[mid - 1] >= target:
range_end = mid
else:
range_end = mid
end = mid
print "**", start, end
return [range_start, range_end]'''
def main():
nums = map(int, raw_input().split(','))
target = int(raw_input())
print searchRange(nums, target)
if __name__ == "__main__":
main()
|
3c680495c7f8407d8b7cd8909c766a84fc85a39f | marwasha/vehicleControl | /include/vehicleControl/recordTestData.py | 1,047 | 3.65625 | 4 | import csv
class recordTestData(object):
"""Class to print desired information"""
def __init__(self, gps, state, input, savefile="test"):
'''Sets up the csv writer and header'''
data = self.merge(gps, state, input)
csv_columns = list(data.keys())
csv_file = "/home/laptopuser/mkz/data/tests/" + savefile + ".csv"
self.csvfile = open(csv_file,'w')
self.writer = csv.DictWriter(self.csvfile,
fieldnames=csv_columns,
quoting=csv.QUOTE_NONNUMERIC)
self.writer.writeheader()
def merge(self, gps, state, input):
'''Merges the dictionarys together'''
data = {}
data.update(gps)
data.update(state)
data.update(input)
return data
def write(self, gps, state, input):
'''Merges the different dictionarys and prints the data'''
data = self.merge(gps, state, input)
self.writer.writerow(data)
#def __del__(self):
# self.csvfile.close()
|
29bc8f763d05f89cac084a1f5a9875a7726536f1 | ibykovsky/findMin | /main.py | 1,225 | 3.734375 | 4 | from math import sin
from time import sleep
# This is a sample Python script.
# Press Ctrl+F5 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press F9 to toggle the breakpoint.
def func(x):
# return (x-1.5)**2
return (x) ** 3 + x**2
def findMin(a, b, eps, f):
def printout(x, fx, fn, dx):
print(f"{x:18}\t\t{dx:18}\t\t{fx:18}\t\t{fn:18}")
x = (a + b) / 2
dx = abs((a - b) / 4)
while 1:
fx = f(x)
xn = x + dx
if xn < a or xn > b:
return (x, fx)
fn = f(xn)
df = fn - fx
printout(x, fx, fn, dx)
if abs(df) > eps:
if (df > 0):
dx = -dx / 3
x = xn
else:
return (x, fx) if fx < fn else (xn, fn)
# sleep(1)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
print(f"result = {findMin(-10, 10, 1e-9, func)}")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
525a0b07710a6b64b83e37570cffe5b43d36c074 | mnshkumar931/python-program | /list_p.py | 281 | 3.75 | 4 | l=[1,2,3,10,56,23,87,4,5,6,7]
print(l[0:3])
print(l[::-1])
print(l[-1::])
l.append(8)
print(l)
l.pop()
print(l)
l.sort()
print(l)
l.reverse()
print(l)
l1=[2,3,4,[2,4,6,8],7]
print(l1[3])
l2 = ['manish','ashish''nitesh']
print(l2[0])
print(min(l))
print(max(l))
|
3e9f9d0886a4a63a8ff556428981c0496fd50ecc | zzz136454872/leetcode | /reverseWords3.py | 208 | 3.5 | 4 |
class Solution:
def reverseWords(self, s: str) -> str:
l=s.split()
l=[i[::-1] for i in l]
return ' '.join(l)
sl=Solution()
print(sl.reverseWords("Let's take LeetCode contest"))
|
cfb4c80fb6ba6436a9c3397012d1b3c7a141a125 | offbynull/offbynull.github.io | /docs/data/learn/Bioinformatics/output/ch8_code/src/Stepik.8.15.FinalChallenge.py | 6,020 | 3.71875 | 4 | # As we mentioned earlier, gene expression analysis has a wide variety of applications, including cancer studies. In
# 1999, Uri Alon analyzed gene expression data for 2,000 genes from 40 colon tumor tissues and compared them with data
# from colon tissues belonging to 21 healthy individuals, all measured at a single time point. We can represent his data
# as a 2,000 × 61 gene expression matrix, where the first 40 columns describe tumor samples and the last 21 columns
# describe normal samples.
#
# Now, suppose you performed a gene expression experiment with a colon sample from a new patient, corresponding to a
# 62nd column in an augmented gene expression matrix. Your goal is to predict whether this patient has a colon tumor.
# Since the partition of tissues into two clusters (tumor vs. healthy) is known in advance, it may seem that classifying
# the sample from a new patient is easy. Indeed, since each patient corresponds to a point in 2,000-dimensional space,
# we can compute the center of gravity of these points for the tumor sample and for the healthy sample. Afterwards, we
# can simply check which of the two centers of gravity is closer to the new tissue.
#
# Alternatively, we could perform a blind analysis, pretending that we do not already know the classification of samples
# into cancerous vs. healthy, and analyze the resulting 2,000 x 62 expression matrix to divide the 62 samples into two
# clusters. If we obtain a cluster consisting predominantly of cancer tissues, this cluster may help us diagnose colon
# cancer.
#
# Final Challenge: These approaches may seem straightforward, but it is unlikely that either of them will reliably
# diagnose the new patient. Why do you think this is? Given Alon’s 2,000 × 61 gene expression matrix and gene data from
# a new patient, derive a superior approach to evaluate whether this patient is likely to have a colon tumor.
import random
import statistics
import tarfile
from math import log2
# Load
from statistics import mean, stdev
with tarfile.open('cancer_dataset.tar.xz', 'r:xz') as t:
with t.extractfile('colon_healthy.txt') as f:
healthy_samples_str = f.read().decode('utf-8')
healthy_samples = [[float(e) for e in l.split()] for l in healthy_samples_str.split('\n')]
with t.extractfile('colon_cancer.txt') as f:
cancer_samples_str = f.read().decode('utf-8')
cancer_samples = [[float(e) for e in l.split()] for l in cancer_samples_str.split('\n')]
with t.extractfile('colon_test.txt') as f:
unknown_sample_str = f.read().decode('utf-8')
unknown_sample = [float(e) for e in unknown_sample_str.split()]
def test(healthy_samples, cancer_samples, unknown_sample):
# Calculate average
healthy_sample_gene_avgs = []
cancer_sample_gene_avgs = []
for i in range(0, 2000):
healthy_sample_gene_avgs.append(mean(r[i] for r in healthy_samples))
cancer_sample_gene_avgs.append(mean(r[i] for r in cancer_samples))
# Apply logarithms
healthy_samples_logged = [[log2(e) for e in r] for r in healthy_samples]
cancer_samples_logged = [[log2(e) for e in r] for r in cancer_samples]
unknown_sample = [log2(e) for e in unknown_sample]
healthy_sample_gene_avgs_logged = [log2(e) for e in healthy_sample_gene_avgs]
cancer_sample_gene_avgs_logged = [log2(e) for e in cancer_sample_gene_avgs]
# Find genes with vastly different average for healthy vs cancer, then see which mean the unknown is closer to
genes_above_threshold = []
healthy = 0
cancer = 0
for i in range(0, 2000):
logged_healthy_i_list = [s[i] for s in healthy_samples_logged]
logged_cancer_i_list = [s[i] for s in cancer_samples_logged]
logged_avg_offset = abs(healthy_sample_gene_avgs_logged[i] - cancer_sample_gene_avgs_logged[i])
if logged_avg_offset < 1.7:
continue
# print(f'===={i}====')
# print(f'{min(logged_healthy_i_list)=} {max(logged_healthy_i_list)=}')
# print(f'{min(logged_cancer_i_list)=} {max(logged_cancer_i_list)=}')
dist_to_healthy_mean = abs(healthy_sample_gene_avgs_logged[i] - unknown_sample[i])
dist_to_cancer_mean = abs(cancer_sample_gene_avgs_logged[i] - unknown_sample[i])
if dist_to_cancer_mean < dist_to_healthy_mean:
# print(f'CANCER IDENTIFIED: {dist_to_healthy_mean=} vs {dist_to_cancer_mean=}')
cancer += 1
else:
# print(f'HEALTHY IDENTIFIED: {dist_to_healthy_mean=} vs {dist_to_cancer_mean=}')
healthy += 1
genes_above_threshold.append(i)
# print(f'------------------------')
# print(f'{len(genes_above_threshold)=}')
# print(f'{healthy=}')
# print(f'{cancer=}')
return healthy, cancer
healthy_samples_cnts = []
for i, s in enumerate(healthy_samples):
local_healthy_samples = healthy_samples[:]
local_healthy_samples.pop(i)
local_unknown_sample = s
healthy_cnt, cancer_cnt = test(local_healthy_samples, cancer_samples, local_unknown_sample)
healthy_samples_cnts.append((healthy_cnt, cancer_cnt))
print(f'When healthy_samples[{i}] is removed as the unknown sample, it\'s identified as having cancer % of {(cancer_cnt / (healthy_cnt + cancer_cnt)):.2f}')
print('-----')
cancer_samples_cnts = []
for i, s in enumerate(cancer_samples):
local_cancer_samples = cancer_samples[:]
local_cancer_samples.pop(i)
local_unknown_sample = s
healthy_cnt, cancer_cnt = test(healthy_samples, local_cancer_samples, local_unknown_sample)
cancer_samples_cnts.append((healthy_cnt, cancer_cnt))
print(f'When cancer_samples[{i}] is removed as the unknown sample, it\'s identified as having cancer % of {(cancer_cnt / (healthy_cnt + cancer_cnt)):.2f}')
print('-----')
unknown_healthy_cnt, unknown_cancer_cnt = test(healthy_samples, cancer_samples, unknown_sample)
print(f'For the actual unknown sample, it\'s identified as having cancer % of {(unknown_cancer_cnt / (unknown_healthy_cnt + unknown_cancer_cnt)):.2f}') |
b84a22cef859f05578bb8120d23f40262d597baf | ovsienko/Itea-python | /2_lesson/shop.py | 577 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Shop:
_total = 0
def __init__(self, name, sells):
self.name = name
self.sells = sells
Shop._total += sells
def get_total(self):
return self._total
def set_sells(self, sells):
self.sells += sells
Shop._total += sells
total = property(get_total, None, None, 'total')
achan = Shop('Achan', 100)
print(achan.sells)
achan.set_sells(10)
print(achan.sells)
print(achan.get_total())
atb = Shop('ATB', 3)
print(atb.sells)
print(atb.get_total())
print(atb.total) |
14258acf8fd2484435a0080983af3a0be88df7cd | TimMKChang/AlgorithmSampleCode | /DynamicProgramming/PalindromePartitioning.py | 1,008 | 3.8125 | 4 | from typing import List
class Solution:
def __init__(self):
self.is_palindrome = None
self.ans = None
def find_palindrome(self, s):
self.is_palindrome = [[False for _ in range(len(s)+1)] for _ in range(len(s)+1)]
for j in range(len(s)):
for i in range(0, j+1):
if (s[i] == s[j]) and ( j - i < 2 or self.is_palindrome[i+1][j-1]):
self.is_palindrome[i][j] = True
def helper(self, start, s, palindromes):
if (start == len(s)):
self.ans.append(palindromes[:])
for i in range(start, len(s)):
if (self.is_palindrome[start][i]):
palindromes.append(s[start:i+1])
self.helper(i+1, s, palindromes)
palindromes.pop()
def partition(self, s: str) -> List[List[str]]:
self.find_palindrome(s)
self.ans = []
self.helper(0, s, [])
return self.ans
s = Solution()
input = "abaca"
print(s.partition(input)) |
5849e4679bd8f30e39ba3a474a49589c2d722286 | haodayitoutou/Algorithms | /ch2_heap_sort.py | 626 | 3.734375 | 4 | def sink(nums, idx, length):
while idx <= length // 2:
j = idx * 2
if j < length and nums[j] < nums[j + 1]:
j += 1
if nums[idx] >= nums[j]:
break
nums[idx], nums[j] = nums[j], nums[idx]
idx = j
def heap_sort(nums):
length = len(nums) - 1
for k in reversed(range(1, length // 2 + 1)):
sink(nums, k, length)
while length > 1:
nums[1], nums[length] = nums[length], nums[1]
length -= 1
sink(nums, 1, length)
return nums
print(
heap_sort(["0", "S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"])
)
|
aefe8015d0ba257eda2ef2b9461c09b7af58fb9c | Abdullahtmk/Coursera-interactivePython | /week3/Exercisea/user46_DvNYgHst4Y_0.py | 396 | 4.25 | 4 | # Display an X
###################################################
# Student should add code where relevant to the following.
import simplegui
# Draw handler
def draw(canvas):
canvas.draw_text("X",[0,36],48,"Red")
# Create frame and assign callbacks to event handlers
frame=simplegui.create_frame("Display X",96,96)
frame.set_draw_handler(draw)
# Start the frame animation
frame.start() |
d5078743a5d6e107bc91e77e557bbb731979e8af | XisnZhang/learning | /machine_learning/ensemble_learning/bootstrap.py | 442 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def bootstrap(samples):
"""
有放回地随机选择
"""
length = len(samples)
result = []
for _ in range(length):
result.append(random.choice(samples))
return result
if __name__ == '__main__':
samples = [1, 2, 3, 4, 5]
print(bootstrap(samples)) # [5, 2, 5, 2, 2]
print(bootstrap(samples)) # [3, 1, 3, 5, 3]
|
4356c8675b998a1013f1c4b3487a9cbac18302e6 | lzwjava/curiosity-courses | /oj/items.py | 469 | 3.625 | 4 | class Solution:
def countMatches(self, items: [[str]], ruleKey: str, ruleValue: str) -> int:
i = 0
if ruleKey == "type":
i = 0
elif ruleKey == "color":
i = 1
else:
i = 2
n = 0
for item in items:
if item[i] == ruleValue:
n +=1
return n
# print(Solution().countMatches([["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], "color", "silver"))
|
1076ac74ba4d3d884ec4279172d4505bee9fc079 | KipTheFury/Python | /RedditDailyChallenges/EasyChallenges/bottles_of_beer.py | 759 | 4.125 | 4 | '''
write a program that will print the song "99 bottles of beer on the wall".
for extra credit, do not allow the program to print each loop on a new line.
Created on 12 Aug 2014
@author: kbennett
'''
bottles = 99
while bottles > 0:
if bottles > 1:
print "%d bottles of beer on the wall\n%d bottles of beer" % (bottles, bottles)
else:
print "%d bottle of beer on the wall\n%d bottle of beer" % (bottles, bottles)
print "take one down, pass it around"
bottles -= 1
if bottles > 1:
print "%d bottles of beer on the wall\n" % bottles
elif bottles > 0:
print "%d bottle of beer on the wall\n" % bottles
else:
print "No more bottles of beer on the wall" |
3c05a24f309169a753b3574a2c5f5a00e9fe4046 | undersfx/python-para-zumbis | /exerc_word_count_alice.py | 809 | 3.75 | 4 | #Importa lib de string para utilizar as pontuações
import string
word = 'alice'
#Abre arquivo alice.txt em alice
with open('alice.txt', encoding="utf8") as alice:
#carrega o texto de alice em uma variavel.
texto = alice.read()
#Converte tudo para minusculo
texto = texto.lower()
#Substitui todos os caracteres de pontuação por ' '
for x in string.punctuation:
texto = texto.replace(x, ' ')
#Quebra o texto em uma list com base no espaço em branco
texto = texto.split()
#Cria um dicionario e popula o mesmo com o valor de palavras adicionando 1 caso já exista
d = {}
for p in texto:
if p not in d:
d[p] = 1
else:
d[p] += 1
#Mostra o total somado correspondente ao indice 'alice'
print('A palavra "'+ word + '" aparece %s vezes.' %d[word]) |
325f802eab1f2add538e97debbb27c85cde2e500 | deltonmyalil/MachineLearningAndDS | /MachineLearning/Machine Learning A-Z Template Folder/Part 2 - Regression/Section 4 - Simple Linear Regression/mySimpleLinearRegression.py | 1,833 | 4.0625 | 4 | # My own Simple Linear Regression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv') # Replace with filename
X = dataset.iloc[:, :-1].values # It's fine because most datasets will contain depVar in the last col
y = dataset.iloc[:, 1].values # Need to change with the index of last col
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # you may choose your own test size
# Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
sc_y = StandardScaler()
y_train = sc_y.fit_transform(y_train)"""
# Preprocessing done
# Simple Linear Regression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
# Fit the regressor object to the training set
regressor.fit(X_train, y_train)
# It learned the correlations between X_train and y_train
# Predicting the test set results
y_pred = regressor.predict(X_test)
# Visualizing the training results
plt.scatter(X_train, y_train, color = 'red') # actual training set data in red
plt.plot(X_train, regressor.predict(X_train), color = 'blue') # predicted data for training set - line in blue
plt.title("Salary v/s experience of training set")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
# Visualizing the test set result
plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue') # regressor is the same in both training and test
plt.title("Salary v/s experience of training set")
plt.xlabel("Years of Experience")
plt.ylabel("Salary")
plt.show()
|
fcceb7dc417bb263806409e26acad72ba2d2c4ab | ShriSiva/ShriGitHub | /gameknock_codes.py | 3,120 | 3.859375 | 4 | ## Primary Project 1 - "Python program to create a user-interface driven 'knock Knock' jokes"
## Name - Shriram Sivaraman
## Course - Introduction to Python Programming
## Course code - MSIT 3440
## Description - The objective of the program is to present a user-interface driven “knock knock” jokes where both the system
## and the user interact with each other as “person 1 and person 2” in joke format.
import random
joketot=[]
joketot.append(["yah","Noo!, Thanks I use Google"])
joketot.append(["firewall","welcome to china! Home of the great firewall"])
joketot.append(["hard drive","I had a hard drive, let me in so I can relax!!"]) ## accepting the joke's prompt and punchline
variant=["who's there","who's there?","whos there?","whos there",
"who is there","who is there?","who there?","who dere","who dere?"] ## list to get all types of who is there
random.shuffle(joketot) ## random.shuffle is used to shuffle the list containing jokes
print " Welcome to the portal of Knock-Knock jokes "
while True:
try:
times=int(raw_input("Enter the number of 'knock-knock' jokes you wanna hear ?? ")) ## To enroll the number of times to tell the joke
if times in range(1,4): ## To check the number of jokes within the range
break
else:
print ' ', times, 'is out of range' ## To print if the given input is out of range
except ValueError: ## To handle ValueError exception
print " I am expecting a number dear !! "
except KeyboardInterrupt:
exit ()
print "Prepare to be amazed "
inc=0 ## A variable which is initialized to trasverse through the list everytime for loop runs
for inc in range(times):
text1=raw_input("knock, knock !! \n")
if text1.lower() in variant:
print joketot[inc][0]
else:
## While loop made to run until the input prompt condition is satisfied
while True:
text1=raw_input(" Please type Who's there? \n")
if text1.lower() in variant:
print joketot[inc][0]
break
text2=raw_input("") ## user input based on the system prompt
if "who" in text2.lower(): ## check made if word "who" is in the input text
print joketot[inc][1]
else:
## While loop made to run until the input prompt condition is satisfied
while True:
print 'Please type '+(joketot[inc][0]+" who")
text2=raw_input("") ## user input based on the system prompt
if "who" in text2.lower():
print joketot[inc][1]
break
inc+=1
if inc<times:
print "Ha Ha!!Get ready for next joke" ## To alert the user to get ready for the next joke
else:
print "Hope you had great fun. Bye-Bye!!" ## This message gets printed after the last joke
break
|
b960c8bbd2c6cf29b5a1dca2f06965f503fc8365 | Pankaj145-pb/Front-technologies | /anacom.py | 484 | 3.640625 | 4 | from collections import Counter
def removeChar(str1, str2):
dict1 = Counter(str1)
dict2 = Counter(str2)
keys1 = dict1.keys()
keys2 = dict2.keys()
count1 = len(keys1)
count2 = len(keys2)
set1 = set(keys1)
commonKeys = len(set1.intersection(keys2))
if commonKeys == 0:
return -1
else:
return max(count1, count2) - commonKeys
if __name__ == '__main__':
str1 = 'ahe'
str2 = 'clhbae'
print(removeChar(str1, str2)) |
6f1b8e97279fbd49c208bf8877a0fa56a45f186c | jfcjlu/APER | /Python/Ch. 09. Python - Weighted Mean and Standard Deviations.py | 708 | 3.828125 | 4 | # Python - WEIGHTED MEAN AND STANDARD DEVIATIONS
from __future__ import division
import numpy as np
import math
# Enter the values given as the components of the vector x:
x = np.array([100.1, 100.2, 99.8, 100.3, 99.9, 100.2, 99.9, 100.4, 100.0, 100.3])
# Enter the corresponding weights w of the x values:
w = np.array([1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
# Evaluation
N = len(x)
wmean = np.average(x, weights=w)
variance = np.average((x-wmean)**2, weights=w)
stdev = math.sqrt(variance)
# Results
print ("N:", N)
print ("Weighted mean:", wmean)
print ("Weighted standard deviation of the sample:", stdev)
print ("Weighted standard deviation of the mean:", stdev/math.sqrt(N-1))
|
8d9bd2f5b730a398713a9e670dc7e0e85762abbc | Viper-code/HeadsTails_Dice | /Random_Dice_or_Head_and_tails.py | 688 | 4.15625 | 4 | #Please enter roll, dice or flip, coin and nothing else!
import random
import time
Dice = random.randint(1,6)
f_coin = random.randint(1,2)
start = input('please type roll to roll a dice, enter "filp" to flip a coin, enter "num" to get a random number: ')
if start.lower() == 'roll':
print(' Rolling...... ')
time.sleep(2)
print('You got a ' + str(Dice))
elif start.lower() == 'flip':
print(' Flipping.......')
time.sleep(2)
if f_coin == 1:
time.sleep(1)
print('You got HEADS')
if f_coin == 2:
time.sleep(1)
print('you go TAILS')
elif start.lower() =='num':
input('Please enter Exit ')
|
aaeccaab32cd02154216fbd26e1d73d24bf7b0c8 | RanjanShrivastva/PythonSeleniumAutomation | /PythonPrograms/PythonPrograms/Inheritence/P08_MultipleInheritance.py | 659 | 4.25 | 4 | """
Multiple Inheritance = Many parent classes but only child classes
Multiple Inheritance is also called Diamond access Problem
P_ = Parent
C = Child
GC = Grand Child
"""
class P1:
def m1(self):
print("I am parent-1 class")
class P2:
def m1(self):
print("I am Parent-2 class")
class C(P1, P2):
def m2(self):
print("I am Child Class")
# Order of argument matters based on order child class method will be called
# if methods are same in parent and child class then priority goes to child class first then
# class C(P2, P1):
# def m2(self):
# print("I am Child Class")
c = C()
c.m1()
c.m2()
# c.m3()
|
3d45f82e7ae6b199b98c35376f6993983c5e562c | XiongQiuQiu/leetcode-slove | /Algorithms/741-Cherry-Pickup.py | 3,542 | 4.25 | 4 | '''
In a N x N grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through;
1 means the cell contains a cherry, that you can pick up and pass through;
-1 means the cell contains a thorn that blocks your way.
Your task is to collect maximum number of cherries possible by following the rules below:
Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);
After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;
When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);
If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.
Example 1:
Input: grid =
[[0, 1, -1],
[1, 0, -1],
[1, 1, 1]]
Output: 5
Explanation:
The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Note:
grid is an N by N 2D array, with 1 <= N <= 50.
Each grid[i][j] is an integer in the set {-1, 0, 1}.
It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1.
'''
class Solution(object):
def cherryPickup(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
L = len(grid)
dp = [[0 for _ in range(L)] for _ in range(L)]
dp[0][0] = grid[0][0]
for t in range(1,2*L-1):
for i in range(L)[::-1]:
for p in range(L)[::-1]:
j = t-i
q = t -p
if (j<0 or q <0 or j >= L or q >= L or grid[i][j] <0 or grid[p][q] < 0):
dp[i][p] = -1
continue
if i > 0:dp[i][p] = max(dp[i][p],dp[i-1][p])
if p > 0:dp[i][p] = max(dp[i][p],dp[i][p-1])
if i>0 and p>0:
dp[i][p] = max(dp[i][p],dp[i-1][p-1])
if dp[i][p] >= 0:
second = grid[p][q] if i != p else 0
dp[i][p] += grid[i][j] + second
return max(dp[-1][-1],0)
class Solution(object):
def cherryPickup(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
dp = {}
res = self.findMaxCherries(0, 0, 0, 0, dp, grid)
return 0 if res == float('-inf') else res
def findMaxCherries(self, i1, j1, i2, j2, dp, grid):
if (i1, j1, i2, j2) in dp:
return dp[(i1, j1, i2, j2)]
n = len(grid)
if i1 == n - 1 and j1 == n - 1 and i2 == n - 1 and j2 == n - 1:
return grid[-1][-1]
if i1 >= n or i2 >= n or j1 >= n or j2 >= n:
return float('-inf')
if grid[i1][j1] == -1 or grid[i2][j2] == -1:
return float('-inf')
best = max(
self.findMaxCherries(i1 + 1, j1, i2 + 1, j2, dp, grid),
self.findMaxCherries(i1 + 1, j1, i2, j2 + 1, dp, grid),
self.findMaxCherries(i1, j1 + 1, i2 + 1, j2, dp, grid),
self.findMaxCherries(i1, j1 + 1, i2, j2 + 1, dp, grid)
)
best += grid[i1][j1] if (i1, j1) == (i2, j2) else grid[i1][j1] + grid[i2][j2]
dp[((i1, j1, i2, j2))] = best
return best |
c5ecaf96d11f4164fc3b47f430a14a70c62602b9 | Paker211/parker40105_sti | /sti_py/chapter8/8_1/9.py | 412 | 3.703125 | 4 | class Leg():
def __init__(self, num, look):
self.num = num
self.look = look
class Animal():
def __init__(self, name, leg):
self.__name = name
self.leg = leg
def show_name(self):
return self.__name
def show(self):
print(self.show_name(), ' have ', self.leg.num, ' ', self.leg.look, ' leg. ')
leg = Leg(4, 'short')
a = Animal('DOG', leg)
a.show()
|
8be4678833aa3625e2038207267038f1ba35347a | rafaelgama/Curso_Python | /CursoEmVideo/Mundo3/Exercicios/ex075.py | 1,194 | 4.1875 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceu o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
cores = {'limpa':'\033[m',
'bverde':'\033[1;32m',
'roxo':'\033[35m',
'bvermelho': '\033[1;31m',
'pretoebranco':'\033[7:30m'}
print('-=-'*8)
print(cores['pretoebranco']+'_____INICIO_____'+cores['limpa'])
print('-=-'*8)
num = ( int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')) )
print(f'Você digitou os números: {num} ')
print(f'O valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3 apareceu na {num.index(3)+1}ª posição.')
else:
print('O valor 3 não apareceu')
print(f'Os valores pares digitados foram: ', end='')
for n in num:
if n % 2 == 0:
print(f'{n} ', end='')
print('')
print('-=-'*8)
print(cores['pretoebranco']+'______FIM_______'+cores['limpa'])
print(cores['pretoebranco']+'_Code by Rafael_'+cores['limpa'])
print('-=-'*8) |
ee1549b65baa08c85953437516aba2245171c94c | Programmable-school/Python-Training | /lesson/lessonListTuple/main.py | 1,909 | 3.859375 | 4 | """
リスト型_タプル型
"""
"""
リスト型
データの配列。同型のデータを複数扱える
"""
nums1 = [0, 1, 2, 3]
print(nums1) # [0, 1, 2, 3]
print(nums1[0], nums1[3]) # 0 3
# 最後に新しい要素を追加
nums1.append(4)
print(nums1) # [0, 1, 2, 3, 4]
# 先頭に新しい要素を追加
nums1.insert(0, 5)
print(nums1) # [5, 0, 1, 2, 3, 4]
# 最後の要素を取得
last = nums1[-1]
print(last) # 4
# 値の書き換え
nums1[0] = 1000
print(nums1) # [1000, 0, 1, 2, 3, 4]
# 結合
nums2 = [200, 300, 400]
nums3 = nums1 + nums2
print(nums3) # [1000, 0, 1, 2, 3, 4, 200, 300, 400]
# 要素数
length = len(nums3)
print(length) # 9
# 存在する要素数を取得
num4 = [3, 3, 20, 30, 1, 2]
print(num4.count(3)) # 2
# 検索(要素の位置を取得)
print(nums3.index(1000)) # 0
print(nums3.index(200)) # 6
# 削除(要素を指定)
nums3.remove(1000) # [0, 1, 2, 3, 4, 200, 300, 400]
print(nums3)
# 削除(末端)
lastPop = nums3.pop()
print(lastPop, nums3) # 400 [0, 1, 2, 3, 4, 200, 300]
# 参照渡し
list1 = [0, 1, 2, 3]
print('list1', list1) # list1 [0, 1, 2, 3]
list2 = list1
list2[2] = 100
print('list1', list1) # list1 [0, 1, 100, 3]
print('list2', list2) # list2 [0, 1, 100, 3]
"""
タプル型
違う型のデータを複数扱える
"""
values = (0, 10.123, 'Hello')
print(values) # (0, 10.123, 'Hello')
print(values[0], values[2]) # 0 Hello
print(values.index('Hello')) # 2
print(values.count('Hello')) # 1
# スライス
slice_values = [10, 20, 30, 40]
# 要素の位置の1〜3番目を表示
print(slice_values[1:4]) # [20, 30, 40]
# 要素の位置の0〜1番目を表示
print(slice_values[:2]) # [10, 20]
# 要素の位置の2番目以降
print(slice_values[2:]) # [30, 40]
|
a6b87045f14e7c7001f15ea00ab81516c5c7138f | qianli2424/test11 | /qianliProject/day4/demo1.py | 576 | 3.75 | 4 | # -*- coding=utf8 -*-
#@author:qianli
# 文件说明:
userlist = [['admin',123456],['test',123456],['root',123456],['mysql',123456],['sa',123456]]
for user in userlist:
for a in user:
print(a,end='\t')
print() #什么都不做,但会换行
for x in 'abcdefg':
print(x,end='\t')
print()
for x in [1,2,3,4,5,6,7,8]:
print(x)
range(0,9) #产生0-9的整数序列数
for x in range(len(userlist)):
print(x,end='-----------')
# temp = []
# for user in userlist:
# print(user)
# name = user[0]
# temp.append(name)
# print(temp)
|
c484e4a92f6ae320794ae80c0b3c7503e62d4695 | lijubjohn/python-stuff | /algorithms/linkedlist/linkedlist.py | 1,301 | 4.3125 | 4 | """
Pros
Linked Lists have constant-time insertions and deletions in any position,
in comparison, arrays require O(n) time to do the same thing.
Linked lists can continue to expand without having to specify
their size ahead of time (remember our lectures on Array sizing
form the Array Sequence section of the course!)
Cons
To access an element in a linked list, you need to take O(k) time
to go from the head of the list to the kth element.
In contrast, arrays have constant time operations to access
elements in an array.
"""
class SinglyLinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
class DoublyLinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = DoublyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
def print_doubly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep) |
4edeac1f718d5c1f152bd0e70783c82fcc7820dc | Jerry-Bang/python-learn | /lesson3/regex.py | 414 | 3.65625 | 4 | import re
reg_exp = r"(\(.*\))|[A-Za-z0-9._-]+"
rc = re.compile(reg_exp)
def search_all(f):
pos = 0
rlt = []
while pos < len(f):
x = rc.search(f, pos)
if x:
rlt.append(x.group())
pos = x.end()
else:
break
return rlt
if __name__ == "__main__":
s = ' apple and (orange or banana ) '
result = search_all(s)
print(result)
|
734ffe9daf7a08576dcd9b98f8aca490107f3418 | Esteban-Hastamorir/calculadora | /calculadora.py | 564 | 3.953125 | 4 | def sumar (a,b):
return a + b
def restar (a,b):
return a - b
def multiplicar (a,b):
return a*b
def dividir (a,b):
return a/b
print ("Hola, como estas\n")
a1 = float (input("Ingresa la primera cifra\n"))
operacion = input ("Ingrese la operacion\n[+]Sumar\n[-]Restar\n[*]Multiplicar\n[/]Dividir\n")
b2 = float (input("Ingrese el segundo numero\n"))
if operacion == "+" :
print (sumar (a1,b2))
elif operacion == "-":
print (restar(a1,b2))
elif operacion == "*":
print (multiplicar(a1,b2))
elif operacion == "/":
print (dividir(a1,b2)) |
941b1e4cadb9c055b586ba8039f026ecaa81e54f | laogenglgll/python | /33.PY | 1,091 | 3.9375 | 4 | #__ iter__():返回迭代器本身;
#__ next__():这里写迭代的规律
import datetime as dt
class IteR:
def __iter__(self):
return self
class YeaR:
def __init__(self,before):
self.now = dt.date.today().year
self.before = before
self.c=[]
def RyeaR(self,year):
if (year%4 == 0 and year%100 != 0) or (year%400 == 0):
return True
else:
return False
def years(self):
a=list(range(self.before,self.now))
for b in a:
if self.RyeaR(b):
self.c.append(b)
else:
pass
self.c=iter(self.c)
return self.prin()
def itER(self):
pass
def __iter__(self):
return self
def prin(self):
for i in self.c:
print(i)
self.c=iter(self.c)
year=YeaR(2000)
print(year.years())#迭代器应该没重现更新 所以还是结束时后的样子
year.prin()
#无法重置迭代器
#import 模块名 as 新名字 #调用模块时比较好用
|
c9960530e5d04484924c3f870c1696019c72c3d1 | kickass9797/Testing | /rand/graph.py | 4,025 | 3.515625 | 4 | #Undirected, unweighted Graph
class Graph(object):
def __init__(self, graph_dict=None):
if graph_dict in [0,None]:
graph_dict = {}
if type(graph_dict) is int:
if graph_dict < 0:
raise ValueError("Number of nodes can't be negative")
self.__graph_dict = {}
for i in range(1,graph_dict+1):
self.__graph_dict[str(i)] = []
if type(graph_dict) is dict:
self.__graph_dict = graph_dict
if type(graph_dict) is Graph:
self.__graph_dict = dict(graph_dict.__graph_dict)
def vertices(self):
if not self.__graph_dict:
return []
return list(self.__graph_dict.keys())
def len_vertices(self):
return len(self.vertices())
def edges(self):
return self.__generate_edges()
def add_vertex(self, vertex):
if vertex not in self.__graph_dict:
self.__graph_dict[vertex] = []
def add_edge(self, edge):
#get edge as tuple
vertex1, vertex2 = edge
self.__graph_dict[vertex1].append(vertex2)
self.__graph_dict[vertex2].append(vertex1)
def remove_edge(self, edge):
#get edge as tuple
vertex1, vertex2 = edge
self.__graph_dict[vertex1].remove(vertex2)
self.__graph_dict[vertex2].remove(vertex1)
def base(self):
if len(self.vertices()) > 0:
return self.vertices()[0]
def next_Node(self, vertex):
if not self.__graph_dict[vertex]:
return []
return self.__graph_dict[vertex][0]
def all_Node(self, vertex):
return self.__graph_dict[vertex]
def degree(self, vertex):
return len(self.__graph_dict[vertex])
def __generate_edges(self):
edges = []
for vertex in self.__graph_dict:
for neighbour in self.__graph_dict[vertex]:
edges.append((vertex, neighbour))
return edges
def is_connected(self):
if self.len_vertices() < 2: return True
visited = []
for i in self.vertices():
visited.append(False)
visited[0] = True
oStack = [self.vertices()[0]]
while len(oStack) > 0:
v = oStack.pop();
nodes = self.all_Node(v)
for i in nodes:
if not visited[int(i)]:
visited[int(i)] = True
oStack.append(i)
if False in visited:
return False
return True
def search_iterativ(self):
S = [self.base()]
visited = []
while S:
u = S.pop()
if u not in visited:
visited.append(u)
for v in reversed(self.all_Node(u)):
S.append(v)
return visited
def search_recursiv(self, u, visited=[]):
# u = startnode
visited.append(u)
for v in self.all_Node(u):
if v not in visited:
self.search_recursiv(v)
return visited
def __str__(self):
res = "vertices: "
for k in self.__graph_dict:
res += str(k) + " "
res += ("\nedges: ")
for edge in self.__generate_edges():
res += str(edge) + " "
return res
if __name__ == "__main__":
# g = { "0" : ["1","2"],
# "1" : ["0","3","4","5"],
# "2" : ["0","3"],
# "3" : ["1","2","4","5"],
# "4" : ["1","3","5","6"],
# "5" : ["1","3","4","6"],
# "6" : ["4","5"]
# }
g = { "0" : ["1","2","3"],
"1" : ["0","6"],
"2" : ["0","3","5"],
"3" : ["0","2","4"],
"4" : ["3"],
"5" : ["2"],
"6" : ["1"]
}
graph = Graph(g)
print(graph.search_iterativ())
print(graph.search_recursiv(graph.base()))
|
76e54d70654b259cc906077fec519ca3eccad3d8 | Zedmor/hackerrank-puzzles | /leetcode/73.set-matrix-zeroes.py | 1,982 | 3.71875 | 4 | #
# @lc app=leetcode id=73 lang=python3
#
# [73] Set Matrix Zeroes
#
# https://leetcode.com/problems/set-matrix-zeroes/description/
#
# algorithms
# Medium (42.40%)
# Total Accepted: 300.7K
# Total Submissions: 706.1K
# Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]'
#
# Given a m x n matrix, if an element is 0, set its entire row and column to 0.
# Do it in-place.
#
# Example 1:
#
#
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
#
#
# Example 2:
#
#
# Input:
# [
# [0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]
# ]
# Output:
# [
# [0,0,0,0],
# [0,4,5,0],
# [0,3,1,0]
# ]
#
#
# Follow up:
#
#
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best
# solution.
# Could you devise a constant space solution?
#
#
#
from typing import List
def nullify_row(matrix, i):
matrix[i] = [None] * len(matrix[0])
def nullify_col(matrix, j):
for row in matrix:
row[j] = None if row[j] != 0 else 0
class Solution:
"""
>>> Solution().setZeroes([[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]])
>>> Solution().setZeroes([[1,1,1],[1,0,1],[1,1,1]])
[[1,0,1],[0,0,0],[1,0,1]]
>>> Solution().setZeroes([[0,1,2,0],[3,4,5,2],[1,3,1,5]])
[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
"""
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
should_null_row = False
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
nullify_col(matrix, j)
should_null_row = True
if should_null_row:
nullify_row(matrix, i)
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] is None:
matrix[i][j] = 0
# return matrix
|
8ab1d7cab9b4ce8b2b506dab3184e5fa284aa8ae | dsushanta/learning-python | /com/bravo/johny/practice/class_and_objects.py | 201 | 3.828125 | 4 | class tree :
name = ""
fruit = ""
def fruit_name(self):
print(self.name+" gives : "+self.fruit)
mango = tree()
mango.name = "Mango Tree"
mango.fruit = "Mango"
mango.fruit_name()
|
349229f4d7cf8ab7c210285d89994c218dca770a | tsabbasi/data-structures-and-algorithms | /Python/linkedListImplementation.py | 1,474 | 3.953125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next_node = None
def traverse(self):
# set current node
# iterate through linked list, print nodes, until reached end of list
node = self
while node != None:
print(node.data)
node = node.next_node
# remove duplicates from a linked list
# use an array to store new values, if new node already in array, remove current node from linked list, and continue.
# removing a node: point the previous node to the node after the current node
def remove_duplicates(node):
unique_data = []
previous = None
while node != None:
print(unique_data)
if node.data in unique_data:
previous.next_node = node.next_node
else:
unique_data.append(node.data)
previous = node
node = node.next_node
def remove_dup_w_runner(node):
current = node
while current != None:
runner = current
while runner.next_node != None:
if runner.next_node.data != current.data:
runner = runner.next_node
else:
runner.next_node = runner.next_node.next_node
current = current.next_node
#Test:
node = Node(8)
node2 = Node(5)
node3 = Node(8)
node4 = Node(3)
node.next = node2
node.next_node = node2
node2.next_node = node3
node3.next_node = node4
node.traverse()
#remove_duplicates(node)
remove_dup_w_runner(node)
|
b4275909fc6f2e714909cdffe973b9f3459f2db6 | CX4Life/AdventOfCode | /advent-5.py | 784 | 3.921875 | 4 | """Day 5 of the 2017 Advent of Code challenge!"""
__author__ = 'Tim Woods'
INPUT_FILENAME = 'advent5-input.txt'
def array_from_input():
ret = []
opened = open(INPUT_FILENAME, 'r')
for line in opened:
ret.append(int(line.rstrip()))
return ret
def go_through_instructions(list_of_inst):
index = 0
hops = 0
while 0 <= index < len(list_of_inst):
add_to_current_index = list_of_inst[index]
if add_to_current_index < 3:
list_of_inst[index] += 1
else:
list_of_inst[index] -= 1
index += add_to_current_index
hops += 1
return hops
def main():
instructions = array_from_input()
hops = go_through_instructions(instructions)
print(hops)
if __name__ == '__main__':
main() |
84c6f6880ebe3b5cad80e02f6d5fdc3a2bd3447b | Wangchangchung/pystart | /day1/func.py | 1,072 | 3.953125 | 4 | # Author: Charse
# 函数
def func1():
"""testing1"""
print('in the func1')
return 0
# 过程
def func2():
'''testing2'''
print('in the func2')
x = func1()
y = func2()
print('from func1 return is %s' % x)
# 没有返回值时None
print('from func2 return is %s' % y)
def test1():
pass
def test2():
return 0
def test3():
return 0, 'hello', ['a', 'b', 'c'], {'name', 'alex'}
x = test1()
y = test2()
z = test3()
# None
print(x)
# 0
print(y)
# 输出一个元组 (0, 'hello', ['a', 'b', 'c'], {'name', 'alex'})
print(z)
def test4(x, y, z):
print(x)
print(y)
print(z)
# 实参与形参一一对应
test4(1, 2, 3)
# 通过形参的指定,那么实参入参的时候,就没有顺序
test4(x=1, y=2, z=3)
# 通过形参指定,必须在实参的后面 否则会报出错误的: 位置参数在关键字参数之后"positional argument follows keyword argument"
#test4(z=3, 1, 2)positional argument follows keyword argument
#test4(1,x=1, y=2) test4() got multiple values for argument 'x'
test4(1, z=2, y=0)
test4(1, z=2, y=0)
|
f1da618a1bbe74d9f03f1567b0f8c14eaeadb0e5 | gastonpalav/frro-soporte-2019-08 | /practico_01/ejercicio-06.py | 230 | 3.828125 | 4 | def inversa(cadena):
index = 0
invertida = ""
cant = len(cadena)
for index in range(cant):
cant -=1
invertida += invertida.join(cadena[cant])
print(invertida)
inversa(input('ingresar cadena'))
|
295f002f8a48987a7714e2fc219010e77593fc2e | GuilhermeGGM/Estudos-python | /Calculdora de fatorial.py | 159 | 4.0625 | 4 | f = int(input('Digite o número que quer ver o fatorial: '))
for c in range(f, 1, -1):
fa = f
fat = fa*(fa-1)
fato = fa*(fa-2)
print(fat, fato) |
3a7b17620816f816a30426f718ce87b28f5dc2cb | evacaiy/gy-2006A | /7/test.py | 3,305 | 3.75 | 4 | # a = 1
# b = 10
# print(a+b)
#
#
#
# a,b,c = [1,2,3]
# print(a)
# print(b)
# print(c)
#
# x,y,*z = (1,2,3,4,5)
# print(x)
# print(y)
# print(z)
#
# a = 10
# b = 20
# print(a+b)
# print(a-b)
# print(a*b)
# print(b/a)
# print(b % a)
# print(3**3)
# print(a//b)
#
# print(a==b)
# print(a!=b)
# print(a>b)
# print(a<b)
# print(a>=b)
# print(a<=b)
#
# print(a and b)
# print(a or b)
#
# x = 1,2,3,4,5
# print(1 in x)
# print(1 not in x)
#
# z = 11
# print(z % 2 == 0)
#
# z = 12331
# print(z % 10)
# z //= 10
# print(z)
#
# print(z%10)
#
# l = ("果芽","老干妈","腾讯","百度","阿里")
# if ("果芽" in l):
# print("合作方")
# else:
# print("非合作方")
#
# score = 50
# if (score < 0):
# print("请输入正确的成绩")
# if (score > 0 and score < 60):
# print("不及格")
# if (score >= 60 and score <= 70):
# print("及格")
# if (score >= 71 and score <= 80):
# print("良好")
# if (score >=81 and score <= 100):
# print("优秀")
# if (score > 100):
# print("请输入正确的成绩")
#
#
# score = 60
# if (score > 0 and score < 60):
# print("不及格")
# elif (score >= 60 and score <= 70):
# print("及格")
# elif (score >= 71 and score <= 80):
# print("良好")
# elif (score >=81 and score <= 100):
# print("优秀")
# else:
# print("请输入正确的成绩")
#
#
# score_1 = [98,55,60,23,45,56,85,79,91,92,100,86,77,96,43]
# for score in score_1:
# if (score > 0 and score < 60):
# print("不及格")
# elif (score >= 60 and score <= 70):
# print("及格")
# elif (score >= 71 and score <= 80):
# print("良好")
# elif (score >=81 and score <= 100):
# print("优秀")
# else:
# print("请输入正确的成绩")
#
#
# # 100以内数的和 不算100
# s = 0
# for i in range(100):
# s = s + i
# print(s)
#
# # range()
# # 第一个参数:起始数据 默认为0
# # 第二个参数:代表结束值,不包含边界
# # 第三个参数:步长(增量) 默认值为1
#
# for i in range(1,100,2):
# print(i)
#
# for i in range(100,0,-1):
# print(i)
#
#
# # 求出10*9*8...*1 的结果 10的阶乘 10!
# s = 1
# for i in range(10,0,-1):
# s = s * i
# print(s)
#
# 猜数字
# flag = True
# a = 62
#
# while flag:
# b = int(input("请输入数字"))
# if b > a:
# print("大了")
# elif(b < a):
# print("小了")
# else:
# print("猜对了")
# flag = False
# # 找出100以内可以被3整除的数字
# for i in range(1,100):
# if (i % 3 != 0):
# continue
# print(i)
# 定义一个求两个数商和余数的方法
# a = 20
# b = 10
# print(a % b)
# print(a // b)
# def level(a,b):
# print(a % b)
# print(a // b)
# level(20,10)
# level(5,3)
# def div(a,b):
# print(a % b)
# print(a // b)
# div(20,10)
# div(5,3)
# # 定义一个求两个数商和余数的方法
# def shang_yu(a,b): # a,b形参
# print("商:",a // b,",余数:",a % b)
#
# shang_yu(10,5) #方法调用 10,5实参
# shang_yu(20,3)
# def shang_yu(a,b):
# if(b==0):
# return None
# else:
# return (a//b,a%b)
# shang_yu(20,3)
res = shang_yu (20,0)
if res is None:
print("参数错误")
else:
print("商为:",res[0],",余数为:",res[1])
|
9ea2497ab2bd1a1bb9a47c1c2af6ca463f376e6d | taufanpr/ora-py-py | /B.1.1. Python Fundamental for Data Science/09. for (1).py | 548 | 3.78125 | 4 | for i in range (1,6): #perulangan for sebagai inisialisasi dari angka 1 hingga angka yg lbh kecil drpd 6
print("Ini adalah perulangan ke -", i) #perintah jika looping akan tetap berjalan
#Maksud dari fungsi for i in range (1,6):
#jika kita konversi pada JAVA atau C sama dengan for(i=1;i<6i++).
#Jika dikonversi jadi kalimat adalah “perulangan dimulai dari nilai i = 1 hingga nilai i kurang dari 6 dimana setiap kali perulangan nilai i akan selalu ditambah 1”.
#Jika nilai i sudah mencapai 6 perulangan akan dihentikan. |
0e992ab97b1d93a0ccac9cabe751c81442df96f3 | jiangxinyang227/leetcode | /热题HOT100/中等/105,从前序与中序遍历构造二叉树.py | 1,274 | 3.890625 | 4 | """
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
"""
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder) == len(inorder) == 0:
return None
mid_val = preorder[0]
root = TreeNode(mid_val)
index = inorder.index(mid_val)
root.left = self.buildTree(preorder[1: index + 1], inorder[:index])
root.right = self.buildTree(preorder[index + 1:], inorder[index + 1:])
return root
def dfs(self, root):
if root is None:
return
stack = []
cur = root
while stack or cur:
if cur:
print(cur.val)
stack.append(cur.right)
cur = cur.left
else:
cur = stack.pop()
s = Solution()
res = s.buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
s.dfs(res)
|
6f530b7b9ed1eb94b29dcc46fe7f951c62d29a1b | imtiaz-mamun/bongo | /Question_2/Solution_Q2.py | 3,328 | 3.671875 | 4 | class Person(object):
def __init__(self, first_name, last_name, father):
self.first_name = first_name
self.last_name = last_name
self.father = father
person_a = Person("User", "1", "")
person_b = Person("User", "2", person_a)
def print_depth(data):
print("Current Parameter and Level:")
lines=data
level = 0
for i in range(len(lines)):
line = lines[i].split()
for j in range(len(line)):
if(line[j]=="{"):
level = level + 1
x = line[j].split(':')
if(len(x)>1):
key = x[0].replace('“','')
key = x[0].replace('”','')
print(key," ", level)
with open('input.txt') as f:
lines = f.readlines()
my_data = lines
print_depth(lines)
def add_my_object(data, add_obj,add_level,keys,val):
linesa=data
level = 0
for i in range(len(linesa)):
linea = linesa[i].split()
for j in range(len(linea)):
if(linea[j]=="{"):
level = level + 1
if(level==add_level):
for k in range(len(keys)):
if(k==0):
linesa[i] = linesa[i].append('\n“')
linesa[i] = linesa[i].append(add_obj)
linesa[i] = linesa[i].append('”')
linesa[i] = linesa[i].append(':')
linesa[i] = linesa[i].append('{\n')
linesa[i] = linesa[i].append('“')
linesa[i] = linesa[i].append(keys[k])
linesa[i] = linesa[i].append('”')
linesa[i] = linesa[i].append(':')
linesa[i] = linesa[i].append(val[k])
linesa[i] = linesa[i].append(',')
print(linesa)
if(k==len(keys)-1):
linesa[i] = linesa[i].append('\n}')
else:
linesa[i] = linesa[i].append('“')
linesa[i] = linesa[i].append(keys[k])
linesa[i] = linesa[i].append('”')
linesa[i] = linesa[i].append(':')
linesa[i] = linesa[i].append(val[k])
if(k+1!=len(keys)-1):
linesa[i] = linesa[i].append(',')
print_depth(linesa)
add_obj = input("\nObject Addition to the dictionary:\nInsert Object Name?")
if(add_obj):
add_param_key = "y"
count=0
keys = []
val = []
while(add_param_key=="y" or add_param_key=="Y"):
add_param_key = input("Add new parameter?(Y/N)")
if(add_param_key=="y" or add_param_key=="Y"):
print("yes")
keys.append(input("Parameter name?"))
val.append(input("Parameter value?"))
count = count + 1;
if(add_param_key=="n" or add_param_key=="N"):
add_level = input("Insert Object level?")
add_my_object(my_data,add_obj, add_level,keys,val)
break
else:
add_param_key = input("Add new parameter?(Y/N)")
|
73e1dfc65a897ee05fcf0bc4389cc1b66202567c | mingddo/sunday_algorithm | /4일차_Stack1/서녕/SWEA_4873_반복문자지우기_정선영.py | 395 | 3.65625 | 4 | def erase(sentence):
i = 0
tmp = []
while True:
if i == len(sentence) -1:
break
if sentence[i] == sentence[i+1]:
del sentence[i:i+2]
i = 0
else:
i += 1
return len(sentence)
T = int(input())
for test_case in range(1, T+1):
sentence = list(input())
print('#{} {}'.format(test_case, erase(sentence)))
|
f724be7993345bb7dec2700288a4b9cf8879ecdd | simeongs/codeclub | /introductory_course/lessons/lesson_5-standard_library/standard_functions.py | 1,311 | 4.03125 | 4 | #abs() returns the absolute value of a number
print(abs(-1))
print(abs(-100))
print(abs(0))
print(abs(45))
#all() returns True if all items in an iterable object are True
print(all([True, True, True]))
print(all([True, False, True]))
print(all([False, False, False]))
#any() returns True if at least one item in the iterable object is True
print(any([True, True, True]))
print(any([True, False, True]))
print(any([False, False, False]))
#bin() returns the binary form of a number
print(bin(2))
print(bin(0))
print(bin(5))
#len() returns the length of an object
print(len("#codeclub"))
print(len(["bakerloo", "central", "circle", "district", "hammersmith", "jubilee", "metropolitan", "nothern", "picadilly", "victoria", "waterloo and city"]))
print(len({1, 2, 3}))
print(len(""))
print(len([]))
print(len({}))
#isinstance() returns True if a speficied object is an instance of a of specified object
print(isinstance("codeclub", str))
print(isinstance("codeclub", int))
#sum() sums items in iterator
print(sum([1,2,3]))
print(sum([-1,2,-3,4]))
print(sum([10,20,30,40,50]))
#min() returns smallest value in iterable
print(min([1,2,3]))
print(min([-1,2,-3,4]))
print(min([10,20,30,40,50]))
#max() returns greatest value in iterable
print(max([1,2,3]))
print(max([-1,2,-3,4]))
print(max([10,20,30,40,50]))
|
ff25329fb34d0312d49da28bc83e4a5b31b16bfc | mgperson/cauchy | /SIGN/src/tests/TestSIGN.py | 518 | 3.71875 | 4 | import unittest
from ..SIGN import SIGN
class testSIGN(unittest.TestCase):
def setUp(self):
self.sign = SIGN(2)
def test_get_positive_and_negative_permutations(self):
expected_len = 8
expected_permutations = [[-1, -2],[-1, 2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1]]
self.assertEqual(len(self.sign.positive_and_negative_permutations),expected_len)
self.assertEqual([permutation for permutation in self.sign.positive_and_negative_permutations], expected_permutations) |
be9c0a615342c6ff0dedf47fa6fe39958bd4cbb4 | wpy-111/python | /DataAnalysis/day01/demo05_shape.py | 319 | 3.890625 | 4 | """
维度操作
"""
import numpy as np
ary = np.arange(1,9)
print(ary,ary.shape)
b = ary.reshape(2,4)
print(b,b.shape)
ary[0] = 999
print(b)
#ravel()变为一维数图
c = b.ravel()
print(c)
#复制变维
d = c.flatten()
c[0] = 12
print(d,d.shape)
print(c)
#就地变维
c.shape = (2,4)
c.resize(2,2,2)
print(c)
|
cf6b6c959824a052e365d413640fbf4f8baaeb8b | hoque-nazmul/codingbat-problem-solving | /list-1/problem-8.py | 194 | 3.828125 | 4 | def max_end3(nums):
larger_num = 0
first_num = nums[0]
last_num = nums[-1]
if first_num > last_num:
larger_num = first_num
else:
larger_num = last_num
return [larger_num] * 3 |
43af5390f668d96503f9c9bd8583e4dbc2f89464 | noozip2241993/learning-python | /csulb-is-640/deitel-text/exercises/ch05/ex501.py | 2,920 | 4.03125 | 4 | '''
(What’s Wrong with This Code?)
print('c) name = 'amanda'
name[0] = 'A'
d) numbers = [1, 2, 3, 4, 5]
numbers[3.4]
e) student_tuple = ('Amanda', 'Blue', [98, 75, 87])
student_tuple[0] = 'Ariana'
f) ('Monday', 87, 65) + 'Tuesday'
g) 'A' += ('B', 'C')
h) x = 7
del x
print(x)
i) numbers = [1, 2, 3, 4, 5]
numbers.index(10)
j) numbers = [1, 2, 3, 4, 5]
numbers.extend(6, 7, 8)
k) numbers = [1, 2, 3, 4, 5]
numbers.remove(10)
l) values = []
values.pop()
'''
print('What, if anything, is wrong with each of the following code segments?')
print('\na) day, high_temperature = (\'Monday\', 87, 65)')
try:
day, high_temperature = ('Monday', 87, 65)
print(day)
print(high_temperature)
except:
print('the tuple has three elements but only two are assigned.')
print('\nb) numbers = [1, 2, 3, 4, 5]\nnumbers[10]')
try:
numbers = [1, 2, 3, 4, 5]
numbers[10]
except:
print('the list numbers has a len of 5 with a max index of 4, numbers[10] \
attempts to call for an item in numbers at an index that does not exist.')
try:
print('\nc) name = \'amanda\' \nname[0] = \'A\'')
name = 'amanda'
name[0] = 'A'
except:
print('strings are not mutable. Their characters cannot be changed.')
try:
print('d) numbers = [1, 2, 3, 4, 5] \nnumbers[3.4]')
numbers = [1, 2, 3, 4, 5]
numbers[3.4]
except:
print('float values are not valid list indexes.')
try:
print('e) student_tuple = (\'Amanda\', \'Blue\', [98, 75, 87]) \nstudent_tuple[0] = \'Ariana\'')
student_tuple = ('Amanda', 'Blue', [98, 75, 87])
student_tuple[0] = 'Ariana'
except:
print('Tuple\'s are not mutable. Their elements can not be changed.')
try:
print('f) (\'Monday\', 87, 65) + \'Tuesday\'')
print(('Monday', 87, 65))
print(('Monday', 87, 65) + 'Tuesday')
except:
print('Tuple\'s are not mutable.')
try:
print("'A' += ('B', 'C')")
#'A' += ('B', 'C')
except:
print("syntax error. 'A' is not assignable" )
try:
print("h) x = 7\ndel x\nprint(x)")
x = 7
del x
print(x)
except:
print("'print(x)' calls a variable after it has been deleted.")
try:
print("i) numbers = [1, 2, 3, 4, 5]\nnumbers.index(10)")
numbers = [1, 2, 3, 4, 5]
numbers.index(10)
except:
print("the list 'numbers' does not have 10 as an element therefore .index(10) does not exist either.")
try:
print("j) numbers = [1, 2, 3, 4, 5]\nnumbers.extend(6, 7, 8)")
numbers = [1, 2, 3, 4, 5]
numbers.extend(6, 7, 8)
except:
print(".extend takes in a sequence item as an argument. 'numbers.extend(6, 7, 8)' should be numbers.extend([6, 7, 8])")
try:
print("k) numbers = [1, 2, 3, 4, 5]\nnumbers.remove(10)")
numbers = [1, 2, 3, 4, 5]
numbers.remove(10)
except:
print("The value '10' is not on the list")
try:
print("l) values = []\nvalues.pop()")
values = []
values.pop()
except:
print("Can't .pop from an empty list.") |
29f894ae29d361069dcb3999d6c02fec42ffe81a | vinhpham95/python-testing | /BasicEditor.py | 1,287 | 4.21875 | 4 | # Vinh Pham
# 10/11/16
# Lab 7 - Basic Editor
# Reads each line from word.txt and copy to temp.txt unless asked to change the line.
# Open appopriate files to use.
words_file = open("words.txt","r")
temp_file = open("temp.txt","w")
line_counter = 0 # To count each line; organization purposes.
# Read each line seperately and change if program receives an input.
for line_str in words_file:
line_counter +=1
replacement = input("What do you want to replace for line {}: {}".format(line_counter,line_str))
if replacement == "":
print (line_str,end="",file=temp_file)
else: print (replacement,file=temp_file)
replacement = "" # Resets to no input.
# Necessity
words_file.close()
temp_file.close()
# This is a test code to read the temp_file.
##temp_file = open("temp.txt","r")
##for line_str in temp_file:
## print(line_str)
##
##temp_file.close()
# Copy everything back into words_file, overwriting it.
words_file = open("words.txt","w")
temp_file = open("temp.txt","r")
for line_str in temp_file:
print(line_str,end="",file=words_file)
words_file.close()
temp_file.close()
# This is a test code to read the finished words_file.
##words_file = open("words.txt","r")
##for line_str in words_file:
## print(line_str)
##
##words_file.close()
|
0a350fd6687592569469c497c568ba2d52ee614e | sainadhreddy92/dsImplementations | /trie.py | 2,087 | 3.734375 | 4 | class trienode(object):
def __init__(self):
self.map = {}
self.isCompleteword = False
class solution(object):
def addName(self,rootNode,word):
for i in range(len(word)):
if word[i] in rootNode.map:
if i==len(word)-1:
rootNode.isCompleteword = True
rootNode = rootNode.map[word[i]]
else:
newnode = trienode()
rootNode.map[word[i]]= newnode
if i==len(word)-1:
rootNode.isCompleteword = True
rootnode = newnode
def findword(self,rootNode,prefix):
for i in range(len(prefix)):
if prefix[i] in rootNode.map:
if i == len(prefix)-1 and rootNode.isCompleteword==True:
return True
rootNode = rootNode.map[prefix[i]]
else:
return False
return False
def getallwords(self,rootNode,prefix):
res = []
rootnode2 = rootNode
rootNode = self.isprefix(rootNode,prefix)
if not rootNode:
return []
else:
res.extend(self.helper(rootNode,prefix,[]))
if self.findword(rootnode2,prefix):
res=[prefix]+res
return res
def helper(self,rootNode,prefix,res):
if len(rootNode.map)==0:
return res
for letter in rootNode.map:
if rootNode.isCompleteword==True:
res=self.helper(rootNode.map[letter],prefix+letter,res+[prefix+letter])
else:
res=self.helper(rootNode.map[letter],prefix+letter,res)
return res
def isprefix(self,rootNode,prefix):
for char in prefix:
if char not in rootNode.map:
return None
rootNode = rootNode.map[char]
return rootNode
def main():
li = ["hack","hackerrank","abc","abcf","abce","abcd","abcde","abcdef","abcdefg"]
rootNode = trienode()
sol = solution()
for element in li:
sol.addName(rootNode,element)
#print sol.findword(rootNode,"hack")
#print sol.findword(rootNode,"hackerrank")
#print sol.findword(rootNode,"abc")
#print sol.findword(rootNode,"abcd")
#print sol.findword(rootNode,"bdjcbejbjfb")
print sol.getallwords(rootNode,"")
if __name__=='__main__':
main()
|
af929c9aedc86b034c20dc1f4f7efd081d522324 | HYUNMIN-HWANG/LinearAlgebra_Study | /LinearAlgebra_Function/3.04.LeastSquares_matplotlib.py | 1,372 | 3.6875 | 4 | # Least Squares
# 해방정식을 근사적으로 구하는 방법 : 구하려는 해와 실제 해의 오차의 제곱의 합이 최소가 되는 해를 구하는 방법
# 샘플 데이터
import numpy as np
import matplotlib.pyplot as plt
def make_linear(w=0.5, b=0.8, size=50, noise=1.0):
# w : 기울기, b : y 절편
x = np.arange(size)
y = w * x + b
noise = np.random.uniform(-abs(noise), abs(noise), size=y.shape) # 노이즈 생성
yy = y + noise # 노이즈 추가
# 시각화
plt.figure(figsize=(10, 7))
plt.plot(x, y, color='r', label=f'y = {w}*x + {b}')
plt.scatter(x, yy, label='data')
plt.legend(fontsize=20)
plt.show()
print(f'w: {w}, b: {b}')
return x, yy
def least_square(x, y) :
# Least Square 공식으로 w와 b 구하기
x_bar = x.mean()
y_bar = y.mean()
# w 계수
calculated_weight = ((x - x_bar) * (y - y_bar)).sum() / ((x - x_bar)**2).sum()
print('w: {:.2f}'.format(calculated_weight))
# b
calculated_bias = y_bar - calculated_weight * x_bar
print('b: {:.2f}'.format(calculated_bias))
x, y = make_linear(size=50, w=1.5, b=0.8, noise=5.5)
least_square(x, y)
# w: 1.5, b: 0.8
# w: 1.49
# b: 0.82
# 노이즈 더 추가
print("========Add noise=========")
y[5]=60
y[10]=60
y[15]=60
least_square(x, y)
# w: 1.30
# b: 7.92
# outlier에 취약하다.
|
cb1592b8103398fa4e4c9ea0611fb2840ea05651 | puneetgupta4java/python-codes | /Dictionary.py | 263 | 3.828125 | 4 | dict1 = dict()
print dict1
dict2 ={'a':1,'b':2}
print(dict2)
dict2['a'] = 1000
print dict2
for i in dict2:
dict1[dict2[i]]= i
print dict1
print dict1.clear()
print dict1
print dict2.items()
print dict2.keys()
print("hello "*5)
|
e023c2df1882592401c96db5b8908efd6569e07c | jtenhave/AdventOfCode | /2019/Day6/c.py | 956 | 3.5 | 4 | import re
orbitPattern = re.compile("(\w*)\)(\w*)")
# Class that represents an orbiting object.
class Object:
def __init__(self, id):
self.id = id
self.parent = None
# Total number of orbits this object has around the central mass.
def totalOrbits(self):
if not self.parent:
return 0
else:
return 1 + self.parent.totalOrbits()
# Get the objects.
def getObjects(file):
with open(file) as input:
orbitDefs = input.readlines()
objects = {}
for orbitDef in orbitDefs:
match = orbitPattern.match(orbitDef)
parentID = match[1]
childID = match[2]
if parentID not in objects:
objects[parentID] = Object(parentID)
if childID not in objects:
objects[childID] = Object(childID)
parent = objects[parentID]
child = objects[childID]
child.parent = parent
return objects
|
6096543c5575803e54df28fadf6ed9300fd86fe3 | lsclike/Python_Practice | /GoodBook/heap_sorting.py | 724 | 3.6875 | 4 | def sort(unordered):
leng = len(unordered)
k = leng // 2
while k >= 1:
sink(unordered, k, leng)
k -= 1
while leng > 1:
exch(unordered, 1, leng)
leng -= 1
sink(unordered, 1, leng)
def sink(arr, s, e):
while 2 * s <= e:
j = 2 * s
if (j < e) and less(arr, j, j + 1):
j += 1
if not less(arr, s, j):
break
exch(arr, s, j)
s = j
def exch(arr, s, e):
arr[s-1], arr[e-1] = arr[e-1], arr[s-1]
def less(arr, s, e):
return arr[s-1] < arr[e-1]
if __name__ == '__main__':
test = [9, 8, 7, 6, 5, 4, 102, 12, 12312, 2341234213491024]
sort(test)
for t in test:
print(t, end=' ')
|
04805cc067fc741c6ab181a4c1056235b4fddc4f | rafaelgama/Curso_Python | /Udemy/Secao4/aula103/classes.py | 1,255 | 3.875 | 4 | # Herança sempre vem de cima para baixo na hierarquia.
# Sobreposição de membros
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
self.nomeClasse = self.__class__.__name__
def falar(self):
print(f'{self.nomeClasse} falando...')
# Herda os atributos da classe Pessoa
class Cliente(Pessoa):
def comprar(self):
print(f'{self.nomeClasse} comprando...')
# Se existir um método def falar() aqui, o super executa ele primeiro.
# Herda os atributos da classe Pessoa e da classe Cliente
'''class ClienteVip(Cliente):
def falar(self):
# super() ele executa os metodos da classe herdada até encontrar o método.
super().falar()
# Pode chamar direto, colocando por exemplo: Pessoa.falar(self), mas não poderia ficar sem o self,
# para saber de qual instancia que ele veio.
print(f'{self.nomeClasse} falando de novo...')'''
# Exemplo de Atributo exclusivo da classe
class ClienteVip(Cliente):
def __init__(self, nome, idade, sobrenome):
Pessoa.__init__(self, nome, idade)
self.sobrenome = sobrenome
def falar(self):
Pessoa.falar(self)
print(f'{self.nome} {self.sobrenome}')
|
c350a998faf5281901712f8fccf7d21c9d70cd98 | charliechocho/py-crash-course | /x7_multiples_of_10.py | 226 | 3.875 | 4 | check_for10 = input("Fyll i ett nummer så ska vi se om det är jämnt delbart med 10: ")
if not int(check_for10) % 10:
print("Ditt nummer är en multipel av 10")
else:
print("Ditt nummer är inte en multipel av 10")
|
7e5e21ba73680ead465ca34d4963d2b3e5332759 | St3451/Linux_Python_Programming | /assignment5/handin5_test.py | 1,057 | 3.53125 | 4 | # 2. Create a new file, called handin5_test.py where you import the handin5 module. Then call the read_fasta function and save the result in a variable called fasta_dict
import handin5
fasta_dict = handin5.read_fasta("Ecoli.prot.fasta")
print(fasta_dict.keys())
# 4. In the handin5_test.py file, call the find_prot function on the protein name YHCN_ECOLI. Save the result to a variable called yhcn.
yhcn = (handin5.find_prot(fasta_dict,"YHCN_ECOLI"))
# 5. In the handin5_test.py file, call the find_prot function on the protein name BOOM_ECOLI. Save the result to a variable called boom. Note that this case should print an error, since this is not an actual Ecoli protein name.
boom = handin5.find_prot(fasta_dict,"BOOM_ECOLI")
# 7. In handin5_test.py, use the find_prot2 function to return all the protein names in Ecoli that only consist of three characters before _ECOLI (e.g. EX1_ECOLI). Save the result in a variable called matches". Print the number of matches to screen.
matches = handin5.find_prot2(fasta_dict,"^..._ECOLI")
print(len(matches))
|
7a6075a2951805bbcb3800b4d2c0b3820cc8f6b4 | AdityaRavipati/algo-ds | /set_matrix_zeros.py | 507 | 3.671875 | 4 | def set_matrix_zeros(A):
C = len(A[0])
R = len(A)
row = [1] * R
col = [1] * C
for i in range(0, R):
for j in range(0, C):
if (A[i][j] == 0):
row[i] = 0
col[j] = 0
for i in range(0, R):
for j in range(0, C):
if row[i] == 0 or col[j] == 0:
A[i][j] = 0
for l in A:
a = " ".join(str(i) for i in l)
print a
A = [[1, 0, 1],
[1, 1, 1],
[1, 0, 1]]
set_matrix_zeros(A) |
3e09251aba825259ca4e73beb7911d2da1978d59 | gudduarnav/Acceleratron-Python-Workshop-Assignments | /assignment02/program_19.py | 444 | 3.921875 | 4 | # 19. Write a program to find greatest common divisor (GCD) or highest common factor (HCF) of given two numbers
a, b = map(int, input("Enter 2 numbers:").split())
print("Numbers are",a,b)
# find gcd
gcd = a
div = b
while True:
remainder = div % gcd
if remainder == 0:
# gcd found
break
else:
# swap
div = gcd
gcd = remainder
print("GCD is", gcd)
# find lcm
print("LCM is", (a*b)//gcd) |
5cc75b21a38a021e8e18c238417e7b8b9f8430cc | CiscoDevNet/devnet-express-cloud-collab-code-samples | /itp/collab-python-parsing-json-itp/json_parse_1_sol.py | 1,163 | 4.3125 | 4 | var={"car":"volvo", "fruit":"apple"}
print(var["fruit"])
for f in var:
print("key: " + f + " value: " + var[f])
print()
print()
var1={"donut":["chocolate","glazed","sprinkled"]}
print(var1["donut"][0])
print("My favorite donut flavors are:", end= " ")
for f in var1["donut"]:
print(f, end=" ")
print()
print()
#Using the examples above write code to print one value of each JSON structure and a loop to print all values below.
var={"vegetable":"carrot", "fruit":"apple","animal":"cat","day":"Friday"}
print(var["vegetable"])
for f in var:
print("key: " + f + " value: " + var[f])
print()
print()
var1={"animal":["dog","cat","fish","tiger","camel"]}
print(var1["animal"][0])
print("My favorite animals are:", end= " ")
for f in var1["animal"]:
print(f, end=" ")
print()
print()
myvar={"dessert":"ice cream", "exercise":"push ups","eyes":"blue","gender":"male"}
print(myvar["exercise"])
for f in myvar:
print("key: " + f + " value: " + myvar[f])
print()
print()
myvar1={"dessert":["cake","candy","ice cream","pudding","cookies"]}
print(myvar1["dessert"][0])
print("My favorite desserts are:", end= " ")
for f in myvar1["dessert"]:
print(f, end=" ")
|
5ac246af231584ff2a2d8aaa8a3e5d3f0baab047 | alinaromanenko/project5 | /main.py | 1,034 | 4.1875 | 4 | letter_list = ['а', 'о', 'и', 'е', 'ё', 'э', 'ы', 'у', 'ю', 'я', 'А', 'О', 'И', 'Е', 'Ё', 'Э', 'Ы', 'У', 'Ю', 'Я']
answer = input('Нужно ли перевести фразу? ')
while answer.lower() == 'да':
letter = input('Введите первую букву цвета языка: ')
text = input("Введите текст: ")
for i in letter_list:
char = i+letter+i.lower()
text = text.replace(i, char)
print(text)
answer = input('Нужно ли перевести фразу? ')
answer_ = input('Хотите ли вы воспользоваться переводчиком? ')
while answer_.lower() == 'да':
letter = input('Введите первую букву цвета языка: ')
text = input("Введите текст: ")
for i in letter_list:
char = i+letter+i.lower()
text = text.replace(char, i)
print(text)
answer_ = input('Хотите ли вы воспользоваться переводчиком? ') |
afd69dac333a56966028cd3eb21cd1e69ac0f8ef | waltman/advent-of-code-2020 | /day06/custom_customs.py | 653 | 3.578125 | 4 | #!/usr/bin/env python3
from sys import argv
from collections import defaultdict
questions = defaultdict(int)
num_groups = 0
num_all = 0
group_size = 0
filename = argv[1]
with open(filename) as f:
for line in f:
line = line.rstrip()
if line:
group_size += 1
for q in line:
questions[q] += 1
else:
num_groups += len(questions)
# how many questions did everyone answer?
num_all += len([v for v in questions.values() if v == group_size])
questions.clear()
group_size = 0
print('Part 1:', num_groups)
print('Part 2:', num_all)
|
b13e6d11f4f0d10a3c65ee37b8330a8e6618b106 | theYBFL/20.21.10.1 | /10a-if3.py | 299 | 3.71875 | 4 | #0-50 1
#50-60 2
#60-70 3
#70-85 4
#85-100 5
n1=int(input("1.not "))
n2=int(input("2.not "))
ort=(n1+n2)/2 #90 - 0-100
print(ort)
if ort>0 and ort<50:
print("1")
elif ort>=50 and ort<60:
print("2")
elif ort>=60 and ort<70:
print("3")
elif ort>=70 and ort<85:
print("4")
else:
print("5") |
22a816e983aa603c92587d206b5720801198ff81 | ColinWilder/pythonBasics | /Ch04-exs.py | 1,669 | 4.15625 | 4 | ## Exercise 1
if 0==True:
print("0 is true.")
else:
print("0 is false.")
if 1==True:
print("1 is true.")
else:
print("1 is false.")
if 2==True:
print("2 is true.")
else:
print("2 is false.")
print("\n")
## Exercise 2
v=9
if v>=0 and v<=9:
print("V passes the 0-9 test.")
else:
print("V fails test.")
print("\n")
## Exercise 3
l=["a","d","c"]
if l[0]=="b":
print("quarry is in list l")
elif l[1]=="b":
print("quarry is in list l")
else:
print("quarry is NOT in list l")
## Exercise 4
print("\n")
fridge={}
fridge["milk"]="creamy"
fridge["eggs"]="protein-filled"
fridge["cheese"]="bluecheezy"
food_sought=input("What food do you seek? ")
for food in fridge:
if food == food_sought:
print(food, fridge.get(food))
break
else:
print("sought-after food is not in fridge")
## Exercise 5
print("\n")
fridge={}
fridge["milk"]="creamy"
fridge["eggs"]="protein-filled"
fridge["cheese"]="bluecheezy"
food_sought=input("What food do you seek? ")
fridge_list=list(fridge.keys())
while len(fridge_list)>0:
current_key=fridge_list[0]
if current_key==food_sought:
print("sought-after food is in fridge and is %s" % fridge[food_sought])
break
fridge_list.pop(0)
if len(fridge_list)==0:
print("sought-after food is NOT in fridge")
## Exercise 6
print("\n")
fridge={}
fridge["milk"]="creamy"
fridge["eggs"]="protein-filled"
fridge["cheese"]="bluecheezy"
food_sought=input("What food do you seek? ")
try:
if fridge[food_sought]=="bluecheezy":
print("you must like blue cheese!")
except (KeyError) as error:
print("none of that here, I'm afraid")
|
b8dd24628a15e76de6690100fd750be909f9044c | nihalgaurav/Artificial-Intelligence | /ai_package01/AI_Practical24.py | 194 | 4.1875 | 4 | import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
plt.plot([1, 2, 3, 4], list(a**2 for a in x))
plt.xlabel("-------some numbers-------->")
plt.ylabel("-------squared value------->")
plt.show()
|
c6088a32c9f861497abf91eead314a991fab7b4c | Sreenitti/Python-Projects | /Credit_Card_Validator.py | 1,458 | 3.625 | 4 | from tkinter import *
def validate(card_no) :
odd_sum = 0
even_sum = 0
double_list = []
number = list(card_no)
for index, val in enumerate(number) :
if index%2 !=0 : # odd index number
odd_sum += int(val)
else : # even index number
double_list.append(int(val)*2)
# converting double_list into string
double_string = ""
for i in double_list :
double_string += str(i)
# converting double_string back into list
double_list = list(double_string)
for x in double_list :
even_sum += int(x)
net_sum = odd_sum + even_sum
listbox = Listbox(canvas, width=40, height=1)
canvas.create_window(200, 200, window=listbox)
if net_sum%10 == 0 :
listbox.insert(END, "This is a valid credit card number.")
else :
listbox.insert(END, "This is not a valid credit card number.")
root = Tk()
root.title("Credit Card Validator")
canvas = Canvas(root, width=400, height=250)
canvas.pack()
title = Label(root, text="Credit Card Validator", font=("Comic Sans MS", 20), fg="Brown")
canvas.create_window(200, 20, window=title )
label = Label(root, text="Enter credit card number ")
canvas.create_window(100, 100, window=label )
entry = Entry(root)
canvas.create_window(250,100, window=entry)
button = Button(root, text="Validate", command=lambda :validate(entry.get()))
canvas.create_window(200, 150, window=button)
root.mainloop()
|
994a1c28df3a078037728433c97817fcd09e3597 | Friction-Log/learning_python_frictionlog | /lessons/syntax.py | 2,197 | 4.34375 | 4 |
# Print hello world
print("Hello World")
# create a string variable
my_string = "Hello World"
# concatenate two strings
print(my_string + "!!!")
# interpolate a string
print("Hello %s" % "World")
# interpolate a string with a number
print("Hello %s %d" % ("World", 42))
# interpolate a string and assign to a variable
greeting = "Hello %s" % "World"
# find the length of a string
print(len(greeting))
# find a letter in a string
print("H" in greeting)
# return the index of a letter in a string
print(greeting.index("H"))
# reverse a string
print(greeting[::-1])
# handle exceptions
try:
print(greeting[100])
except IndexError:
print("Index out of bounds")
# Create a variable with a list
my_list = [1, 2, 3]
# destructure a list
a, b, c = my_list
print(a, b, c)
# Add two numbers
x = 2
y = 3
print(x + y)
# Divide two numbers
x = 10
y = 3
print(x / y)
# Two numbers divided by each other
x = 10
y = 3
print(x // y)
# Two numbers divisible by each other
x = 10
y = 3
print(x % y)
# Round a number
x = 10.5
print(round(x))
# Average of a list
my_list = [1, 2, 3, 4, 5]
print(sum(my_list) / len(my_list))
# Change variable from a string to an integer
my_string = "123"
my_int = int(my_string)
print(my_int)
# Change variable from integer to a string
my_int = 123
my_string = str(my_int)
print(my_string)
# Int64
x = 1234567890123456789
print(x)
#Float64
x = 1.2345678901234567890
print(x)
# Int64 to Float64
x = 1234567890123456789
print(float(x))
# Multi line string
my_string = """
This is a multi-line string.
This is the second line.
"""
print(my_string)
# Write a boolean check
my_string = "Hello World"
# if statement
if my_string == "Hello World":
print("String is equal to 'Hello World'")
# if else statement
if my_string == "Hello World":
print("String is equal to 'Hello World'")
else:
print("String is not equal to 'Hello World'")
# if elif else statement
if my_string == "Hello World":
print("String is equal to 'Hello World'")
elif my_string == "Hello World!!":
print("String is equal to 'Hello World!!'")
else:
print("String is not equal to 'Hello World'")
# check if type is a number
if type(my_string) is int:
print("String is an integer")
|
2e73743f752f326f598879041f516dec1cac7c30 | sutariadeep/datastrcutures_python | /Arraysandstrings/itoa.py | 460 | 4.15625 | 4 | #http://www.geeksforgeeks.org/implement-itoa/
def convert_to_string(num, base=10):
if num == 0:
return '0'
if num < 0 and base == 10:
num = -num
elif num // base == 0:
return chr(num + ord('0'))
return convert_to_string(num // base, base) + chr(num % base + ord('0'))
print convert_to_string(1567,10)
print convert_to_string(-1567,10)
print convert_to_string(1567,2)
print convert_to_string(1567,8)
#print convert_to_string(1567,16) #Hexadecimal |
b5ae9c4b8fe0e9a8e173dfe3b1d1b3f002a79311 | zosopick/mathwithpython1 | /Excersises/Chapter 4/1. Factor Finder.py | 784 | 4.25 | 4 | '''
Make a program which asks the user to input an expression, calculates its factors and prints them
It ought to handle invalid input by making use of exception handling
'''
from sympy import symbols,factor,sympify
from sympy.core.sympify import SympifyError
def factorizer(expr):
x,y=symbols('x,y')
factorized=factor(expr)
return factorized
if __name__=='__main__':
expr1=input('Please enter an expression to be factorized: ')
try:
expression=sympify(expr1)
except SympifyError:
print('The input is invalid and cannot be factorized.')
else:
factorizer(expression)
print('The factor of {0} is'.format(expression))
print('{0}'.format(factorizer(expression)))
|
4275701e04a54af336043eb9b1a13404a0fd9e6d | rachelrly/dsa-python | /solutions/linked-list-drills.py | 1,702 | 3.671875 | 4 | from ll import LinkedList
from dll import DoublyLinkedList
# llist = LinkedList()
# llist.__insert_first__('one')
# llist.__insert_last__('two')
# llist.__insert_last__('three')
# llist.__insert_last__('four')
# llist.__insert_last__('five')
dllist = DoublyLinkedList()
dllist.insert_first('five')
dllist.insert_last('four')
dllist.insert_last('three')
dllist.insert_last('two')
dllist.insert_last('one')
dllist.show()
#singly linked list
def three_from_the_end(llist):
node = llist.head
while node.next.next.next != None:
node = node.next
return node
# alternate solution
def three_from_end_alt(llist):
reverse_ll = llist.reverse()
node = reverse_ll.head
for node in range(0, 3):
node = node.next
return node
#singly linked list
def find_list_center(ll):
node = ll.head
fast_pointer = ll.head
while (fast_pointer.next != None):
node = node.next
fast_pointer = node.next.next
return node
def reverse_dll(dll, node=None, prev=None):
node = dll.head if node == None else node
if next == None:
node.next = prev
prev.prev = node
dll.head = prev
return
hold = node.next
node.next = prev
node.prev = node.next
node = hold
prev = node.prev
dll.show()
reverse_dll(dll, node, prev)
reverse_dll(dllist)
#hold the previous node and
# def __recurse_reverse__(self, node, prev=None):
# hold = node.next
# node.next = prev
# hold.next = node
# if node.next == None:
# self.__show_ll__()
# return
# self.__recurse_reverse__(hold, node)
# def recurse_reverse(self):
# return self.__recurse_reverse__(self.head)
|
a1143b729bfff1d0255a65352d7b04d9677be55f | lordpews/python-practice | /oops12.py | 510 | 3.765625 | 4 | class A:
class_var1 = "i am a variable in class A"
def __init__(self):
self.var1 = "i am inside class A's contructor "
self.class_var1 = "i am an instance variable in class A"
self.sp = "spigot"
class B(A):
class_var1 = "i am a variable in class b"
def __init__(self):
super().__init__()
self.var1 = "i am inside class B's contructor "
self.class_var1 = "i am an instance variable in class B"
a = A()
b = B()
print(b.class_var1)
print(b.sp) |
adaa91ae15d293cf27771f0a49725f1343883e36 | daisykha/MultipleChoiceMarking | /load_file.py | 1,373 | 3.71875 | 4 | import tkinter as tk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
# create the root window
class LoadFileDialog:
def __init__(self):
self.root = tk.Tk()
self.root.title("Select an image")
self.root.resizable(False, False)
self.root.geometry("400x200")
self.root.withdraw()
self.selected_file = None
def get_selected_file(self):
return self.selected_file
def select_file(self):
filetypes = (("image files", "*.jpeg *.png *.jpg"), ("All files", "*.*"))
filename = fd.askopenfilename(
title="Open a file", initialdir="/", filetypes=filetypes
)
# showinfo(title="Selected File", message=filename)
print(filename)
if filename:
self.selected_file = filename
self.root.destroy()
showinfo("Success", f"Successfully loaded file\n{filename}")
def create_screen(self):
# open button
self.root.deiconify()
open_button = tk.Button(
self.root,
text="Load a scanned test image (.png, .jpg)",
height=100,
width=200,
command=self.select_file,
)
open_button.pack(expand=True)
# run the application
self.root.mainloop()
|
dc29a1e01a2eeac9ef9dc3620f2dece96fd59398 | jianhui-ben/leetcode_python | /265. Paint House II.py | 2,066 | 3.65625 | 4 | #265. Paint House II
#There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
#The cost of painting each house with a certain color is represented by an n x k cost matrix costs.
#For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on...
#Return the minimum cost to paint all houses.
#Example 1:
#Input: costs = [[1,5,3],[2,9,4]]
#Output: 5
#Explanation:
#Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
#Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.
##min heap
import heapq
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
"""
keep a stack of k
k[i] = the min cost up to the current house if current house is using color i
return k
for every house i, we also need to track
the min cost up to house i - 1, and the color in house i - 1
the second min cost up to house i - 1, and the color in house i-1
time: O(nklogk)
space: O(k)
"""
heap = [(c, i)for i, c in enumerate(costs[0])]
heapq.heapify(heap)
for house_i in range(1, len(costs)):
lowest, second_lowest = heapq.heappop(heap), heapq.heappop(heap)
temp_heap = []
for color_i, cost in enumerate(costs[house_i]):
if color_i != lowest[1]:
heapq.heappush(temp_heap, (lowest[0] + cost, color_i))
else:
heapq.heappush(temp_heap, (second_lowest[0] + cost, color_i))
heap = temp_heap
return heapq.heappop(heap)[0]
|
44aed6b67e2e9c9556f9c655b0420ec2999c8f07 | jennypeng/python-practice | /Web/horoscope.py | 1,700 | 3.6875 | 4 | import urllib2
import sys
from bs4 import BeautifulSoup
def getHoroscope(sign, horoscope_type):
"""
Retrieves horoscope from site according to SIGN and HOROSCOPE_TYPE.
"""
url = "http://www.elle.com/horoscopes/daily/" + sign + "-" + horoscope_type + "-horoscope"
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
soup.prettify()
horoscope = soup.find('div', {'class': "body bodySign"}).get_text()
print(horoscope.encode(sys.stdout.encoding, errors='replace'))
def getUserInput(seed = None):
"""
Requests user input for horoscope media queries.
For simplicity of testing, optional parameter of seed which can retrieve queries.
Run doctest using "python -m doctest -v example.py"
>>> wrong_entry = ["nothoroscope", "nottype"]
>>> getUserInput(seed = wrong_entry)
Invalid sign
Invalid horoscope type
>>> right_entry = ["cancer","daily"]
>>> getUserInput(seed = right_entry)
Success
"""
signs = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn",
"aquarius", "pisces"]
types = ["daily", "weekly", "monthly"]
if seed is None:
sign = raw_input("Enter your horoscope sign: ").lower()
horoscope_type = raw_input("Daily, weekly, or monthly?: ").lower()
else:
sign = seed[0]
horoscope_type = seed[1]
if sign not in signs:
print("Invalid sign")
if horoscope_type not in types:
print("Invalid horoscope type")
else:
if seed is None:
getHoroscope(sign, horoscope_type)
else:
print("Success")
if __name__ == '__main__':
getUserInput() |
bd61d20f5dedbe3996c9abba3dc68acc067cd61f | numberjun/numberfirst | /pillow/生成验证码.py | 1,840 | 3.53125 | 4 | #代码借鉴了廖雪峰的官方网站
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
def rndChar():
return chr(random.randint(65, 90))
# 随机数字:
def rndNum():
return str(random.randint(0,9))
#随机中文
def rndChinese():
pass
# 随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
def get_char(draw,height, font):
# 输出文字:
char_list = []
for t in range(4):
char_list.append(rndChar())
draw.text((height * t + 10, 10),char_list[t] , font=font, fill=rndColor2())
return char_list
def get_num(draw,height, font):
# 输出数字:
num_list=[]
for t in range(4):
num_list.append(rndNum())
draw.text((height * t + 10, 10),num_list[t] , font=font, fill=rndColor2())
return num_list
def begin_get_pic():
# 240 x 60:
height = 80
width = height * 4
#创建纯白的背景图
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype(r'C:\Windows\Fonts\Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
#list_anw =get_num(draw,height, font)
list_anw =get_char(draw,height, font)
list_anw = "".join(list_anw)
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save(r'C:\Users\Administrator\Desktop\test\%s.jpg' %str(list_anw), 'jpeg')
print(list_anw)
# image.show()
if __name__ == "__main__":
for i in range(10):
begin_get_pic()
|
321c4fe59eab1cded00ca25285c03d582f499a00 | VrushitG/Py_Cwh | /tut5.py | 646 | 3.828125 | 4 | import flask
#Pleas Dont remove this line
"""
Pleas Dont remove this line
this is multi -
line comment
"""
print("Hello World""This is vrushit G")
print("Hello World","This is vrushit G") #this is for adding space betweent two statment
print("Hello World", end=" Joker ") #end function for adding somthing in new line
print("Hello World 2")
print("C:\harry")
print("C:\narry") #\n is consider as new line
print("C:\\narry") #this is called escap sequence character
print("C:\"harry") #for adding double quote sign
print("C:\'harry\'") #for adding single quote sign
print("This is \n good boy \t1") #\n for new line \t for one TAB space
|
13d1c2eed60d53c799b78e0e1aba7ffc8645a251 | Vampirskiy/helloworld | /venv/Scripts/Урок4/why_funk_param.py | 207 | 3.609375 | 4 | def my_filter(numbers):
result = []
for number in numbers:
if number % 2 == 0:
result.append(number)
return result
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
print(my_filter(numbers)) |
060039d16dd15ad334c507dc359f275aa2462c4f | AdityaGudimella/python_practice | /python_practice/iterables.py | 664 | 4.46875 | 4 | import typing
# Implement every function in functools and more_itertools and itertools using python loops
# Write a function that finds the length of an iterable without storing it in memory.
def iter_len(iterable: typing.Iterable) -> int:
""" Return len of iterable without storing it in memory """
# Write a function that finds the length of an iterable without storing it in memory and without consuming it.
def iter_len(iterable: typing.Iterable) -> int:
"""
iterable = (x for x in range(5))
assert iter_len(iterable) == 5
assert len(list(iterable)) == 5
"""
# Related Qeustions:
# - [1295] Find Numbers with Even Number of Digits
|
c58e4cccf6a7debe210ee51e79b60c3eb0a774b9 | krsthg/python3 | /문제300/211~220.py | 756 | 3.515625 | 4 | #211
#안녕 Hi
#212
#7, 15
#213
#함수에 인수가 없기 때문이다
#214
#문자와 정주는 더할 수 없기 때문이다.
#215
def print_with_smile():
a = input()
print(a+ " :D")
#216
print_with_smile()
#217
def print_upper_price():
a = int(input())
print(a*1.3)
#218
def print_sum():
a = int(input())
b= int(input())
print(a+b)
#219
def print_arithmetic_operation():
a = int(input())
b= int(input())
print(a,"+", b,"=",a+b)
print(a,"-", b,"=", a-b)
print(a,"*",b, "=", a*b)
print(a, "/", b, "=", a/b)
#220
def print_max():
a= int(input())
b = int(input())
c = int(input())
if a>b and a>c:
print(a)
elif b>a and b>c:
print(b)
else:
print(c) |
bcbda1e7458cb35c5df43ace3c3d3dba563a4543 | piazentin/programming-challenges | /hacker-rank/implementation/caesar_cipher.py | 691 | 3.890625 | 4 | # https://www.hackerrank.com/challenges/caesar-cipher-1
alpha_max = ord('z') - ord('a') + 1
def round_char(c, rounds, limit):
c = ord(c) + rounds
if c > ord(limit):
return chr(c - alpha_max)
else:
return chr(c)
def cipher_char(c, rounds):
if 'a' <= c <= 'z':
return round_char(c, rounds, 'z')
elif 'A' <= c <= 'Z':
return round_char(c, rounds, 'Z')
else:
return c
def caesar_cipher(plain, rounds):
rounds %= alpha_max # adjusting rounds to simplify calculation
return ''.join([cipher_char(c, rounds) for c in plain])
n = int(input())
plain = input()
rounds = int(input())
print(caesar_cipher(plain, rounds))
|
7d673f7bc713efa81643359430071d234860ecf1 | kyuugi/saitan-python | /やってみよう_必修編/chapter09/9_15_lottery_analysis.py | 2,150 | 3.671875 | 4 | from random import choice
def get_winning_ticket(possibilities):
"""当選したくじの番号を返す"""
winning_ticket = []
# 同じ数字や文字を繰り返さないために while ループを使用する
while len(winning_ticket) < 4:
pulled_item = choice(possibilities)
# 存在しない数字や文字の場合だけ、当選した番号のリストに追加する
if pulled_item not in winning_ticket:
winning_ticket.append(pulled_item)
return winning_ticket
def check_ticket(played_ticket, winning_ticket):
"""
プレーヤーのくじが当選しているかをチェックする
"""
# 当選したくじの中にない番号があったらFalseを返す
for element in played_ticket:
if element not in winning_ticket:
return False
# くじが当選している!
return True
def make_random_ticket(possibilities):
"""ランダムにくじを作成して返す"""
ticket = []
# 同じ数字や文字を繰り返さないために while ループを使用する
while len(ticket) < 4:
pulled_item = choice(possibilities)
# 存在しない数字や文字の場合だけ、当選した番号のリストに追加する
if pulled_item not in ticket:
ticket.append(pulled_item)
return ticket
possibilities = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e')
winning_ticket = get_winning_ticket(possibilities)
plays = 0
won = False
# くじの最大試行回数を設定する
max_tries = 10_000
while not won:
new_ticket = make_random_ticket(possibilities)
won = check_ticket(new_ticket, winning_ticket)
plays += 1
if plays >= max_tries:
break
if won:
print("くじに当選しました!")
print(f"あなたのくじ: {new_ticket}")
print(f"当選番号: {winning_ticket}")
print(f"{plays}回目のくじで当選しました!")
else:
print(f"{plays}回くじをひきましたが、当選しませんでした...")
print(f"あなたのくじ: {new_ticket}")
print(f"当選番号: {winning_ticket}")
|
85fff930ebc26a8527c481d3d20fa5aa95d77b49 | debolina-ca/my-projects | /Python Codes 1/Formatting Date Time Objects in Print.py | 1,239 | 3.84375 | 4 | # Formatting time objects
from datetime import time
t = time(hour = 10, minute = 15)
# display as 10:15 AM
# string passed to strftim includes all necessary spaces and semicolons
formatted_string = t.strftime("%I:%M %p")
print("First format: ", formatted_string)
# display as 10:15:00 (24 hour clock, no AM/PM)
formatted_string = t.strftime("%H:%M:%S")
print("Second format: ",formatted_string)
# Formatting date objects
from datetime import date
d = date(year = 1999, month = 11, day =3)
# display as November, 03, 1999
# string passed to strftime includes all necessary spaces and commas
formatted_string = d.strftime("%B, %d, %Y")
print("First format: ", formatted_string)
# display as Nov 03 99
formatted_string = d.strftime("%b %d %y")
print("Second format: ", formatted_string)
# Formatting datetime objects
from datetime import datetime
dt = datetime(year = 1999, month = 11, day = 3, hour = 10, minute = 15)
# display as November, 03, 1999 @ 10:15 AM
formatted_string = dt.strftime("%B, %d, %Y @ %I:%M %p")
print("First format: ", formatted_string)
# display as Nov 03 99 / 10:15:00
formatted_string = dt.strftime("%b %d %y / %H:%M:%S")
print("Second format: ", formatted_string)
|
342a47f223a8445dc5a4a74defbd9a99881f3027 | ryndovaira/leveluppythonlevel1_300321 | /topic_02_syntax/examples/03_bool.py | 762 | 3.75 | 4 | print("type(True) = >", type(True))
print("True + 3 = >", True + 3)
print("False + 3 = >", False + 3)
print("True == 1 = >", True == 1)
print("True == 77 = >", True == 77)
print("False == 0 = >", False == 0)
print("False == '0' = >", False == '0')
print("bool(77) = >", bool(77))
print("bool(-77) = >", bool(-77))
print("bool(0) = >", bool(0))
print("bool(' ') =", bool(" "))
print("bool('') =", bool(""))
print("bool('0') =", bool("0"))
print("bool([]) = >", bool([]))
print("4 + 7 == 9 = >", 4 + 7 == 9)
print("'asd' == 'asd' = >", 'asd' == 'asd')
print("-----------------------------------------------------------------------------------------------------------")
my_result = 7 * 86 * 8 / 685 + 8
if my_result:
print('!=0')
else:
print('==0')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.