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
|
---|---|---|---|---|---|---|
716372e3033009476d2e08c1142b39cbca07d554 | AnhQuanTrl/kqueens | /queen_multi_constraint.py | 1,201 | 3.515625 | 4 | from typing import Dict, List
from constraint import Constraint, V, D
class QueenMultiConstraint(Constraint[int, int]):
def __init__(self, columns: List[int]) -> None:
super().__init__(columns)
self.columns: List[int] = columns
def is_satisfied(self, assignment: Dict[int, int]) -> bool:
for col1, row1 in assignment.items():
for col2 in range(col1 + 1, len(self.columns)):
if col2 in assignment:
row2: int = assignment[col2]
if row1 == row2:
return False
if abs(row2 - row1) == abs(col2 - col1):
return False
return True
def get_conflicted(self, assignment: Dict[int, int]) -> List[int]:
conflicted_variable: List[int] = []
for col1, row1 in assignment.items():
for col2 in range(col1 + 1, len(self.columns)):
if col2 in assignment:
row2: int = assignment[col2]
if row1 == row2 or abs(row2 - row1) == abs(col2 - col1):
conflicted_variable.extend([col1, col2])
return list(set(conflicted_variable))
|
0017822b7071426624b33945d2ce1cdc75c07464 | golden-garage/PyGameWorkshop | /displayscr.py | 525 | 3.5 | 4 |
import pygame #This is to import the pygame library
pygame.init() #we need to initialise all the modules in pygame
gameDisplay = pygame.display.set_mode((1280,1024)) #gameDisplay is the name of the surface we create. The resolution of the screen is 1280x1024.
pygame.display.set_caption('Hello Wormy') #We want to set the caption as Hello Wormy
pygame.display.update() #the changes in the frame can be shown only if it is updated. Hence we update the screen
pygame.quit() #Quits the pygame module
quit() #quits python
|
9be0edba00fa13ea1f5eefbe785aa6cfc37c7f9a | benscruton/python_fundamentals | /coding_dojo_assignments/fundamentals/fun_ctions.py | 1,262 | 4.59375 | 5 | # Odd/Even:
# Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
def odd_even(max):
for i in range(1, max + 1):
quality = "odd" if i % 2 else "even"
print(f"Number: {i}. This is an {quality} number.")
# odd_even(2000)
# Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by a second argument.
def multiply(l, multiplier):
return [item * multiplier for item in l]
# print(multiply([2,4,10,16], 5))
# Hacker Challenge:
# Write a function that takes the multiply function call as an argument. Your new function should return the multiplied list as a two-dimensional list. Each internal list should contain the 1's times the number in the original list. Here's an example:
# def layered_multiples(arr):
# # your code here
# return new_array
# x = layered_multiples(multiply([2,4,5],3))
# print x
# # output
# >>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
def layered_multiples(l):
return [ [1] * num for num in l ]
print(layered_multiples(multiply([2,4,5], 3))) |
834f02c26737e97e99cddf2d07934e0c9d38b80d | toufiq007/Python-Tutorial-For-Beginners | /OOP/instance_method.py | 530 | 3.859375 | 4 |
# instance method
class Person:
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def full_name(self):
full_name = self.first_name+ ' ' + self.last_name
return full_name
def is_avobe(self):
return self.age > 18
p1 = Person('Mostafiz','Limon',11)
p2 = Person('Tamim','Hassan',21)
print(p1.first_name)
print(p1.last_name)
print(p1.full_name())
print(p1.is_avobe())
# print(p2.full_name())
|
efed3649aecb7e9b3ef667a3f2aba21540a1e070 | senel-study/kosmo-3rd | /s.yoon/kakao_2019_1/kakao4_proto.py | 564 | 3.5 | 4 | def muji(k, food_times):
tmp = 0
flag = True
if k >= sum(food_times):
food = -1
return food
while flag:
for i, _ in enumerate(food_times):
if food_times[i] is not 0:
food_times[i] -= 1
tmp+=1
if tmp == k+1:
if i == len(food_times)-1:
food = len(food_times)
else:
food = i+1
flag = False
break
return food
result = muji(5, [3,1,2])
print(result)
|
370d077e96fae1268e4dd7756d8c9c2faa28abc1 | iancwwong/Text-Based-Adventure-Game | /src/FloodFillNode.py | 311 | 3.75 | 4 | # This class represents a node when using the flood fill algorithm
class FloodFillNode(object):
# Attributes
pos = {} # Position of node in the format {'x': X, 'y': Y}
items = [] # List of items possessed at this node
def __init__(self, nodePos, itemlist):
self.pos = nodePos
self.items = itemlist |
7bb5c2a83b9b1ddebaf097f5c511fc2c0c163380 | wezil/algorithmic-thinking | /1p-graph-degree-dist.py | 2,292 | 3.828125 | 4 | """
Degree distribution for graphs
Project 1, Algorithmic Thinking (Part 1)
This is a simple set of methods to analyze
the degree distribution of directed graphs
Author: Weikang Sun
Date: 6/4/15
Codeskulptor source:
http://www.codeskulptor.org/#user40_jdtGmYLlQ1_4.py
"""
# project 1 example directed graphs
EX_GRAPH0 = {0: set([1, 2]),
1: set([]),
2: set([])}
EX_GRAPH1 = {0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3]),
3: set([0]),
4: set([1]),
5: set([2]),
6: set([])}
EX_GRAPH2 = {0: set([1, 4, 5]),
1: set([2, 6]),
2: set([3, 7]),
3: set([7]),
4: set([1]),
5: set([2]),
6: set([]),
7: set([3]),
8: set([1, 2]),
9: set([0, 3, 4, 5, 6, 7])}
def make_complete_graph(num_nodes):
"""
Returns a complete graph given n num_nodes
n*(n-1)/2 edges will be generated
"""
_digraph = {}
# creates a set with all nodes
_full_set = set(range(num_nodes))
# simply remove own node for each node set
for node in range(num_nodes):
_digraph[node] = _full_set.difference(set([node]))
return _digraph
def compute_in_degrees(digraph):
"""
Returns a dictionary of number of
in-degrees for all nodes in the graph
"""
_node_indeg = {}
# creates the init 0 indegree node dic
for key in digraph.keys():
_node_indeg[key] = 0
# iterates over all set values in the dictionary
for key in digraph.keys():
for head in digraph[key]:
_node_indeg[head] += 1
return _node_indeg
def in_degree_distribution(digraph):
"""
Returns an unnormalized distribution
of the number of in-degrees in the graph
"""
# calls compute_in_degrees(), get in-degree list
_indeg_list = compute_in_degrees(digraph).values()
_indeg_dist = {}
for value in _indeg_list:
# check existing key, increment if so
if _indeg_dist.has_key(value):
_indeg_dist[value] += 1
# otherwise create new key:value pair
else:
_indeg_dist[value] = 1
return _indeg_dist
|
0b4b1a5261237823c6f066ae770ad0e2f411fa35 | sdbarnes/R1 | /3.2.1_nested_elif.py | 830 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 4 10:31:43 2019
@author: Scott
"""
# - If you've been dating for at least 4 years, give them a
# dog ("dog").
# - If you've been dating for at least 1 year but less than
# 4 years, give them a watch ("watch").
# - If you've been dating for at least 6 months but less than
# 1 year, give them concert tickets ("concert tickets").
# - If you've been dating for at least a day but less than 6
# months, give them candy ("candy").
# - If aren't actually dating, go big or go home: give them
# a yacht to sail away together ("yacht").
years = 0
months = 5
days = 0
if years>4:
print("dog")
elif years >=1:
print("watch")
elif months >= 6:
print ("concert tickets")
elif months or days >=1:
print("candy")
else:
print ("yacht")
|
d3cdbbea323c316d2be106f50b114b170a7e6340 | mhtehrani/Algorithms | /Knapsack_DynamicProgramming.py | 792 | 3.65625 | 4 | """
Knapsack without Repetitions (Dynamic Programming)
==================================================
@author: mhtehrani
September 17, 2021
https://github.com/mhtehrani
"""
def optimal_weight(W, w):
value = [0]*(len(w)+1)
for i in range(len(w)+1):
value[i] = [0]*(W+1)
#end
for i in range(1,len(w)+1):
for j in range(1,W+1):
value[i][j] = value[i-1][j]
# print(w[i-1], j)
if w[i-1] <= j:
val = value[i-1][j-w[i-1]]+w[i-1]
if value[i][j] < val:
value[i][j] = val
#end
#end
#end
#end
return value[len(w)][W]
W, n = list(map(int, input().split()))
w = list(map(int, input().split()))
print(optimal_weight(W, w)) |
a44931c323483e383c1969b69c62b2593fd049e3 | Carolusian/leetcode | /p1_add_two.py | 211 | 3.734375 | 4 | def two_sum(nums, target):
for k1, v1 in enumerate(nums):
for k2, v2 in enumerate(nums):
if v1 + v2 == target and k1 != k2:
return [k1, k2]
print(two_sum([3, 2, 4], 6))
|
f7c3f9d79a44402d2c45e16405789e82c1a2950c | dnknown1/okaj | /pygame/aisearchtools.py | 2,661 | 3.984375 | 4 | class Node:
"""
Base Node class: every states of actual problem to be converted into
this datastructure. A node representes each point in the problem set
"""
def __init__(self, state+None, action+None, cost+None):
self.state = state
self.action = action
self.parent = parent
self.cost = cost
def __eq__(self, other):
return self.state == other.state
class Agent:
"""
Base Artificial Agent Class thst percieves a given envioronment and acts upon
# defalut container is list
"""
def __init__(self, start_state, end_state, container= list()):
self.memo = set()
self.container = container
self.state = start_state
self.goal = end_state
# override
def action(self):
"""while nodes in self.state.action.pop: self.container
"""
pass
# override
def transition(self):
pass
# Only to run unless you cetainly know what wre you doing
def explore(self):
if self.state == self.goal:
return self.state
self.action()
self.transition()
return self.explore() if self.container else False
class dfsAgent(Agent):
def __init__(self, state_space, start, end):
super.__init__(self,start, end):
self.path = list()
self.cost = int()
# utility function that converts a (sparce)mattrix to Graph
def state_space(problem, row, col):
"""
Converts a problem matrix to a Graph G(State Space)
"""
state_space = list()
# make nodes
for i in range(row): # row
for j in range(col): #column
actions = set()
# if visitable
if not problem[i][j]:
#find neighbours
#left
if (j-1) >= 0 and not problem[i][j-1]:
actions.add((i, j-1))
#right
if (j+1) < col and not problem[i][j+1]:
actions.add((i, j+1))
#up
if (i-1) >= 0 and not problem[i-1][j]:
actions.add((i-1, j))
#down
if (i+1) < row and not problem[i+1][j]:
actions.add((i+1, j))
# create node
state_space.append(Node((i, j), actions))
return state_space
# utility function to print mattrix as 2d
def pp(a, row, col):
print('\t')
for _,j in enumerate(a):
print(*j)
# sample Problem
prb = [
[1, 0, 0, 1, 0],
[1, 1, 0, 0, 1],
[0, 0, 0, 0 ,1],
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 1]
]
row = len(prb)
col = len(prb[0])
pp(state_space(prb, row, col))
|
b37fbaa5a7fca0bef6d76332d8b69e5d05b1a37e | HOPExxp/QZ | /daya爬虫/8-18/bs4_test.py | 2,214 | 3.90625 | 4 | html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
and they lived at the bottom of a well.</p>
<p class="story">...</p>
<html>
"""
from bs4 import BeautifulSoup
# soup=BeautifulSoup(html,'lxml')
#
# #基本用法
# print(soup.prettify())#把解析的字符串以标准的缩进格式输出
# print(soup.title.string)#调用string获取title文本内容
#
# #1.选择元素
# print(soup.head)#全部内容
# print(soup.p)#当有多个节点的时候,只会返回第一个节点
#
# #2.提取信息
# #-1节点名称name
# print(soup.head.name)
# #-2节点属性和值
# print(soup.p.attrs)
# print(soup.p.attrs['name'])
# #-3获取节点内容
# print(soup.p.string)
#3.嵌套选择 sb
#4.关联选择
#选取某个节点为基准再选择它的子节点、父节点、兄弟节点,这种叫做关联选择
html1 = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">
<span>Elsie</span>
</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html1,'lxml')
#print(soup.prettify())
print(soup.p.contents)
print('-------------------')
print(soup.p.children)
#enumerate()函数可以将一个可遍历的数据对象(list 元组,字符串等)组合成一个 索引序列,同时列出数据和数据下标
for a,child in enumerate(soup.p.children):
print(a,child) |
f6b407bba48460f485a1d4f74f31bf87c86390c4 | kmurphy/coderdojo | /01-Guess_my_Number/code/Storing_Information.py | 58 | 3.640625 | 4 | x = 5
print(x)
print(x * 4)
x = "5"
print(x)
print(x * 4) |
504aa625dc6fdd7e415c3956390319f0ffaa4656 | starswap/WBGSAlgorithms | /Algorithms/Day 2 Bubble Sort/bubble sort.py | 819 | 4.21875 | 4 | #Python implementation of Bubble Sort by James
#array = [2,83,6,6,88,97,5,154,3,4,35,7,8,2,5,10,7,8,18]
sorted = False
def bubble_sort (array,sorted):
while sorted == False:
#sorted = False
changed = False # sets changed back to false
for i in range (len (array)-1):
if array[i] > array[i+1]:
tmp = array[i]
array[i] = array[i+1] # swapping the variables around
array[i+1] = tmp
changed = True # used to check if a swap has occured at any point during a run down the list
#sorted = False
if changed == False: # checking if the list is sorted
sorted = True # this could probably be more optimized
bubble_sort (array,sorted)
print(array)
|
8e0af157a922e32db42224e62987ccbbf9fc5069 | gimdongwon/Coding_Test | /Dongwon/Test_question/PriviousTest_Kakao/2020/Internship/keypad/keypad.py | 1,122 | 3.796875 | 4 | def solution(numbers, hand):
answer = ''
position = [[3,1], [0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
left, right = [3,0], [3,2]
for number in numbers:
if number in [1,4,7]:
answer += "L"
left = position[number]
elif number in [3,6,9]:
answer += "R"
right = position[number]
else:
left_distance = abs(left[0] - position[number][0]) + abs(left[1] - position[number][1])
right_distance = abs(right[0] - position[number][0]) + abs(right[1] - position[number][1])
# print(left_distance,right_distance)
if left_distance > right_distance:
answer += "R"
right = position[number]
elif left_distance < right_distance:
answer += "L"
left = position[number]
else:
if hand == "right":
answer += "R"
right = position[number]
else:
answer += "L"
left = position[number]
return answer |
281958c094306433b35814ac89a8fb449b5a0952 | tahmid-tanzim/problem-solving | /Stacks_and_Queues/Min-Max-Stack-Construction.py | 1,665 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Min%20Max%20Stack%20Construction
"""
Write a MinMaxStack class for a Min Max Stack. The class should
support:
1. Pushing and popping values on and off the stack.
2. Peeking at the value at the top of the stack.
3. Getting both the minimum and the maximum values in the stack at any given
point in time.
All class methods, when considered independently, should run in constant time
and with constant space.
Sample Usage
// All operations below are performed sequentially.
MinMaxStack(): - // instantiate a MinMaxStack
push(5): -
getMin(): 5
getMax(): 5
peek(): 5
push(7): -
getMin(): 5
getMax(): 7
peek(): 7
push(2): -
getMin(): 2
getMax(): 7
peek(): 2
pop(): 2
pop(): 7
getMin(): 5
getMax(): 5
peek(): 5
"""
class MinMaxStack:
def __init__(self):
self.container = []
def peek(self):
return self.container[-1]
def pop(self):
last_value = self.container[-1]
del self.container[-1]
return last_value
def push(self, number):
self.container += [number]
def getMin(self):
minimum_value = self.container[0]
i = 1
while i < len(self.container):
if self.container[i] < minimum_value:
minimum_value = self.container[i]
i += 1
return minimum_value
def getMax(self):
maximum_value = self.container[0]
i = 1
while i < len(self.container):
if self.container[i] > maximum_value:
maximum_value = self.container[i]
i += 1
return maximum_value
if __name__ == "__main__":
pass
|
9de4ef74ed3e7d2bb116c2433768aeb1a252b98b | JormanWell/exercicios | /Range exercice.py | 307 | 3.875 | 4 | # [1, 2, 3] --> 6
count = 0
for number in range(1, 4):
count = count + number # nova contagem + a velha contagem
print(count)
# outro modo de fazer
def sum_list(my_list):
count = 0
for number in my_list:
count = count + number
print(my_list)
print(count)
|
8a033b947cffe225b5ad6c2a4a990a9e32230948 | AJayTheProgrammer/developing-journey | /FindBirthdayDay.py | 223 | 3.828125 | 4 | import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%m %d %Y')
day = born.weekday()
return calendar.day_name[day]
date = '01 02 1999'
print(findDay(date))
|
3ed341a5c740470e34ccbbe91add4ef8b1523d8a | DanielPravitz/DesignPatterns | /taxes.py | 2,026 | 3.59375 | 4 | from abc import ABCMeta, abstractmethod
from budget import Budget
class Tax(object):
def __init__(self, tax= None) -> None:
super().__init__()
self.__tax = tax
def calculate_another_tax(self, budget: Budget) -> float:
if self.__tax is None:
return 0
return self.__tax.calculate(budget)
@abstractmethod
def calculate(self, budget: Budget) -> float:
pass
class TaxCondicionalTemplate(Tax):
__metaclass__ = ABCMeta
def calculate(self, budget: Budget) -> float:
if self.if_max_tax(budget):
return self.max_tax(budget) + self.calculate_another_tax(budget)
else:
return self.min_tax(budget) + self.calculate_another_tax(budget)
@abstractmethod
def if_max_tax(self, object) -> bool:
pass
@abstractmethod
def max_tax(self, object) -> float:
pass
@abstractmethod
def min_tax(self, object) -> float:
pass
class ISS(Tax):
def calculate(self, budget: Budget) -> float:
return budget.value * 0.1 + self.calculate_another_tax(budget)
class ICMS(Tax):
def calculate(self, budget: Budget) -> float:
return budget.value * 0.06 + self.calculate_another_tax(budget)
class ICPP(TaxCondicionalTemplate):
def if_max_tax(self, budget: Budget) -> bool:
return budget.value > 500
def max_tax(self, budget: Budget) -> float:
return budget.value * 0.07
def min_tax(self, budget: Budget) -> float:
return budget.value * 0.05
class IKCV(TaxCondicionalTemplate):
def if_max_tax(self, budget: Budget):
return budget.value > 500 and self.__more_than_100(budget)
def max_tax(self, budget: Budget) -> float:
return budget.value * 0.1
def min_tax(self, budget: Budget) -> float:
return budget.value * 0.06
def __more_than_100(self, budget: Budget):
for item in budget.get_itens():
if item.value > 100:
return True
return False
|
5558ec47e4fa41a2d38043069a0d933024cbebb0 | poszy/UdacityDA | /Week 10 - Sorting Algorithms/BubbleSort.py | 2,037 | 4.5 | 4 | # In-place : an algorithm that sorts the data inside the data structure without having to copy over the data to a new datastructure
# Naive Approach: whatever comes to mind to solve the problem, there will always be a better way.
# ITs important to know the time complexity of sorting algorithms.
# Bubble sort
# Given a list, [7,3,1,,0,8]
# compare the first two elements, if the second element is lower, shift the two elements,
# keep doing this until the list is in order, this will take forever as there are a lot of iterations that must be completed.
# ITeration
# 1 , 2 , 3 ,4
#
# comparisons
# n-1, n-1, n-1, n-1 = (n-1)(n-1) = n2 -2n + 1
# Worst case = O(n^2)
# Average case = O(n^2)
# Best case = O(n) (the array was already sorted)
# space = O(1) because the algorithm is IN-PLACE, no other datastructure was used, and the array was sorted in place
wakeup_times = [16,49,3,12,56,49,55,22,13,46,19,55,46,13,25,56,9,48,45]
def bubble_sort_1(l):
for iteration in range(len(l)):
for index in range(1, len(l)):
this = l[index]
prev = l[index - 1]
if prev <= this:
continue
l[index] = prev
l[index - 1] = this
bubble_sort_1(wakeup_times)
print ("Pass" if (wakeup_times[0] == 3) else "Fail")
# Bubble Sort with two
# Entries are (h, m) where h is the hour and m is the minute
sleep_times = [(24,13), (21,55), (23,20), (22,5), (24,23), (21,58), (24,3)]
def bubble_sort_2(l):
# TODO: Implement bubble sort solution
for i in range(len(l)):
for index in range(1, len(l)):
this_hour, this_min = l[index]
prev_hour, prev_min = l[index -1]
if prev_hour > this_hour or (prev_hour == this_hour and prev_min > this_min):
continue
l[index] = (prev_hour, prev_min)
l[index -1] = (this_hour, this_min)
pass
bubble_sort_2(sleep_times)
print ("Pass" if (sleep_times == [(24,23), (24,13), (24,3), (23,20), (22,5), (21,58), (21,55)]) else "Fail")
|
9cd467c15625206ce18e3022ddb764aa191e2934 | cielliyuanpeng/learn_Python_in_hard_way | /ex31.py | 1,850 | 3.890625 | 4 | while True:
door = input("""
你从黑暗中醒来
此时,你身处一个幽暗的房间之中,你的面前有两扇门。\n
一扇门上是白底黑字的生,另一扇门上是黑底白字的死\n
请问您选择进入哪一间?\n
1.生门 2.死门
""")
if door == "1":
print("""
你推开生门,进入其中
发现是一片阳光明媚的草地
草地上鲜花盛开,阳光和煦,微风习习
不远处仿佛有一口水井,一位朴素打扮的妇人正在打水
此时,她也看到了你
请问要和他打招呼吗?
1. 打招呼 2.视而不见
""")
hello = input(">")
if hello == "1":
print("""
她很和善的邀请你去她家坐坐
你也跟随她去了她家
一间简朴的屋子没有过多的装饰
她说:“就在这住下吧,我觉得我们会生活的很愉快”
从此你们快乐地生活在了一起,直到死去
在死去的前一刻,你似乎意识到了什么不对劲的地方
end
""")
break;
if hello == "2":
print("""
她很和善的邀请你去她家坐坐
你也跟随她去了她家
一间简朴的屋子没有过多的装饰
她说:“就在这住下吧,我觉得我们会生活的很愉快”
从此你们快乐地生活在了一起,直到死去
在死去的前一刻,你似乎意识到了什么不对劲的地方
end
""")
break;
elif door == "B":
pass
else:
print("""
房间中慢慢传来奇怪的味道\n
你的意识渐渐昏沉,身体提不起力气\n
忽然你感受到强烈的下坠感\n
似乎掉到了什么软乎乎的东西上\n
原来是一座尸山\n
你因[资料删除]而死
""")
break;
|
ca2ebf61520ac779a77e0a11642064836c805a3e | Sbarj130917/Implementing_Algorithms---Python | /inplace_quicksort.py | 1,097 | 4.125 | 4 | # array_to_be_sorted[] = Array which is to be sorted,
# low = Starting index of the array,
# high = Ending index of the array
def array_partition(array_to_be_sorted,low,high):
pivot = array_to_be_sorted[high] # last element of the array is being taken as pivot
x = ( low-1 )
for y in range(low , high):
# check whether current element is smaller than or equal to pivot
if array_to_be_sorted[y] <= pivot:
# increment index of smaller element
x = x+1
array_to_be_sorted[x],array_to_be_sorted[y] = array_to_be_sorted[y],array_to_be_sorted[x]
array_to_be_sorted[x+1],array_to_be_sorted[high] = array_to_be_sorted[high],array_to_be_sorted[x+1]
return ( x+1 )
# Quick sort function
def quickSort(array_to_be_sorted,low,high):
if low < high:
# pi is partitioning index
pi = array_partition(array_to_be_sorted,low,high)
# Sorting of elements separately before and after partition
quickSort(array_to_be_sorted, low, pi-1)
quickSort(array_to_be_sorted, pi+1, high)
|
2ddfd43fb293816cb720943766c2e718bd0e029f | pxz97/AlgorithmsByPython | /BasicAlgorithms/Tree/InorderTraversal.py | 453 | 3.71875 | 4 | def inorderTraversal_recur(root):
if not root:
return []
return inorderTraversal_recur(root.left) + [root.val] + inorderTraversal_recur(root.right)
def inorderTraversal(root):
stack = []
res = []
cur = root
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
|
8c4c454418f227b26a07a4f5687a513c3eb3f6e4 | anucoder/Python-Codes | /02_Strings.py | 837 | 4.25 | 4 |
mystring = 'Hello world'
print(mystring)
#indexing
print(mystring[0])
#negative indexing
print(mystring[-1])
#slicing
print(mystring[2:]) #strat at index 2 and print all the way to end
print(mystring[:3]) #strat at index 0 atill the index 2 (not including 3)
print(mystring[2:5]) #strat at index 2 and till 4
print(mystring[:]) #sentire mystring
print(mystring[::2]) #step size of 2
#immutable
#mystring[0] = 'x'
#Basic methods
x = mystring.upper() #uppercase
y = mystring.lower() #lowercase
z = mystring.capitalize() #capitalize first letter
print(x)
print(y)
print(z)
spl = mystring.split('o') #returns an array of strings after splitting
print(spl)
#print formatting
#inserting strings
x = "Item One : {} ,Item Two : {}".format("dog","cat")
print(x)
x = "Item One : {y} ,Item Two : {x}".format(x="dog",y="cat")
print(x)
|
2b69fa88dc67644b1ac8ad890c8db3994157fdef | digrawal/python_lover | /healf_man_sys.py | 4,752 | 3.90625 | 4 | def getdate():
import datetime
return datetime.datetime.now()
"""print("enter the name of the person among rahul ,lokesh and pappu you want operate\n")
s=input()
if s== "rahul":
print("write,what do u want log or retrive\n")
lg=input()
if lg=="log":
print("write exercise or food to log\n")
rf=input()
if rf=="food":
print("enter food item\n")
rfd=input()
with open("rahul_f.txt","a") as f:
f.write(str([str(getdate())]) + rfd +"\n")
print("file written successfully")
f.close()
elif rf == "exercise":
print("enter exercise name\n")
rfd = input()
with open("rahul_e.txt", "a") as f:
f.write(str([str(getdate())]) + rfd + "\n")
print("file written successfully")
f.close()
else:
print("inter valid input between food or exercise")
elif lg=="retrive":
print("retrive food or exercise\n")
rf = input()
if rf == "food":
with open("rahul_f.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
elif rf=="exercise":
with open("rahul_e.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
if s== "lokesh":
print("write,what do u want log or retrive\n")
lg=input()
if lg=="log":
print("write exercise or food to log\n")
rf=input()
if rf=="food":
print("enter food item\n")
rfd=input()
with open("lokesh_f.txt","a") as f:
f.write(str([str(getdate())]) + rfd +"\n")
print("file written successfully")
f.close()
elif rf == "exercise":
print("enter exercise name\n")
rfd = input()
with open("lokesh_e.txt", "a") as f:
f.write(str([str(getdate())]) + rfd + "\n")
print("file written successfully")
f.close()
else:
print("inter valid input between food or exercise")
elif lg=="retrive":
print("retrive food or exercise\n")
rf = input()
if rf == "food":
with open("lokesh_f.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
elif rf=="exercise":
with open("lokesh_e.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
if s== "pappu":
print("write,what do u want log or retrive\n")
lg=input()
if lg=="log":
print("write exercise or food to log\n")
rf=input()
if rf=="food":
print("enter food item\n")
rfd=input()
with open("pappu_f.txt","a") as f:
f.write(str([str(getdate())]) + rfd +"\n")
print("file written successfully")
f.close()
elif rf == "exercise":
print("enter exercise name\n")
rfd = input()
with open("pappu_e.txt", "a") as f:
f.write(str([str(getdate())]) + rfd + "\n")
print("file written successfully")
f.close()
else:
print("inter valid input between food or exercise")
elif lg=="retrive":
print("retrive food or exercise\n")
rf = input()
if rf == "food":
with open("pappu_f.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
elif rf=="exercise":
with open("pappu_e.txt", "r") as f:
print("you log for food:")
print(f.read())
f.close()
"""
i=int(input("enter 0 for log and 1 for retriev\n"))
if i==0:
j=int(input("enter 0 for harry ,1 for jack,2 for raj\n"))
k=int(input("enter 0 for food and 1 for exercise\n"))
l1=["harry","jack","raj"]
l2=["food","exercise"]
with open((l1[j]+"_"+l2[k])+".txt","a") as f:
val=str(input("enter item\n"))
f.write(str("Date:-") + str( getdate()) + "---" + val+"\n")
f.close()
elif i==1:
j = int(input("enter 0 for harry ,1 for jack,2 for raj\n"))
k = int(input("enter 0 for food and 1 for exercise\n"))
l1 = ["harry", "jack", "raj"]
l2 = ["food", "exercise"]
with open((l1[j] + "_" + l2[k]) + ".txt", "r") as f:
print(f.read())
f.close()
|
3bf2c2d2f805fa388e175413c58556a0ba984a3e | astikanand/Interview-Preparation | /Data Structures/11. Advanced Data Structures/2_avl_tree.py | 5,111 | 3.984375 | 4 | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
def insert(root, key):
###### Step-1: Perform Normal BST insertion.
if not root:
return Node(key)
elif key < root.val:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
###### Step-2: Update the height of the ancestor node.
root.height = 1 + max(get_height(root.left), get_height(root.right))
###### Step-3: Get the balance factor.
balance = get_balance_factor(root)
###### Step-4: If the node is unbalanced, then try out the 4 cases discussed.
### a) Left Left Case:
if balance < -1 and key < root.left.val:
return right_rotate(root)
### b) Left Right Case:
if balance < -1 and key > root.left.val:
root.left = left_rotate(root.left)
return right_rotate(root)
### c) Right Right Case:
if balance > 1 and key > root.right.val:
return left_rotate(root)
### d) Right Left Case:
if balance > 1 and key < root.right.val:
root.right = right_rotate(root.right)
return left_rotate(root)
return root
def delete(root, key):
###### Step-1: Perform Normal BST deletion.
if not root:
return root
elif key < root.val:
root.left = delete(root.left, key)
elif key > root.val:
root.right = delete(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = min_node(root.right)
root.val = temp.val
root.right = delete(root.right, temp.val)
###### If the tree has only one node simply return it
if root is None:
return root
###### Step-2: Update the height of the ancestor node.
root.height = 1 + max(get_height(root.left), get_height(root.right))
###### Step-3: Get the balance factor.
balance = get_balance_factor(root)
###### Step-4: If the node is unbalanced, then try out the 4 cases discussed.
### a) Left Left Case:
if balance < -1 and key < root.left.val:
return right_rotate(root)
### b) Left Right Case:
if balance < -1 and key > root.left.val:
root.left = left_rotate(root.left)
return right_rotate(root)
### c) Right Right Case:
if balance > 1 and key > root.right.val:
return left_rotate(root)
### d) Right Left Case:
if balance > 1 and key < root.right.val:
root.right = right_rotate(root.right)
return left_rotate(root)
return root
def right_rotate(current_pivot):
# current_pivot's left will become the new_pivot
# new_pivot's right will change so store it as T2.
new_pivot = current_pivot.left
T2 = new_pivot.right
# Perform rotation: Change the new_pivot's right as current pivot
# and then make current pivot's left T2
new_pivot.right = current_pivot
current_pivot.left = T2
# Update heights for both pivot and new_pivot
current_pivot.height = 1 + max(get_height(current_pivot.left), get_height(current_pivot.right))
new_pivot.height = 1 + max(get_height(new_pivot.left), get_height(new_pivot.right))
# Return the new root
return new_pivot
def left_rotate(current_pivot):
# current_pivot's right will become the new_pivot
# new_pivot's left will change so store it as T2.
new_pivot = current_pivot.right
T2 = new_pivot.left
# Perform rotation: Change the new_pivot's left as current pivot
# and then make current pivot's right T2
new_pivot.left = current_pivot
current_pivot.right = T2
# Update heights for both pivot and new_pivot
current_pivot.height = 1 + max(get_height(current_pivot.left), get_height(current_pivot.right))
new_pivot.height = 1 + max(get_height(new_pivot.left), get_height(new_pivot.right))
# Return the new root
return new_pivot
def get_height(node):
if node is None:
return 0
return node.height
def get_balance_factor(node):
if node is None:
return 0
return get_height(node.right) - get_height(node.left)
def min_node(current_node):
# If current_node is None, min_node not possible
if(current_node is None):
return None
min_node = current_node
while(min_node.left):
min_node = min_node.left
return min_node
def print_preorder(root):
if root:
print(root.val, end=" ")
print_preorder(root.left)
print_preorder(root.right)
print("Print the AVL TREE Traversal:")
root = None
root = insert(root, 10)
root = insert(root, 20)
root = insert(root, 30)
root = insert(root, 40)
root = insert(root, 50)
root = insert(root, 25)
print_preorder(root)
print()
print("\nAVL Tree after deleting Node 40:")
root = delete(root, 40)
print_preorder(root)
print() |
361335629a6e686797a8c5805f67e1f10a9b3b99 | endrepapp/quadratic_solver | /Egyenlet1.0/python1.py | 969 | 3.75 | 4 | from math import *
print ("Equation: ax^2 - bx + c = 0. Press ENTER to start")
def szam_beker(betu):
return int(input("Kerem adja meg az {} - erteket: ".format(betu)))
def neg_szamolas(a,b,c):
if (a == 0 & b == 0 & c == 0):
print ("nem angolozok , ilyen ertek nincs ")
else:
minusz_B = b * (-1)
negyzet_B = b * b
gyok_masodik = 4 * a * c
gyok_muv = (negyzet_B) - (gyok_masodik)
if (gyok_muv < 0):
print "equation can not be solved"
else:
# minuszos----------------
sqrt_muv = sqrt(gyok_muv)
veg_muv = minusz_B - sqrt_muv
oszto = 2 * a
minusz_eredmeny = veg_muv / oszto
return minusz_eredmeny
def main():
print "udvozlom az ekezet nelkuli fuggveny megoldoban."
a = szam_beker("a")
b = szam_beker("b")
c = szam_beker("c")
print neg_szamolas(a,b,c)
if __name__ == '__main__':
main()
|
36399265d984fe1c54f6da90585ae64668d3304a | Divisekara/Python-Codes-First-sem | /PA1/PA1 2013/PA1/PA1-13/2013 - PA1 - 13 - Triangular Matrix.py | 834 | 3.96875 | 4 | #PA1 - 13 - Triangular Matrix
a = 1
while (a):
try:
N = int(raw_input("Enter N (where 1<N<10 for size NxN square matrix) = "))
print "Enter the matrix row by row, seperating the elements with spaces."
matrix = []
if N>=10 or N<2:
print "Invalid Input! Enter N in correct range."
n = 1
for x in range(N):
while True:
row = map(int,raw_input("Enter row %d:"%n).split())
if len(row)!=N:
print "Enter correct number of elements for row, seperating with spaces."
else:
matrix.append(row)
n+=1
break
except ValueError:
print "Enter integer values for the row and column"
continue
else:
|
e784030323fbe3b54b47858032fc826c35e2643a | gguillamon/PYTHON-BASICOS | /python_ejercicios basicos_III/listas/ejercicio2.py | 340 | 4.34375 | 4 | # Crea una lista e inicializala con 5 cadenas de caracteres leídas por teclado.
# Copia los elementos de la lista en otra lista pero en orden inverso,
# y muestra sus elementos por la pantalla.
lista=[]
for x in range(5):
palabras=input("Introduce una palabra: ")
lista.append(palabras)
lista2=[]
lista2=lista
print(lista2[::-1]) |
7c27a19bc69f5621e480fc3f42f85b93cb99d612 | paa-coder/geek_dev_ops | /python/base/hw_7.py | 2,141 | 3.796875 | 4 | import random
import math
separator_task = "*"*100
def separete(something,separator):
print()
print(separator,something,separator)
print()
separete("task №1",separator_task)
fruits = [
"яблоко","банан","апельсин",
"ананас","персик","лимон",
"мандарин","груша","киви"
]
def get_random_fruits(lenght=5):
fruits = [
"яблоко","банан","апельсин",
"ананас","персик","лимон",
"мандарин","груша","киви"
]
return set([random.choice(fruits) for i in range(lenght)])
fruits_first = get_random_fruits()
fruits_second = get_random_fruits(4)
print("first fruits list:{}\nsecond fruits list:{}".format(fruits_first,fruits_second))
print("lists contains same fruits: {}".format([i for i in fruits_first if i in fruits_second]))
separete("task №2",separator_task)
random_int = set([random.randint(-100,100) for i in range(30)])
print("random numbers list:\n{}".format(random_int))
print("selected list condition( Элемент кратен 3,Элемент положительный,Элемент не кратен 4.): {}"
.format([i for i in random_int if i%3==0 and i>=0 and i%4!=0]))
separete("task №3",separator_task)
def get_pow(list):
return [i if i<0 else math.sqrt(i) for i in list.copy() if i!=-1]
init = [random.randint(-10,10) for i in range(5)]
print(" init state list {}".format(init))
print(" result list {}".format(get_pow(init)))
print(" state of init list {}".format(init))
separete("task №4",separator_task)
def cretae_question(question,type):
try:
return type(input(question.strip()+" "))
except Exception as e:
print("Error: value not correct: {}".format(e))
return cretae_question(question,type)
def get_pow_2(integer):
if integer==13:
raise ValueError("not available value {}".format(integer))
return integer**2
try:
x = get_pow_2(cretae_question(" insert integer:", int))
except ValueError as e:
print("Error: {}".format(e))
else:
print("answer: {}".format(x))
|
c4d5de9a77014f8277bda5a2fd2060b217d6142e | swl5571147a/stone | /notes/example/guess.py | 393 | 3.875 | 4 | #!/usr/bin/python
#coding:utf8
import random
num = random.randint(1,20)
for i in '123456':
guess = input('Please enter your guess number:')
if guess == num:
print 'you are right!'
break
else:
if i == '6':
print 'you are so .....'
break
if guess > num:
print 'your enter number is large'
continue
elif guess < num:
print 'your enter number is little'
continue
|
9918272a5907caf7e55b77fa190ca5392e7c337d | david8388/Python-100-Days | /Project/LeetCode/singleNumber1.py | 567 | 3.5625 | 4 | from typing import List
# Runtime: 8900 ms
# Memory Usage: 16.2 MB
#class Solution:
# def singleNumber(self, nums: List[int]) -> int:
# for i in range(len(nums)):
# newNums = nums[:i] + nums[i+1:]
# if nums[i] not in newNums:
# return nums[i]
# Runtime: 80 ms
# Memory Usage: 16.3 MB
class Solution:
def singleNumber(self, nums: List[int]) -> int:
xor_result = 0
for i in nums:
xor_result ^= i
return xor_result
problem = Solution()
print(problem.singleNumber([3, 0, 3]))
|
8ad5453b925ae4a840ba8a58523d7eac816ce737 | reinderien/pyais | /pyais/util.py | 1,895 | 3.890625 | 4 | from bitstring import BitArray
from math import ceil
def split_str(string, chunk_size=6):
"""
Split a string into equal sized chunks and return these as a list.
The last substring may not have chunk_size chars,
if len(string) is not a multiple of chunk_size.
:param string: arbitrary string
:param chunk_size: chunk_size
:return: a list of substrings of chunk_size
"""
chunks = ceil(len(string) / chunk_size)
lst = [string[i * chunk_size:(i + 1) * chunk_size] for i in range(chunks)]
return lst
def ascii6_to_bin(data) -> str:
"""
Convert ASCII into 6 bit binary.
:param data: ASCII text
:return: a binary string of 0's and 1's, e.g. 011100 011111 100001
"""
binary_string = ''
for c in data:
if c < 0x30 or c > 0x77 or 0x57 < c < 0x60:
print("Invalid char")
else:
if c < 0x60:
c = (c - 0x30) & 0x3F
else:
c = (c - 0x38) & 0x3F
binary_string += f'{c:06b}'
return binary_string
def bin_to_ascii6(data):
"""
Encode binary data as 6 bit ASCII.
:param data: binary string
:return: ASCII String
"""
string = ""
for c in split_str(data):
c = int(c, 2)
if c < 0x20:
c += 0x40
if c == 64:
break
string += chr(c)
return string
def signed(bit_vector):
"""
Convert bit sequence to signed integer
:param bit_vector: bit sequence
:return: signed int
"""
b = BitArray(bin=bit_vector)
return b.int
def to_int(bit_string, base=2):
"""
Convert a sequence of bits into an integer.
:param bit_string: Sequence of zeros and ones
:param base: The base
:return: An integer or 0 if no valid bit_string was provided
"""
if bit_string:
return int(bit_string, base)
return 0
|
672721c17dbf40311d0489e93a8f413c5b7d0e58 | Omar7102/fundamentos | /NumeroPar.py | 189 | 4 | 4 | #Programa que muestra si un numero es par
print('Digite el numero')
n=int(input())
if (n % 2) == 0 :
print ('el numero', n, 'es par')
else:
print ( 'el numero', n,'no es par') |
5ad72e3d56246bc745fb208eb7e8a74860c66a3d | srgiola/UniversidadPyton_Udemy | /Fundamentos Python/Manejo de Archivos.py | 1,214 | 3.78125 | 4 | #Abre un archivo
# open() tiene dos parametros, el primero el archivo y el segundo lo que se desea hacer
# r - Read the default value. Da error si no existe el archivo
# a - Agrega info al archivo. Si no existe lo crea
# w - Escribir en un archivo. Si no existe lo crea. Sobreescribe el archivo
# x - Crea un archivo. Retorna error si el archivo ya existe
try:
archivo = open("File_Manejo_Archivos.txt", "w")
archivo.write("Agregando información al archivo \n")
archivo.write("Agregando linea 2")
archivo = open("File_Manejo_Archivos.txt", "r")
''' Formas de leer un archivo
print(archivo.read()) # Leer archivo completo
print(archivo.read(5)) # Numero de caracteres a leer
print(archivo.readline()) # Leer una linea
print(archivo.readlines()) # Lee todas las linea, agrega todo a una lista
print(archivo.readlines()[1]) # Lee solo la linea con indice 1
for linea in archivo:
print(linea)
'''
# Copiando un archivo a otro
archivo2 = open("File_Copia.txt", "w")
archivo2.write(archivo.read())
except Exception as e:
print(e)
finally:
archivo.close() # No es obligatorio
archivo2.close() |
ca47529e8a6d7f4d3ee7ac77e6fc1771ac86be49 | sigudi-kevin/Python_Coursework | /MS-Python-Pre-work/Input/input_demo.py | 2,231 | 4.03125 | 4 | import sys
name = sys.argv[1]
age = sys.argv[2]
# print("How old are you?"))#Comment out to run and vice versa
# age = int(input())
print(name)
print(age) #Prints name and age if initiated with both name and age
list_a = list(range(0,5))#Comment out to run and vice versa
print(list_a)#Displays list from 0 to 5
#
#
# ##########################Using range#################################
for i in range(0,7):
print("I would love " + str(i) + " cookies")
##########################For modulus loop##############################
numbers = [1, 2, 3, 4, 5]
for i in numbers: #Checks out if it is divisible by 2
if i % 2 == 0:
print(i) #Prints out numbers divisible by 2 i.e 2 and 4
########################### Printing in range############################
'''
in a team of members 20, some numbers are taken
and want to display the numbers that are not taken
so others don't pick the picked numbers
'''
# taken numbers
numTaken = [3,5,7,11,13] #Are numbers taken
print("Available numbers")#Directive to print avaliable numbers
# loop
for i in range(1,21):#range defines it from 1 to 21
if i in numTaken:#Condition confirmation
continue
print(i)#Directive to print the numbers
########################## Using extend()method ############################
list_a = ["a","e","i","o","u"]
list_b = [1,2,3,4,5,6,7,8,9,10]
# Joining list_b to list_a
list_a.extend(list_b)
print(list_a) # this will print ["a","b","c","d",1,2,3,4,5,6]
print(list_b) # this will print [1,2,3,4,5,6]
#This adds new values to list_a. Notice that list_b remains unchanged.
#############################Using Append ######################################
list_a = ["a","b","c","d"]
print(list_a) # ["a","b","c","d"]
list_a.append("e")
print(list_a) # ["a","b","c","d","e"]
#Add e to the final array while not affecting the original array
#################################Sorted order##################################
ist_a = [1,3,4,8,5,7,6,2]
list_a.sort()
print(list_a) # [1, 2, 3, 4, 5, 6, 7, 8]
#Prints in sorted order
###############################Reverse Order###################################
list_a = ["a","b","c","d"]
list_a.reverse()
print(list_a) # ['d', 'c', 'b', 'a']
#Prints in reverse
|
91318b684dd0048957a405293d1c53b8978350db | friesia/simple-one | /smp.py | 3,532 | 4.28125 | 4 | #!/usr/bin/python
# a selection of simple Python code to give you a taste of the language ...
#
# Just a few notes about Python:
# Python has a very efficient built-in memory manager.
# Python does not need variable types declared, it is smart enough to figure that out!
# Python uses whitespaces to group statements, this avoids the begin/ends and {}
# of other languages. Let's face it, you use whitespaces anyway in these
# languages to make the code more readable! In other words, Python forces you
# to make code more readable. You get used to the indentations naturally.
# Use the number of spaces you like, the de facto standard is four spaces.
# Important caveat:
# keep the spacing uniform for the group of statements
# that belong together, and don't mix tabs and spaces. Avoid tabs!
#
# I used Python-2.3.4.exe (the Windows installer package for Python23)
# from http://www.python.org/2.3.4/
# code tested with Python23 vegaseat 16jan2005
print "Simple math like 12345679*63 = ", 12345679*63
# print just an empty line
print
# display numbers 0 to 9
# the indentation before print makes it part of the loop
for number in range(10):
print number
# print also adds a newline, use a comma to prevent the newline
for number in range(10):
print number,
print
# import the math module for the sqrt() function
import math
# a little more complex this time
# \n is the newline character, % starts the format specifier
# Python does have its roots in the C language
# notice how we use the sqrt() function from the math module
# CYA: more specifically, sqrt() is a function in module math
print "\nSquare root of integers 0 to 9 formatted as a float with 4 decimals:"
for value in range(10):
squareRoot = math.sqrt(value)
print "sqrt(%d) = %.4f" % (value, squareRoot)
# now it gets a bit more hairy
print "\nDisplay integers 0 to 15 formatted to use 6 spaces ..."
print "(plain, zero-padded, hex and octal)"
print " %s %s %s %s" % ('%6d', '%06d', '%6x', '%6o')
for value in range(16):
print "%6d %06d %6x %6o" % (value, value, value, value)
print
print "\nA not so typical for loop:"
for food in "spam", "eggs", "cumquats":
print "I love", food
print
# a short intro to string slicing
# a little cryptic at first blush, but very powerful
# [begin : < end : step] end is exclusive, step is optional
# defaults are index begin = 0, index end = length, step = 1
animal = "hippopotamus"
print "this is the string = ", animal
print "length of string = ", len(animal)
print "exclude first 3 char = ", animal[3: ]
print "exclude last 4 char = ", animal[:-4]
print "reverse the string = ", animal[::-1]
# define/create a function
# the indented lines are part of the function
def convertFahrenheit2Celsius(fahrenheit):
celcius = 0.555 * (fahrenheit - 32)
return celcius
print
# and use the function
# (make sure you define/create the function before you call it)
print "A Fahrenheit to Celcius table:"
# range is from -40 to < 220 in steps of 10
for tf in range(-40, 220, 10):
print "%5.1fF = %5.1fC" % ( tf, convertFahrenheit2Celsius(tf) )
print
print "A limited set:"
# another variation of the for loop
for tf in -40,0,32,98.6:
print "%5.1fF = %5.1fC" % ( tf, convertFahrenheit2Celsius(tf) )
print
# test boolean results
print "Is 3 > 5? Result =", 3 > 5 # result = False
print "Is 3 < 5? Result =", 3 < 5 # result = True
# optional wait for keypress
raw_input('Press Enter...')
|
dbf04ba79765e0f081ea5e542337bbac872a373b | linzowo/GAME_PRACTICE | /bullet.py | 1,011 | 3.796875 | 4 | #_*_ coding: utf_8 _*_
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""子弹类"""
def __init__(self,ai_seting,screen,ship):
"""在飞船所在的位置创建一个子弹"""
super(Bullet,self).__init__()
self.screen = screen
#在(0,0)处创建一个表示子弹的矩形,再设置正确的位置
self.rect = pygame.Rect(0,0,ai_seting.bullet_width,ai_seting.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#将子弹的移动坐标y存储为浮点数,以便能对子弹做微调
self.y = float(self.rect.y)
self.speed_factor = ai_seting.bullet_speed_factor
self.color = ai_seting.bullet_color
def update(self):
"""向上移动子弹"""
self.y -= self.speed_factor
self.rect.y = self.y
def draw_bullet(self):
"""在屏幕上绘制子弹"""
pygame.draw.rect(self.screen,self.color,self.rect)
|
01db9994201559853877b178796bdc90fd899852 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/alexLaws/lesson03/mailroom.py | 3,484 | 3.796875 | 4 | #!/usr/bin/env python3
donor_list = []
donor_list.append({'Name': 'Ryan Moore', 'Donation': 500})
donor_list.append({'Name': 'Ryan Moore', 'Donation': 250})
donor_list.append({'Name': 'Ted Laws', 'Donation': 1000})
donor_list.append({'Name': 'Ted Laws', 'Donation': 100})
donor_list.append({'Name': 'Ben Snell', 'Donation': 150})
donor_list.append({'Name': 'Andrew Crawford', 'Donation': 2000})
donor_list.append({'Name': 'Andrew Crawford', 'Donation': 2000})
donor_list.append({'Name': 'Andrew Crawford', 'Donation': 4000})
donor_list.append({'Name': 'Beth Ross', 'Donation': 400})
def user_action():
print("Choose an action from this list:")
print("Send a Thank You")
print("Create a Report")
print("Quit")
while True:
option = input("What is your choice: ")
if option.lower() in ["send a thank you", "create a report", "quit"]:
return option
break
else:
print("That is not an option. Choose again.")
def dnrs(x):
names = []
for dnr in x:
person = dnr.get("Name")
if person in names:
pass
else:
names.append(person)
return names
def send_to(x):
donors = dnrs(x)
recipient = input("Who is the thank you note for? Enter a full name or 'list' to see a list: ")
if recipient.lower() == 'list':
print("Here are all the donors:")
for name in donors:
print(name)
recipient = input("Who is the thank you note for? ")
return recipient
else:
return recipient
def name_sum(person, x):
donor_total = 0
for i in x:
if i.get('Name') == person:
donor_total += int(i.get('Donation'))
return donor_total
def name_cnt(person, x):
donor_count = 0
for i in x:
if i.get('Name') == person:
donor_count += 1
return donor_count
def thank_you(recip, x):
print("OK, here is a thank you note for {}".format(recip))
total = name_sum(recip, x)
note = "Dear {},\nThank you for your recent donation. You have now donated ${}.\nThank you so much!\n- Alex Laws"
print(note.format(recip, total))
def total_sort(x):
donors = dnrs(x)
to_sort = []
for i in donors:
to_sort.append({'Name': i, 'Total': name_sum(i, x)})
amounts = []
for n in to_sort:
amounts.append(n.get('Total'))
amounts.sort(reverse=True)
ordered = []
for num in amounts:
for i in to_sort:
if i.get('Total') == num:
ordered.append(i.get('Name'))
return ordered
def report(x):
print("Donor Name | Total Given | Num Gifts | Average Gift")
donors = total_sort(x)
for donor in donors:
total = name_sum(donor, x)
number = name_cnt(donor, x)
average = total / number
print("{:17} ${:14,.2f} {:13} ${:13,.2f}".format(donor, total, number, average))
if __name__ == '__main__':
while True:
act = user_action().lower()
if act == "send a thank you":
name = send_to(donor_list)
if name in dnrs(donor_list):
thank_you(name, donor_list)
else:
amt = int(input("Wait, A new donation! How much: "))
donor_list.append({'Name': name, 'Donation': amt})
thank_you(name, donor_list)
if act == "create a report":
report(donor_list)
if act == "quit":
break
print("Would you like to do something else...")
|
cca8b31e57912b86d8ccb58fc48cfa4835ceb7ae | Prashambhuta/learn-python | /learnpython.org/decorators-understanding-day17.py | 1,613 | 4.03125 | 4 | @decorator
def function(arg):
return "value"
# # is same as
def function(arg):
return "value"
function = decorator(function)
#repeater function
@repeater
def multiply(num1, num2):
print(num1 * num2)
multiply(22,2)
# To change the output
def double_out(old_function):
def new_function(*args, **kwds):
return 2 * old_function(*args, **kwds) # modify the return value
return new_function
# To change the input
def double_in(old_function):
def new_function(arg):
return old_function(arg * 2)
return new_function
#
# # To do checking
def check(old_function):
def new_function(arg):
if arg < 0: raise (ValueError, "Negative Argument")
# This will cause an error
old_function(arg)
return new_function
# Multiply the output by a variable amount
def multiply(multiplier):
def multiply_generator(old_function):
def new_function(*args, **kwds):
return multiplier * old_function(*args, **kwds)
return new_function
return multiply_generator # it returns the new generator
# Usage
@multiply(3) # multiply is not a generator, but multiply(3) is
def return_num(num):
return num
# Now return_num is decorated and reassigned to itself
return_num(5)
# Exercise
# Create a decorator which returns a decorator function with one argument.
# Check the input is correct, if not return "Bad Type".
def type_check(correct_type):
# the code goes here
@type_check(int)
def times2(num):
return 2*num
print(times2(2))
times2('Not a number')
@type_check(str)
def first_letter(word):
return word[0]
|
287c342c34b79cc82231195306a25bdd7e9c8233 | chriswolfdesign/MIT600OCW | /master/psets/pset2/ps2_hangman.py | 2,780 | 4.09375 | 4 | # 6.00 Problem Set 3
# Name: Chris Wolf
# E-mail: [email protected]
# Time: 1:30
# Hangman
#
GUESSES_MAX = 8
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
def concealed_current_word(answer, found):
"""
answer (string): the correct answer for the game
found (dict string -> Boolean): a dictionary representing whether or not
a specific letter in our word had been guessed yet
Returns a string of the answer with unguessed characters "hidden"
"""
cache = ''
for letter in answer:
if found[letter]:
cache += letter
else:
cache += '_'
cache += ' '
return cache
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program
wordlist = load_words()
answer = choose_word(wordlist)
guesses_left = GUESSES_MAX
found = {}
for letter in answer:
found[letter] = False
available_letters = 'abcdefghijklmnopqrstuvwxyz'
print 'Welcome to the game, Hangman!'
print 'I am thinking of a word that is', len(answer), 'letters long.'
print '------------'
while guesses_left > 0:
print 'You have', guesses_left, 'guesses left'
print 'Available letters:', available_letters
current_guess = raw_input('Please guess a letter: ')
current_guess = current_guess.lower()
available_letters = available_letters.replace(current_guess, '')
if current_guess in found:
found[current_guess] = True
print 'Good guess:', concealed_current_word(answer, found)
else:
guesses_left -= 1
print 'Oops! That letter is not in my word:', \
concealed_current_word(answer, found)
print '-----------'
# See if the player has won the game and react accordingly
game_won = True
for letter in found:
if not found[letter]:
game_won = False
if game_won:
print 'Congrulations, you won!'
break
# See if the player has lost the game and react accordingly
# BTW, I just lost The Game typing that last comment :_(
if guesses_left < 1:
print 'I\'m sorry, you are out of usable guesses'
print 'Correct answer:', answer
|
749764584851352a9b75bea122be980208f29f44 | exapde/Exasim | /src/Python/Preprocessing/testing.py | 642 | 3.609375 | 4 |
# a = 1;
# b = a + 1;
# d = a+b*3;
# print("hello")
# print("here")
# print(d)
# import matplotlib
# matplotlib.use('Qt5Agg')
# # This should be done before `import matplotlib.pyplot`
# # 'Qt4Agg' for PyQt4 or PySide, 'Qt5Agg' for PyQt5
# import matplotlib.pyplot as plt
# import numpy as np
#
# t = np.linspace(0, 20, 500)
# plt.plot(t, np.sin(t))
# plt.show()
#
# from IPython.display import Latex
# Latex('''The mass-energy equivalence is described by the famous equation
#
# $$E=mc^2$$
#
# discovered in 1905 by Albert Einstein.
# In natural units ($c$ = 1), the formula expresses the identity
#
# \\begin{equation}
# E=m
# \\end{equation}''')
|
91fe757fe0b7980dc5cc820f64172fdb000c4119 | Saswati08/Data-Structures-and-Algorithms | /Trees/leaves_to_DLL.py | 1,537 | 3.84375 | 4 | class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def convDLL(root):
if root == None:
return
elif root.left == None and root.right == None:
root.right = convDLL.hd
if convDLL.hd != None:
convDLL.hd.left = root
convDLL.hd = root
return None
root.right = convDLL(root.right)
root.left = convDLL(root.left)
return root
def convertToDLL(root):
#return the head of the DLL and remove those node from the tree as well.
convDLL.hd = None
root = convDLL(root)
return convDLL.hd
def printInorder(root):
if root is not None:
printInorder(root.left)
print root.data,
printInorder(root.right)
def printList(head):
while(head):
if head.data is not None:
print head.data,
head = head.right
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
root.left.left.left = Node(7)
root.left.left.right = Node(8)
root.right.right.left = Node(9)
root.right.right.right = Node(10)
print "Inorder traversal of given tree is:"
printInorder(root)
root = extractLeafList(root)
print "\nExtract Double Linked List is:"
printList(convertToDLL.head)
print "\nInorder traversal of modified tree is:"
printInorder(root)
|
04384c0addb3f96c5c0794cea200a1bbcc135bf6 | Psychotechnopath/timeit | /timeitchallenge.py | 1,190 | 4.59375 | 5 | # In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number of iterations to 1,000 or 10,000. The default
# of one million will take a long time to run.
import timeit
def fact(n):
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result
def factorial(n):
# n! can also be defined as n * (n-1)!
if n <= 1:
return 1
else:
return n * factorial(n - 1)
if __name__ == "__main__":
print(timeit.timeit("x=fact(130)", setup="from __main__ import fact", number=10000))
print(timeit.timeit("x=factorial(130)", setup="from __main__ import factorial", number=10000))
print(timeit.repeat("x=fact(130)", setup="from __main__ import fact", number=10000)) #Timeit repeat repeats timeit test 3 times and returns result in a list.
print(timeit.repeat("x=factorial(130)", setup="from __main__ import factorial", number=10000)) |
d2c3fa601d2de8ddb377c69c20ea7a9a9cf508f1 | franklingu/leetcode-solutions | /questions/find-if-path-exists-in-graph/Solution.py | 2,044 | 4.09375 | 4 | """
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source to vertex destination.
Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
Explanation: There are two paths from vertex 0 to vertex 2:
- 0 → 1 → 2
- 0 → 2
Example 2:
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
Explanation: There is no path from vertex 0 to vertex 5.
Constraints:
1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
There are no duplicate edges.
There are no self edges.
"""
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
def build_graph(n, edges):
graph = [set() for _ in range(n)]
for edge in edges:
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
return graph
def has_path(graph, src, dest):
stk = [src]
visited = set()
while stk:
curr = stk.pop()
if curr == dest:
return True
if curr in visited:
continue
visited.add(curr)
for ne in graph[curr]:
stk.append(ne)
return False
graph = build_graph(n, edges)
return has_path(graph, source, destination) |
70652b567c13f74a6aba2944b421fe213b7926c7 | dataholicguy/how-to-think-like-a-cs | /chap08/ex04.py | 431 | 4.28125 | 4 | def count_letters(strng, letter):
""" return the number of a character in a string. """
count = 0
start = 0
while start < len(strng):
if strng.find(letter, start) != -1:
count += 1
start = strng.find(letter, start) + 1
else:
start += 1
return count
print(count_letters("banana", "a"))
print(count_letters("banana", "b"))
print(count_letters("banana", "na"))
|
485197a8519d157d53f03fcbcb6d08440fbe1a93 | RibhuProPower/python_classes | /week_04/hw1.py | 141 | 4.1875 | 4 | n = int(input("enter a number"))
if ((n%2) == 0) :
print (str(n)+" is divisible by 2")
else :
print(str(n) + " isn't divisible by 2") |
631944dfacfd30cae33471f2909d6cd03be271bf | ddsha441981/Python-Sample-Code | /chapter_04_Lists_Tuples/practice_04/practice_02.py | 602 | 3.796875 | 4 | # Author: Deendayal Kumawat
""" Date: 11/12/19
Descriptions: List And Tuples """
# List is a just like container which store set of value of any data type
# Create a list using []
print("*********List and Tupples*********")
std1 = input("Enter marks of student 1 \n")
std2 = input("Enter marks of student 2 \n")
std3 = input("Enter marks of student 3 \n")
std4 = input("Enter marks of student 4 \n")
std5 = input("Enter marks of student 5 \n")
std6 = input("Enter marks of student 6 \n")
print("*******After Sorting Student Marks*********")
stdList = [std1,std2,std3,std4,std5,std6]
stdList.sort()
print(stdList) |
32c7a56faa4532ef3a808c25c0cdfd73947f00e6 | ryoman81/Leetcode-challenge | /LeetCode Pattern/8. LinkedList/234_easy_palindrome_linked_list.py | 1,540 | 4 | 4 | '''
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
'''
# Import helper class ListNode in this folder
# It is the same as LeetCode one with additional methods show() and create()
from ListNode import ListNode
class Solution:
'''
MY CODE VERSION
Thought:
The first idea came up was using stack for the most palindrome questions
- First pass through list to push the value to a stack
- Second pass through list to pop stack from top
Finally the stack should be empty
Iteration:
This method requires a stack in O(n). If follow up, we cannot use stack to store information
One possible way is to reverse the second half of list
And use two pointers to check. I won't present this method here since 实际应用这样之太无聊了吧 代码又繁琐
Complexity:
Time: O(n)
Space: O(n)
'''
def isPalindrome(self, head: ListNode) -> bool:
crr = head
stack = []
# first pass to record list value in a stack
while crr:
stack.append(crr.val)
crr = crr.next
# second pass to check list with the top of stack
crr = head
while crr:
if crr.val == stack[-1]:
stack.pop()
crr = crr.next
else:
return False
return True
## Run code after defining input and solver
input = ListNode().create([1,2,2,3,3,2,2,1])
solver = Solution().isPalindrome
print(solver(input)) |
9dfe4469688c6a636a0801bef87e898825a3242c | fangzli/Leetcode | /src/RecursiveFibonacci.py | 1,602 | 4.40625 | 4 | # Method 1: recursive, slow, no memory of previously calculated value
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# print(fib(5))
# Method 2: iterative
def fibi(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
# Method 3: recursive, fast, has memory of prev calc value
memo = {0:0, 1:1}
def fibm(n):
if not n in memo:
memo[n] = fibm(n-1) + fibm(n-2)
return memo[n]
# print(fibm(5))
# 1. Think of a recursive version of the function f(n) = 3 * n, i.e. the multiples of 3
def mul3(n):
if n == 1:
return 3
else:
return 3 + mul3(n-1)
# print mul3(3)
# 2. Write a recursive Python function that returns the sum of the first n integers.
# (Hint: The function will be similiar to the factorial function!)
def sumn(n):
if n == 0:
return 0
else:
return n + sumn(n-1)
# print sumn(6)
# 3. Write a function which implements the Pascal's triangle:
# 1
# 1 1
# 1 2 1
# 1 3 3 1
# 1 4 6 4 1
# 1 5 10 10 5 1
def pascal(n):
if n == 1:
return [1]
else:
line = [1]
pre_line = pascal(n-1)
for i in range(len(pre_line) - 1):
line.append(pre_line[i] + pre_line[i+1])
line.append(1)
return line
#print pascal(6)
# 4. You find further exercises on our Python3 version of recursive functions,
# e.g. creating the Fibonacci numbers out of Pascal's triangle or produce
# the prime numbers recursively, using the Sieve of Eratosthenes.
|
97048cf96b8646be37ebc8df972cf0df6040434e | Jonathan-Nuno/Assignments | /week_1/d1-a2.py | 192 | 4.4375 | 4 | ### Assignment 2 - Even Odd
print("Is your number even or odd?")
num = int(input("Please enter your number: "))
if (num % 2) == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd") |
17958210b05b01a4dcca948fc9193bbea88fb35c | lrana-227/RBootCamp | /cw/0-3Python/7/08-Stu_RockPaperScissors/Unsolved/RPS_Unsolved.py | 1,520 | 4.40625 | 4 | # Incorporate the random library
import random
# Print Title
print("Let's Play Rock Paper Scissors! There are three trys!")
# Specify the three options
options = ["r", "p", "s"]
# Computer Selection
for x in range(3):
computer_choice = random.choice(options)
# User Selection
user_choice = input("Make your Choice: (r)ock, (p)aper, (s)cissors? ")
print(f"The computer chose {computer_choice}")
computer_wins = 0
you_wins = 0
# Run Conditionals
if ((user_choice == "r" and computer_choice == "p") or (user_choice == "p" and computer_choice == "s") or (user_choice == "s" and computer_choice == "r")):
print("The computer won this round")
computer_wins=computer_wins+1
elif ((user_choice == "r" and computer_choice == "s") or (user_choice == "p" and computer_choice == "r") or (user_choice == "s" and computer_choice == "p") ):
print("You won this round!")
you_wins=you_wins+1
elif ((user_choice == "s" and computer_choice == "s")or (user_choice == "s" and computer_choice == "s") or (user_choice == "s" and computer_choice == "s")):
print("You and the computer picked the same value. No one gets points")
else:
print("You entered an invalid option")
print("You both gain no points and loose a turn")
if computer_wins>you_wins:
print("The computer won :(")
elif computer_wins<you_wins:
print("YOU WON!!! YAY!!! :)")
else:
print("You both tied in points---- you both can't type or can read each others mind!") |
8ec5896d68b345602822883958da1dcc5c4da926 | moamen-ahmed-93/hackerrank_sol | /python3/re-group-groups.py | 155 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import re
r = re.search(r'([a-zA-Z0-9])\1+',input())
print(r.group(1) if r else -1)
|
48fc5c88c16d5fec9bfe5c7382c0a650879c166d | Caioseal/Python | /Aulas/aula16a.py | 551 | 3.96875 | 4 | #Variaveis compostas no Python: Tuplas, Listas e Dicionários
#Tupla = variável que cabem 4 valores. Até agora, variável só recebia 1 valor.
#Tuplas são imutáveis
# lanche = [hamburguer, suco, pizza, pudim]
#print(lanche[2]) - pizza
#print(lanche[0:2]) - hamburguer e suco - o fatiamento exclui o último
#print(lanche[1:]) - suco, pizza e pudim
#print(lanche[-1]) - pudim (último)
#len(lanche) = 4
#for c in lanche: - Vai criar uma variável simples com o nome 'C'
# print(c) - Vai mostrar cada elemento dentro da varíavel lanche. |
aa4bc52016ad5fdc4b4350ccbcd981b2018e2917 | techkang/wordCloudZn | /deleteSingleWord.py | 1,441 | 4.0625 | 4 | # -*- coding:utf-8 -*-
'''
This python file is used to delete auxiliary words in freq.txt.
'''
class DeleteSingleWord():
def __init__(self, srcfile='src.txt', desfile='notionFreq.txt', cutlen=50, enconding='utf-8'):
self.srcfile = srcfile
self.desfile = desfile
self.cutlen = cutlen
self.encoding = enconding
def deleteSingleWord(self):
with open(self.srcfile, 'r', encoding=self.encoding) as src:
line = src.readline().split()
i = 0
output = ''
while line != []:
i += 1
# print(line)
if len(line[0]) == 1 and i < self.cutlen:
line = src.readline().split()
continue
output += str(line[0]) + ' ' + str(line[1]) + '\n'
line = src.readline().split()
with open(self.desfile, 'w',encoding='utf-8') as des:
des.write(output)
if __name__ == "__main__":
testClass = DeleteSingleWord(srcfile='freq.txt')
testClass.deleteSingleWord()
with open(testClass.srcfile, 'r', encoding=testClass.encoding) as src:
print('source file:')
srctext = src.read(300)
print(srctext)
pass
with open(testClass.desfile, 'r') as des:
print('\ndestination file:')
destext = des.read(300)
print(destext)
pass
|
a6b4490784f51efcdffe80bd02764e20b16af249 | lilsweetcaligula/sandbox-codewars | /solutions/python/209.py | 293 | 3.59375 | 4 | def two_sum(values, result):
from collections import OrderedDict
lookup = OrderedDict({ value: index for index, value in enumerate(values) })
for index, x in enumerate(values):
y = result - x
if y in lookup:
return [index, lookup[y]]
return [-1, -1] |
a9e161b6d590f8bfc9694e8ba9bded44c881f142 | JeromeLefebvre/ProjectEuler | /Python/Problem058.py | 1,297 | 3.5 | 4 |
'''
Problem 58
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?
'''
from itertools import count
from pe.primes import isPrime
def problem58():
primes = 0
for shell in count(1):
# We only need to check the 4 cornes and there is an easy formula to
# generate all of them
primes += sum(1 for i in range(1, 4)
if isPrime((2 * shell + 1) ** 2 - 2 * i * shell))
if primes / (4 * shell + 1) < 0.10:
return 2 * shell + 1
if __name__ == "__main__":
print(problem58() == 26241)
from cProfile import run
run("problem58()")
|
18bbb23d04c94705145c4ac20b0966a016c007ea | lxr0804/pythonProject | /条件语句/列表推导式.py | 241 | 3.5625 | 4 | girls = ['alice', 'elena', 'crelin']
boys = ['alark', 'ckjjfa', 'eamon']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print letterGirls
print [b + "+" + g for b in boys for g in letterGirls[b[0]]]
|
4c5acd7a9505090b8a92aae3cbb6abe64d9a55f2 | renanstn/exercicios-uri-online-judge | /1143.py | 231 | 3.515625 | 4 | # Exercicio referente ao problema numero 1143 do URI ONLINE JUDGE.
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1143
# Por: Renan Santana Desiderio
n=input()
for i in range(n+1):
if i!=0:
print "%i %i %i" %(i, i**2, i**3) |
742add3de321d0b9be299faee3106625504ae7c3 | sarahkorb/PythonProjects | /Lab3_Dartmouth_Map/load_graph.py | 2,492 | 4 | 4 | #CHECKPOINT
#function to load the data and create a graph data structure and a dictionary of vertices
#Author: Sarah Korb
#Oct. 31 2018
#Professor Cormen- CS1
from vertex import *
def load_graph (file):
vertex_dict = {} #create a dictionary
in_file = open(file, "r")
for line in in_file: #read through lines of file. strip and split at ";" to split line up into 3 pieces we can index into
line = line.strip()
line = line.split((";"))
name = line[0] #the first section is the name
coordinates = line[2].split(",") #we split the last section again so we can index into it and get the x and y coordinates separately
x_co = int(coordinates[0])
y_co = int(coordinates[1])
vertex_dict[name] = Vertex(name,x_co,y_co) #create a vertex object with these parts as the parameters. This is done for every line- so every location in the text file is anow a reference to a vertex object
in_file.close() #close this file
second_time = open(file, "r") #open the file a second time
for line in second_time: #repeat what we diod before- split each line into 3 parts to index into
line = line.strip()
line = line.split((";"))
name = line[0] #save the first section of each line to the variable 'name'
adjacent = line[1].split(",") #turn the second section of each line into a list by indexing into it and splitting it again by each ','
for vertex in adjacent: #iterate through this list, and strip each name of whitespace
vertex = vertex.strip()
vertex_dict[name].append(vertex_dict[vertex]) #as every name has already been made into a reference to an object in the dictionary, use this list of strings as keys to go into the dictionary
#then append these OBJECTS to the original vertex which we access using 'name' as the key
second_time.close() #REMEMBER: the append method was written in the vertex class and specifically appends to the object's adj_list!
#close the file and return a reference to the dictionary
return vertex_dict
|
dd1a193019ef68796bd5f024784fa6c597ebd9f5 | shivanikarnwal/Python-Programming-Essentials-Rice-University | /week3/comparisons.py | 628 | 4.0625 | 4 | """
Demonstration of arithmetic comparisons
"""
# Six different arithmetic comparison operators
print("Comparisons")
print("===========")
print(7 > 3)
print(7 < 3)
print(7 >= 3)
print(7 <= 3)
print(7 == 3)
print(7 != 3)
print("")
# Using comparisons to get a boolean value
print("Comparing Variables")
print("===================")
num1 = 7.3
num2 = 8.6
greater = num1 > num2
print(greater)
print("")
# == and != are also useful for non-numeric types
print("Comparing Strings")
print("=================")
name = 'Scott'
# Beware of = and == confusion!
equal = name != "Joe"
print(equal)
|
4e825688a2d20922739b7a681e2262049cc53831 | jasmintey/pythonLab6 | /hello.py | 1,660 | 3.90625 | 4 | """
a=10
b=12
print('a > b is', a>b)
a = True
b = False
print('Combine result of a and b is', a and b)
a = [1,2,3]
b = [1,2,3]
c = b
print(a is b)
print(c is b)
import math
print(math.pi)
x = "python" + " exercise"
str.title(x)
print(x)
mark1 = float(input("Please enter mark "))
mark2 = float(input("Please enter mark "))
mark3 = float(input("Please enter mark "))
mark4 = float(input("Please enter mark "))
mark5 = float(input("Please enter mark "))
markList = [mark1, mark2, mark3, mark4, mark5]
print('The mark list is %s' %(markList))
totalmark = sum(markList)
print('Total mark is %s' %(totalmark))
itemsInTheList = len(markList)
averagemark = round(totalmark / itemsInTheList,2)
print('The average mark is %s' %(averagemark))
n = int(input('enter n '))
counter=1
base=2
value=1
while counter <= n:
value = base * value
counter += 1
print(value)
counter=1
n=10
n1=0
n2=1
while counter <= n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
counter += 1
n = int(input('enter n '))
counter = 1
while counter <= n:
print(counter)
counter += 1
"""
failedStudents = []
passedStudents = []
readFile = open ("ExamResult.txt","r")
scoresCount = 0
names = []
scores = []
for split in readFile:
name, score = split.split()
names.append(name)
scores.append(int(score))
while scoresCount < len(scores):
if scores[scoresCount] < 50:
failedStudents.append(name)
failedStudents.append(score)
elif scores[scoresCount] > 51:
passedStudents.append(name)
passedStudents.append(score)
scoresCount += 1
print(failedStudents, passedStudents)
|
cf235ec047ded3018968233914a6d5e4b3cea404 | ivy2350442/Leetcode_challenge | /876_Middle_of_the_Linked_List.py | 487 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
s, f = head, head
while f.next != None:
s = s.next
f = f.next.next
if f == None:
return s
return s
|
1c52cabacf6958d664ea9d4803faa7109f4ce2ea | Ynjxsjmh/PracticeMakesPerfect | /LeetCode/p0239/I/sliding-window-maximum.py | 2,175 | 3.875 | 4 | # -*- coding: utf-8 -*-
# ********************************************************************************
# Copyright © 2022 Ynjxsjmh
# File Name: sliding-window-maximum.py
# Author: Ynjxsjmh
# Email: [email protected]
# Created: 2022-06-28 10:03:33
# Last Updated:
# By: Ynjxsjmh
# Description: You are given an array of integers `nums`, there is a
# sliding window of size `k` which is moving from the very left of the
# array to the very right. You can only see the `k` numbers in the
# window. Each time the sliding window moves right by one position.
#
# Return *the max sliding window*.
#
# Example 1:
# Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
# Output: [3,3,5,5,6,7]
# Explanation:
# Window position Max
# --------------- -----
# [1 3 -1] -3 5 3 6 7 3
# 1 [3 -1 -3] 5 3 6 7 3
# 1 3 [-1 -3 5] 3 6 7 5
# 1 3 -1 [-3 5 3] 6 7 5
# 1 3 -1 -3 [5 3 6] 7 6
# 1 3 -1 -3 5 [3 6 7] 7
#
# Example 2:
# Input: nums = [1], k = 1
# Output: [1]
#
# Constraints:
# * `1 <= nums.length <= 105`
# * `-104 <= nums[i] <= 104`
# * `1 <= k <= nums.length`
# ********************************************************************************
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""使用大根堆记录滑动窗口内 k 个数和索引,
因此根节点就是窗口内的最大数和其索引。
每次窗口右移时,当新数加进堆中,
1. 新数是最大的,直接取堆顶
2. 新数不是最大的,比较堆顶索引是否在当前
滑动窗口内,不是的话弹出,直到堆顶索引
在滑动窗口内。此时堆顶为窗口内最大值。
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
heap = [(-nums[i], i) for i in range(k)]
heapq.heapify(heap)
max_nums = [-heap[0][0]]
for i in range(k, len(nums)):
heapq.heappush(heap, (-nums[i], i))
while heap[0][1] <= i-k:
heapq.heappop(heap)
max_nums.append(-heap[0][0])
return max_nums
|
91d63545f1869326d26d904eea4f84234fba3524 | Giby666566/programacioncursos | /integralpolinomio.py | 626 | 3.921875 | 4 | #Pedimos los limites de nuestra integral a y b
a=int(input("Dame el limite inferior de la integral\n"))
b=int(input("Dame el limite superior de la integral\n"))
#Calculamos b-a porque es la evaluacion de x de la integral definida de un polinomio de grado n
grado=0
integral=0
coeficiente=0
#Hacemos un ciclo mientras el input que me den sea diferente de un espacio
while coeficiente!=" ":
coeficiente=input(f"Dame el coeficiente de x a la {grado}\n")
if coeficiente!=" ":
grado=grado+1
integral=integral+(float(coeficiente)*(b**grado-a**grado))/grado
print(f"El resultado de la integral es {integral}") |
d9d4a4dce516cb9309e54b4bc987c0ff0587254d | bakcoder/study_deepLearning | /loss_function.py | 1,228 | 3.640625 | 4 | import numpy as np
from study_deepLearning.dataset.mnist import load_mnist
# 평균 제곱 오차
def mean_squared_error(y, t):
return .5 * np.sum((y-t)**2)
# 예1 : '2'일 확률이 가장 높다고 추정
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
y = [.1, .05, .6, .0, .05, .1, .0, .1, .0, .0]
print(mean_squared_error(np.array(y), np.array(t)))
# 예2 : '7'일 확률이 가장 높다고 추정
y = [.1, .05, .1, .0, .05, .1, .0, .6, .0, .0]
print(mean_squared_error(np.array(y), np.array(t)))
# 교차 엔트로피 오차
def cross_entropy_error(y ,t):
delta = 1e-7
return -np.sum(t * np.log(y + delta))
# 미니배치 학습
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
print(x_train.shape) # (60000, 784)
print(t_train.shape) # (60000, 10)
train_size = x_train.shape[0] # 60000
batch_size = 10
batch_mask = np.random.choice(train_size, batch_size)
print(batch_mask)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
def cross_entropy_error_for_batch(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
|
536f1a9799c80113d38b2208b9a0664f87547a96 | kmboese/machine-learning | /k-means-clustering/k_means.py | 3,090 | 4.03125 | 4 | #Program that performs k-means clustering on a set of tuples
from math import sqrt
from collections import defaultdict
import random
centroid_count = 3
#Returns the distance between two 2-value tuples
def distance(p1, p2):
return(sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2))
#Randomly chooses k points from a dictionary dataset to initialize a k-means clustering operation
def initCentroids(k, dataset):
centroids = {} #list of centroids to return
points = [] #list of data points
#Read all the keys into the points list
points = dataset.keys()
#Choose k random points
for i in range(k):
tmp = points[random.randint(0,len(points)-1)]
#don't select duplicate points
if tmp not in centroids:
centroids[tmp] = dataset[tmp]
return centroids
#Choose new centroids based off of the mean of the points within the existing clusters
def genCentroids(clusters):
global centroid_count
new_centroids = {}
for key in clusters.keys():
x_sum = 0
y_sum = 0
for point in clusters[key]:
x_sum += point[1][0]
y_sum += point[1][1]
x_centroid = x_sum / len(clusters[key])
y_centroid = y_sum / len(clusters[key])
new_centroids[centroid_count] = x_centroid, y_centroid
centroid_count += 1
return new_centroids
#Assign a point to a cluster
#Returns: the label of the centroid to which the given point should cluster
def groupPoint(p, centroids):
dist = float('inf')
centroid_label = ""
'''
#don't group centroids with themselves
if (p in centroids.values()):
return
'''
for key in centroids.keys():
if (distance(p, centroids[key]) < dist):
dist = distance(p, centroids[key])
centroid_label = key
return centroid_label, centroids[centroid_label]
#Cluster points around the k clusters based off the distance from the point to each centroid value
#Returns: A list of k clusters of datapoints
def cluster(k, centroids, dataset):
clusters = defaultdict(list) #a list of point clusters
#print("\tDEBUG: number of centroids == {}".format(len(centroids)))
assert len(centroids) == k
for key in dataset.keys():
point = dataset[key]
centroid_group = groupPoint(point, centroids)
if centroid_group is not None:
#Add the point to a cluster based on the centroid label
P = (key, point)
clusters[centroid_group[0]].append(P)
return clusters
#Returns the distance of a point from all centroids to a specified amount of decimal points
def distFromCentroids(point, centroids, decimals):
distances = {}
for centroid_label in centroids.keys():
distances[centroid_label] = round(distance(point, centroids[centroid_label]), decimals)
return distances
#Returns the cluster label for a point
def getClusterLabel(p, clusters):
for label in clusters.keys():
for point in clusters[label]:
if p[0] == point[0]:
return ("C" + str(label))
return ("N/A")
|
a456a46b2cafd639cb2dece778dd12ec8b910e79 | MhmDSmdi/Classical-Search | /SearchAlgorithms/graph/state.py | 599 | 3.59375 | 4 | class State:
def __init__(self, state_name, total_cost, parent_state, action_description, distance):
self.total_cost = total_cost
self.parent_state = parent_state
self.action_desc = action_description
self.state_name = state_name
if distance is not 0:
self.root_distance = distance + 1
else:
self.root_distance = 0
def __str__(self):
return "State {}".format(self.state_name)
def __iter__(self):
return self
def action_list(self):
pass
def equal_state(self, state):
pass
|
90dd0e84d740f28ce82ea483746e9ca079d33377 | jdf/processing.py | /mode/examples/Basics/Image/LoadDisplayImage/LoadDisplayImage.pyde | 570 | 3.671875 | 4 | """
Load and Display
Images can be loaded and displayed to the screen at their actual size
or any other size.
"""
def setup():
size(640, 360)
# The image file must be in the data folder of the current sketch
# to load successfully
global img
img = loadImage("moonwalk.jpg") # Load the image into the program
noLoop()
def draw():
# Displays the image at its actual size at point (0,0)
image(img, 0, 0)
# Displays the image at point (0, height/2) at half of its size
image(img, 0, height / 2, img.width / 2, img.height / 2)
|
3519dc260e65c7d3b23aa3728523149dd9a16deb | Moris-Zhan/Udemy_Course | /Python/Complete Course/Spyder/MatPlotlib/MatPlotLib_Introduce.py | 269 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 9 15:08:13 2017
@author: Leyan
"""
import matplotlib
import matplotlib.pyplot as pt
rotal_x = [1,2,3,4]
rotal_y = [3,8,10,25]
pt.title('figure1')
pt.xlabel('Label_x')
pt.ylabel('Label_y')
pt.plot(rotal_x,rotal_y)
|
648852ebb2e4442d003e3e796bb3133a71b2ec51 | RyujiOdaJP/python_practice | /ryuji.oda19/week02/c30_int_list.py | 243 | 3.578125 | 4 | def int_list(L):
if len(L) == 0:
return False
else:
try:
X = [isinstance(L[i],int) for i in range(len(L))]
print(X)
return all(X)
except TypeError:
return False
|
1d6054781b795d6164e98486f3b23df2d1e4a2d0 | Touchfl0w/python_practices | /advanced_grammer/practice1-10/practice7/p1.py | 584 | 3.671875 | 4 | s = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz'
a = s.split(';')
print(a)
t = []
XXX = 'xxx'
def test(x):
y = x.split(',')
#作为参数的函数与普通函数并无区别,可以访问到全局变量XXX以及t
y.append(XXX)
return t.extend(y)
x = map(test,a)
#打印出t的结果并未改变值,不是因为作为参数的test()不能访问全变量,而是因为Python3中的机制
#执行map()后仅返回map object,并未进行完整的映射计算
print(t)
#对map object 执行list操作,才会依次进行映射计算
print(list(x))
#结果证明了这一点
print(t) |
dcf12d6d45d3555cd2adec8c62d5ece59aa87280 | MarcosQiu/beauty-of-algorithm | /python/binary_tree/tree_traversal.py | 1,193 | 3.75 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def pre_order_traversal(node):
if node is None:
return []
left_subtree_traversal = pre_order_traversal(node.left)
right_subtree_traversal = pre_order_traversal(node.right)
return [node.val] + left_subtree_traversal + right_subtree_traversal
def in_order_traversal(node):
if node is None:
return []
left_subtree_traversal = in_order_traversal(node.left)
right_subtree_traversal = in_order_traversal(node.right)
return left_subtree_traversal + [node.val] + right_subtree_traversal
def post_order_traversal(node):
if node is None:
return []
left_subtree_traversal = post_order_traversal(node.left)
right_subtree_traversal = post_order_traversal(node.right)
return left_subtree_traversal + right_subtree_traversal + [node.val]
def level_traversal(node):
queue = [node]
current_idx = 0
result = list()
while current_idx < len(queue):
current_node = queue[current_idx]
if current_node is not None:
result.append(current_node.val)
queue.append(current_node.left)
queue.append(current_node.right)
current_idx += 1
return result
|
498f5ee8600470f43c7bdadb6179cdb5064e6bba | rajib-nh/demo1 | /calculator.py | 5,101 | 4 | 4 | #!/usr/bin/python
from tkinter import *
import math
from PIL import ImageTk, Image
import os
root = Tk()
root.title("Simple Calculator")
root.resizable(0,0) ## Disable maximize button
## set window icon
root.iconphoto(False, PhotoImage(file='/home/rajib/PYTHON-programme/gui-tkinter/calculator-project/icon-calculator.png'))
#root.geometry("360x370")
e = Entry(root, width=20, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=20, pady=20)
## Create ation of function button_click()
reset = "not equal"
def button_click(number):
global reset
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
if reset == "equal":
e.delete(0, END)
e.insert(0, str(number))
reset = "not equal"
def button_clear():
e.delete(0, END)
def button_add():
first_number = e.get()
if first_number == "":
first_number = 0
global f_num
global math
math = "addition"
f_num = float(first_number)
e.delete(0, END)
def button_subtract():
first_number = e.get()
if first_number == "":
first_number = 0
global f_num
global math
math = "subtract"
f_num = float(first_number)
e.delete(0, END)
def button_multiplication():
first_number = e.get()
if first_number == "":
first_number = 0
global f_num
global math
math = "multiply"
f_num = float(first_number)
e.delete(0, END)
def button_divide():
first_number = e.get()
if first_number == "":
first_number = 0
global f_num
global math
math = "division"
f_num = float(first_number)
e.delete(0, END)
def button_sqroot():
first_number = e.get()
#print(first_number)
if first_number == "":
first_number = 0
e.delete(0, END)
f_num1 = float(first_number)
res = f_num1 ** 0.5
e.insert(0, res)
#first_number = 0
def button_x_power_y():
first_number = e.get()
if first_number == "":
first_number = 0
global f_num
global math
f_num = float(first_number)
e.delete(0, END)
math = "power"
def button_equal():
global reset
reset = "equal"
second_number = e.get()
if second_number == "":
second_number = 0
e.delete(0, END)
if math == "addition":
e.insert(0, f_num + float(second_number))
if math == "subtract":
e.insert(0, f_num - float(second_number))
if math == "multiply":
e.insert(0, f_num * float(second_number))
if math == "division":
e.insert(0, f_num / float(second_number))
if math == "power":
e.insert(0, f_num ** float(second_number))
#Create buttons
button_1 = Button(root, text="1", padx=30, pady=20, command=lambda: button_click(1))
button_2 = Button(root, text="2", padx=30, pady=20, command=lambda: button_click(2))
button_3 = Button(root, text="3", padx=30, pady=20, command=lambda: button_click(3))
button_4 = Button(root, text="4", padx=30, pady=20, command=lambda: button_click(4))
button_5 = Button(root, text="5", padx=30, pady=20, command=lambda: button_click(5))
button_6 = Button(root, text="6", padx=30, pady=20, command=lambda: button_click(6))
button_7 = Button(root, text="7", padx=30, pady=20, command=lambda: button_click(7))
button_8 = Button(root, text="8", padx=30, pady=20, command=lambda: button_click(8))
button_9 = Button(root, text="9", padx=30, pady=20, command=lambda: button_click(9))
button_0 = Button(root, text="0", padx=30, pady=20, command=lambda: button_click(0))
button_point = Button(root, text=".", padx=30, pady=20, command=lambda: button_click("."))
button_sqroot = Button(root, text='\u221A', padx=30, pady=20, command=button_sqroot)
button_clear = Button(root, text="C", padx=20, pady=20, command=button_clear)
button_add = Button(root, text="+", padx=20, pady=20, command=button_add)
button_subtract = Button(root, text="-", padx=20, pady=20, command=button_subtract)
button_multiplication = Button(root, text="x", padx=20, pady=20, command=button_multiplication)
button_divide = Button(root, text="\u00f7", padx=20, pady=20, command=button_divide)
button_equal = Button(root, text="=", padx=20, pady=20, command=button_equal)
button_power = Button(root, text="x\u207f", padx=20, pady=20, command=button_x_power_y)
#button_quit = Button(root, text="Exit", padx=20, pady=20, command=root.quit)
#Put the button on the screen
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_point.grid(row=4, column=1)
button_sqroot.grid(row=4, column=2)
button_add.grid(row=1, column=4)
button_subtract.grid(row=1, column=5)
button_multiplication.grid(row=2, column=4)
button_divide.grid(row=2, column=5)
button_clear.grid(row=3, column=4)
button_equal.grid(row=3, column=5)
button_power.grid(row=4, column=3, columnspan=2)
#button_quit.grid(row=4, column=3, columnspan=3)
root.mainloop()
|
befcb2f45a076b695fac24a3c6bb4b52302285b0 | stanislasveronical/Python | /20170309_Arithméthique/Division successives par 2 (EX 1 et 3).py | 527 | 3.890625 | 4 | #EXERCICE 1
n= int(input("Entrer l'entier à convertir : "))
bin , q = [ ],n
while q//2 !=0:
bin = [q%2] + bin
q = q//2
bin = [q%2] + bin
print("L'écriture binaire de l'entier",n,"est ")
for k in range(len(bin)):
print(bin[k],end=' ')
#EXERCICE 3 : Conversion Inverse
print("\n")
bin , n = input("Entrer l'écriture binaire à convertir : "),0
for k in range(len(bin)):
n = n + int(bin[len(bin)-1-k])* 2**(k)
print("L'entier dont l'écriture binaire est ",bin, "est égal à", n)
|
7a5f3c872aba432bdadbac62a8915ad2f97e5a27 | KohsukeKubota/Atcoder-practice | /the_longest_distance.py | 339 | 3.53125 | 4 | from math import sqrt
N = int(input())
coordinate = [list(map(int, input().split())) for i in range(N)]
res = -1
for i in range(N):
for j in range(N):
a = coordinate[i]
b = coordinate[j]
dist = sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
if res < dist:
res = dist
print('{:.6f}'.format(res))
|
d4673cb5494ea1e07474a9cc8504e2568c4f0c5d | jamilahhh21/PYTHON-PROGRAMS | /fieldarea.py | 311 | 3.84375 | 4 | '''AREA OF FIELD'''
l=float(input('Length of field in feet ='))
w=float(input('Width of field in feet ='))
area=l*w
print('''
Length of field in feet = %f feets
Width of field in feet = %f feets
Area of field in square feets = %f
Area of field in acres = %f
'''
%(l,w,area,area/43560)) |
c59ae0cb01e9e42a2a925f6b44aef08ddf5071ce | KatieStevenson/cp1404practicals | /prac_02/string_formatting_examples.py | 687 | 4.28125 | 4 | #STRING FORMATTING -----------------------------------------------------------------------------------------------------
# TODO (1): Use string formatting to produce the output: "1922 Gibson L-5 CES for about $16,035!". (Notice where the values go and also the float formatting / number of decimal places.)
name = "Gibson L-5 CES"
year = 1922
cost = 16035.4
print("{} {} for about ${:,.2f}!".format(year, name, cost))
# TODO (2): Using a for loop with the range function and string formatting (do not use a list), produce the following output (right-aligned numbers): 0, 50, 100, 150
numbers = [0, 50, 100, 150]
for numbers in numbers:
print("{:>3}".format(numbers))
|
95d35d1a7e9ae503a672b0937e0d8b4f9ec4b368 | EpicAdvt/options | /tests/test_conversion.py | 636 | 3.8125 | 4 | """
http://www.optiontradingpedia.com/conversion_reversal_arbitrage.htm
"""
from options import PutOption, CallOption
from options.conversion import ReverseConversion, Conversion
def test_conversion():
und_price = 51
strike = 51
c = CallOption(strike, bid=2.5, ask=2.5)
p = PutOption(strike, bid=1.50, ask=1.50)
conv = Conversion(p, c)
print(conv.value())
assert conv.value() == 1.0
def test_reverse_conversion():
und_price = 51
strike = 51
c = CallOption(strike, bid=1.5, ask=1.5)
p = PutOption(strike, bid=2.50, ask=2.50)
conv = ReverseConversion(p, c)
print(conv.value())
assert conv.value() == 1.0
|
7871dd9b589f6e4f6981719824d23541fc656b7c | minahosam/python-examples | /92.py | 504 | 4.03125 | 4 | class employee:
empname=[]
empadress=[]
empid=[]
empsalary=[]
def empinfo(mine):
return mine.empname , mine.empadress ,mine.empid,mine.empsalary
def printd(mine):
print(mine.empinfo())
emp=employee()
for i in range(3):
emp.empname.extend(input('enter employe name'))
emp.empadress.extend(input('enter employee address'))
emp.empid.extend(input('enter employee id'))
emp.empsalary.extend(input('enter employ salary'))
emp.printd()
input('p e t e')
|
bfc5d0992415ca326371e1c163674f88d32bafb9 | gengwg/Python | /create_managed_properties.py | 1,095 | 4 | 4 | # add type checking to getting or setting of an instance attribute.
# only works in py3
class Person:
def __init__(self, first_name):
self.first_name = first_name
# getter function
@property
def first_name(self):
return self._first_name
# setter function
@first_name.setter
def first_name(self, val):
if not isinstance(val, str):
raise TypeError('Expected a string')
self._first_name = val
# deleter function (optional)
@first_name.deleter
def first_name(self):
raise AttributeError('Cannot delete attribute')
a = Person('Guido')
print(a.first_name) # calls the getter
a.first_name = 'abc'
print(a.first_name)
# a.first_name = 43 # calls the setter
# del a.first_name
# a = Person(43)
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return math.pi * self.radius ** 2
@property
def perimeter(self):
return 2 * math.pi * self.radius
c = Circle(4.0)
print(c.radius)
print(c.area)
print(c.perimeter)
|
18da5832df489204cc8df1d6e8600d8683b0bf3a | SaidTheCoder/Pr105 | /SD2.py | 789 | 3.890625 | 4 | import csv
import math
with open("data2.csv",newline='') as f:
reader=csv.reader(f)
file_data=list(reader)
data=file_data[0]
#step 1 Finding mean
def mean(data):
n=len(data)
total=0
for x in data :
total+=float(x)
mean= total/n
return mean
#step 2 squaring and getting the values
squared_list=[]
for number in data:
a=float(number)-mean(data)
a=a ** 2
squared_list.append(a)
#step 3 get the sum of all of the squared data
sum=0
for i in squared_list:
sum=sum+i
#step 4 dividing by the sum of the total values
result=sum/(len(data)-1)
#last step find the square root and get the SD
std_deviation=math.sqrt(result)
print("the standard deviation of the givin data is: ",std_deviation) |
b77292d9885301d655573fe56b71079fdfe56e3c | szymon-m/playground | /hackerrank/25-03-2020/nested_functions.py | 882 | 3.765625 | 4 | def get_nested_scores(how_many_scores, name_scores_list):
db = []
[db.append([x[0], x[1]]) for x in name_scores_list]
return db
def sorted_by_score_ascending(how_many_scores, name_scores_list):
db = []
[db.append([x[0], x[1]]) for x in name_scores_list]
db = sorted(db, key=lambda x: x[1], reverse=False)
# or
# from operator import itemgetter ->>> operator lib
# (...)
# db = sorted(db, key=itemgetter(1), reverse=False) # for descending - >> reverse = True
return db
def find_second_lowest_ordered_by_name(given_scores_list):
db = sorted_by_score_ascending(len(given_scores_list), given_scores_list)
new_db = []
[new_db.append(item) for item in db if item[1] == db[1][1]]
new_db = sorted(new_db, key=lambda x: x[0], reverse=False)
if len(new_db) == 1:
return new_db[0]
else:
return new_db
|
67816c8a79b5e822ce1c806967b2e42d5471e71c | BoWarburton/DS-Unit-3-Sprint-2-SQL-and-Databases | /sql/rpg_queries.py | 2,540 | 4.125 | 4 | #!/usr/bin/env Python
import sqlite3
# 1st connect to db
conn = sqlite3.connect('rpg_db.sqlite3')
# 2nd make a cursor
cursor = conn.cursor()
# 3rd execute SQL as Python string
# create_statement = "CREATE TABLE pizza (name varchar(30), size int, pepperoni int, pineapple int);"
# cursor.execute(create_statement)
# insert_statement = "INSERT INTO pizza (name, size, pepperoni, pineapple) VALUES ('ellios', 9, 1, 0);"
# cursor.execute(insert_statement)
# cursor.execute("SELECT * FROM pizza;").fetchall()
# cursor.execute("SELECT count(*) FROM charactercreator_character WHERE character_id >= 100")
# How many total Characters are there?
character_count = "SELECT count(*) FROM charactercreator_character"
print(cursor.execute(character_count)).fetchall()
# How many of each specific subclass?
# count_mages = "SELECT COUNT(*) FROM charactercreator_character, charactercreator_mage WHERE
# SELECT count(*) FROM cleric, fighter, mage, necromancer, thief
# How many total Items?
# SELECT count(*) FROM armory_item
# How many of the Items are weapons? How many are not?
# SELECT count(*) FROM armory_item WHERE join to armory_
# How many Items does each character have? (Return first 20 rows)
# How many Weapons does each character have? (Return first 20 rows)
# On average, how many Items does each Character have?
# On average, how many Weapons does each character have?
#You do not need all the tables - in particular, the account_*, auth_*, django_*, and socialaccount_* tables
#are for the application and do not have the data you need. the charactercreator_* and armory_* tables
#and where you should focus your attention. armory_item and charactercreator_character are the main tables
#for Items and Characters respectively - the other tables are subsets of them by type (i.e. subclasses),
#connected via a key (item_id and character_id).
#You can use the DB Browser or other tools to explore the data and work on your queries if you wish,
#but to complete the assignment you should write a file rpg_queries.py that imports sqlite3
#and programmatically executes and reports results for the above queries.
#Some of these queries are challenging - that's OK!
#You can keep working on them tomorrow as well (we'll visit loading the same data into PostgreSQL).
#It's also OK to figure out the results partially with a query and partially with a bit of logic or math afterwards,
#though doing things purely with SQL is a good goal. Subqueries and aggregation functions may be helpful
#for putting together more complicated queries.
|
eda86af7f573ed46374bd5b998081c781d067be5 | maleckim/machine-learning | /svm-classifier.py | 1,476 | 3.875 | 4 | import pandas as pd
import numpy as np
from sklearn import svm, datasets
import matplotlib.pyplot as plt
# svm or supervised machine learning can be used for both regression and classification the idea behind SVM
# is to plot each data item as a point in n-dimensional space with the value of each feature being the value
# of a particular coordinate
#data
# We will use the iris dataset which contains 3 classes of 50 instances each, where each class refers to a type of iris plant.
# Each instance has the four features namely sepal length, sepal width, petal length and petal width. The SVM classifier to
# predict the class of the iris plant based on 4 features is shown below.
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
#create a mesh to plot
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
h = (x_max / x_min)/100
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
X_plot = np.c_[xx.ravel(), yy.ravel()]
C = 1.0
svc_classifier = svm.SVC(kernel='linear',
C=C, decision_function_shape = 'ovr').fit(X, y)
Z = svc_classifier.predict(X_plot)
Z = Z.reshape(xx.shape)
plt.figure(figsize = (15, 5))
plt.subplot(121)
plt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3)
plt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.title('SVC with linear kernel')
plt.show() |
e1e17d9692b5c60d82086c64a002951dd67ffb91 | MyoMyoCU/Python-Exercises | /ex5.py | 680 | 4.0625 | 4 | #More Variables and Printing
#exercise5 embedded variables in string
my_name = ' Myo Myo '
my_age = 22
my_height = 60 # inches
my_weight = 100 #lbs
my_eyes = 'Brown '
my_teeth = 'White'
my_hair = 'Long Black '
print (f"Let's talk about {my_name}." )
print (f"She's {my_height} inches tall.")
print (f"She's {my_weight} pounds heavy.")
print ("Actually that's not too heavy .")
print (f"She's got {my_eyes} eyes and {my_hair} hair.")
print (f"Her teeth are usually {my_teeth} depending on the coffee . ")
#this line is tricky , try to get it exactly right
total = my_age + my_height + my_weight
print (f"If I add {my_age} , {my_height}, and {my_weight} I get {total}.")
|
1af8668fec45dbb1de80096be570c1eb706b7f88 | PhantomShift/pygame-platformer | /src/instance.py | 3,084 | 3.875 | 4 | from typing import Union
classes = {}
class Instance():
"""
Root class of all parent-child objects
"""
def __init_subclass__(cls, class_name, **kwargs):
super().__init_subclass__(**kwargs)
cls.class_name = class_name
classes[class_name] = cls
def __init__(self, parent=None):
self.name = self.__class__.__name__
self.class_name = self.name
self.children: list[Instance] = []
self.parent = parent
def __getattr__(self, name):
if c := self.find_first_child(name):
return c
if c := object.__getattribute__(self, name):
return c
raise AttributeError(f"Attribute {name} not found in {self}")
def __setattr__(self, name, value):
if name == "parent":
if value and not isinstance(value, Instance):
raise TypeError(f"Non-Instance {value} cannot be a parent to {self}")
if value == self:
raise ValueError("Attempt to set self as own parent")
elif value in self.children:
raise ValueError(f"Attempt to to set child of {self} as parent of itself")
if getattr(self, "parent", False):
self.parent.children.remove(self)
if value:
object.__setattr__(self, "parent", value)
self.parent._add_child(self)
object.__setattr__(self, name, value)
def __repr__(self):
return f"<{self.class_name} {self.name}>"
def __str__(self):
return self.name
def __getitem__(self, key):
if c := self.find_first_child(key):
return c
raise KeyError(f"{key} is not a child of {self}")
def _add_child(self, child):
self.children.append(child)
def find_first_child(self, name, resolve:bool=False):
for child in sorted(self.children, key=lambda c: c.name):
if child.name == name:
return child
return resolve
def get_children(self):
return self.children
def get_descendants(self):
descendants = [child for child in self.children]
for child in self.children:
descendants += child.get_descendants()
return descendants
def get_ancestors(self):
parent = self.parent
ancestors = []
while parent:
ancestors.append(parent)
parent = parent.parent
return ancestors
def get_full_name(self) -> str:
return "".join(ancestor.name + "." for ancestor in reversed(self.get_ancestors())) + self.name
@staticmethod
def new(class_name, parent=None):
return classes[class_name](parent)
if __name__ == "__main__":
Root = Instance()
Root.name = "ROOT"
test = Instance()
test2 = Instance()
test2.parent = test
test.parent = Root
print(Root.__repr__())
print(test.get_children())
print(test2.get_ancestors())
print(test2.get_full_name())
print(Root.get_descendants())
print(Root.get_full_name()) |
a364bac47412c9c2b63ed60b17e1dbe29a4db3fd | surekhaw/jtc_class_code | /class_scripts/bootcamp_scripts/list_practice.py | 1,155 | 4.21875 | 4 | # make a grocery list
# lists have particular order
groceries = ['eggs', 'meat', 'pasta']
print(groceries)
print(type(groceries))
groceries = ['eggs', 'meat' 'pasta']
print(groceries)
# add items to end of list with .append
groceries.append(4.0)
groceries.append('kumquat')
groceries.append('potato')
groceries.append(True)
print(groceries)
# remove items with .remove
# must specify what you want removed
groceries.remove('kumquat')
groceries.remove(4.0)
groceries.remove(True)
# use .len() to get length of list
print(len(groceries))
# list indexing
# zero based
print(groceries[0])
# negative list indexing
# -1 gives last item on list
print(groceries[-1])
#slicing
# indexing multiple items, but not the last one
new_list = groceries[0:2] #gives 0 and 1, but not 2 - up to but not including
print(new_list)
#splitting and joining - list must be strings
grocery_string = ' '.join(groceries) #join items with a space in between into one combined string
print(grocery_string)
grocery_string = 'FOOD'.join(groceries)
print(grocery_string)
my_string = 'carrots, rice, peas, avocados'
my_list = my_string.split('o') # split by 'o's
print(my_list) |
99adba8192a06d528c721560339cab06d52b1cb9 | JoseBieco/Emprestimo-por-RA | /BD/TesteBD.py | 1,152 | 3.5 | 4 | import sqlite3
# Teste Switch lambda
def opcoes(op, conn, cursor):
cases = {
1: lambda: cadastrar(conn, cursor),
2: lambda: listar(cursor),
}
cases.get(op, lambda: print("\nOpção inválida!\n"))()
def menuOpcoes():
print("\t--- Menu ---")
print("1 - Cadastrar")
print("2 - Listar")
print("0 - Sair")
print(">> ", end="")
def cadastrar(conn, cursor):
print("\t --- Cadastro ---\n")
def listar(cursor):
print("\t --- Listar ---")
cursor.execute("""
SELECT
A.RA, A.Nome, C.Nome
FROM
Aluno AS A INNER JOIN Curso AS C
ON A.IDCurso = C.IDCurso
""")
for linha in cursor.fetchall():
print("\nRA: " + linha[0])
print("Nome: " + linha[1])
print("Curso: " + linha[2])
print("\n")
# Connection
conn = sqlite3.connect("Faculdade.db")
# Defining Cursor
cursor = conn.cursor()
# Main -> Teste de Inserção no Banco
continuar = True
while continuar:
menuOpcoes()
op = int(input())
if op == 0:
continuar = False
continue
opcoes(op, conn, cursor)
conn.close() |
e273ddd854f5170c592d25abee145b90c799a713 | Lucas-HMSC/curso-python3 | /#083 - Validando expressões matemáticas.py | 416 | 4.03125 | 4 | expressao = list()
contA = contB = 0
conta = False
expressao.append(input('Digite uma expressão matemática: '))
for letra in expressao:
for l in letra:
if l in '+-*/':
conta = True
elif l in '(':
contA += 1
elif l in ')':
contB += 1
if contA == contB and conta:
print('A expressão é válida.')
else:
print('A expressão não é válida.')
|
0fb7e07da968ef830f3d88d3a195b53f4cee7ee8 | pedrovs16/PythonEx | /ex073.py | 409 | 3.828125 | 4 | tabela = ('Flamengo', 'Cruzeiro', 'Figueirense', 'Chapecoense', 'Fluminense', 'Avai', 'Santos', 'Bragantino', 'Gremio')
print(f'A ordem na tabela é {tabela}.')
print(f'A tabela em ordem alfabética é {sorted(tabela)}.' )
print(f'Os primerios 5 times da tabela são {tabela[:5]}.')
print(f'Os ultimos 4 times da tabela são {tabela[5:]}.')
print(f'A posição da Chape é {tabela.index("Chapecoense") + 1}') |
c9a528a238df192a7ef416fa03e6421c53a50316 | Mahay316/Python-Assignment | /Exercise/0325/copy_file.py | 486 | 3.84375 | 4 | # 练习:将一个文件夹下的文件复制到另一个文件夹中
import os
# 该函数将覆盖dst目录下的已有同名文件
def copy(src, dst):
fileList = os.listdir(src)
for f in fileList:
sf = os.path.join(src, f)
df = os.path.join(dst, f)
if os.path.isfile(sf):
with open(sf, 'rb') as f1, open(df, 'wb') as f2:
for line in f1:
f2.write(line)
os.chdir('Exercise/0325')
copy('src', 'dst')
|
2877198745a30538c7cb0464e3c38b1e8131f717 | mocusez/XUTPracticals | /prac_01/Sequences.py | 1,189 | 3.96875 | 4 | MENU = """E - Show the even numbers from x to y
O - Show the odd numbers from x to y
S - Show the squares from x to y
Q - Quit"""
print(MENU)
choice = input(">>> ").upper()
while choice != "Q":
if choice == "E":
print("Input the number X and Y")
x, y = input().split()
x = int(x)
y = int(y)
# print even
if x%2 == 0:
for i in range(x,y,2):
print(i,end=' ')
if(y % 2 == 0):
print(y)
else:
x = x+1
for i in range(x, y, 2):
print(i,end=' ')
if (y % 2 != 0):
print(y)
elif choice == "O":
print("Input the number X and Y")
x, y = input().split()
x = int(x)
y = int(y)
# print Odd
if x%2 != 0:
for i in range(x,y,2):
print(i,end=' ')
if(y % 2 == 0):
print(y)
else:
x = x+1
for i in range(x, y, 2):
print(i,end=' ')
if (y % 2 != 0):
print(y)
elif choice == "S":
for i in range(x, y, 1):
print(i**0.5) |
56860e37d3e49356d240ec68504c6fc08aae388c | gittenberg/rosalind | /Rabbits and Recurrence Relations.py | 179 | 3.578125 | 4 | def LinearFibonacci(n, k):
fn = f1 = f2 = 1
for x in range(2, n):
fn = f1 + k * f2
f2, f1 = f1, fn
return fn
n = 31
k = 4
print(LinearFibonacci(n, k)) |
c5b204d597874106e91b508d7e4518b7a39b6c17 | sameer-h/ENGR102 | /Lab04bMathPractice.py | 1,060 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 17:59:59 2019
By submitting this assignment , I agree to the following :
"Aggies do not lie , cheat , or steal , or tolerate those who do ."
"I have not given or received any unauthorized aid on this assignment ."
Names: Sameer Hussain
ENGR 102 - 214
Professor: Dr.Socolofsky
Assignment: Lab 02b
Date: 09/22/2019
[email protected]
Script: Labo04bMathPractice.py
Individual Lab
Generating a random number between 1 and 20 and doing subtraction problem, making sure that the difference is always positive.
"""
from random import *
#Pre Processor
def math_practice():
a = randint(1,20)
b = randint(1,20)
#While loop
while a - b < 0:
a = randint(1,20)
b = randint(1,20)
#User answer
userans = int(input("Enter your guess for the problem " + str(a) + " - " + str(b) + " = "))
if userans == (a - b):
print("You are correct!")
else:wha
print("That is incorrect! The correct answer is " + str(a-b))
#Post processor
math_practice()
|
43c16f5ed756e175104f128b276762c76012fba7 | Mannuel25/ROCK_PAPER_SCISSORS_GAME_VERSION_2.0 | /get_player_username.py | 1,832 | 4 | 4 | import string
from number_of_players import numberOfPlayers
def PlayerUsername(serverRooms):
"""
Gets each player's username
:return : None
"""
no_of_players = numberOfPlayers()
print('\nEnter a valid username that conforms to the following rules:')
print('\t+ Minimum length is 5')
print('\t+ Maximum length is 10')
print('\t+ Should contain at least a number')
print('\t+ Should contain at least a special character (such as $,_,+,-,!,*,^,&,@,#,etc)')
print('\t+ Should contain at least a lowercase or a uppercase letter')
print('\t+ Should not contain space(s)')
for i in range(1, no_of_players + 1):
player_username = input(F'\nPlayer {i}, enter a valid username: ')
player_username = player_username.strip()
while not(5 <= len(player_username) <= 10):
print('Invalid username!')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
while ' ' in player_username:
print('Invalid username!')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
while not any(i in string.punctuation for i in player_username):
print('Invalid username!')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
while not any(i in string.digits for i in player_username):
print('Invalid username!')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
while not any(i in string.ascii_letters for i in player_username):
print('Invalid username!')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
while player_username in serverRooms:
print('oops..username has been taken')
player_username = input(F'\nPlayer {i}, enter a valid username: ')
else:
print('Valid username..your username has been saved!')
serverRooms[player_username] = 0 #initial player score is zero |
95f9790babefb0f88534d199b0bd4757d8a42f11 | pratian-pyclub/task-1-c | /word_magic.py | 1,343 | 3.890625 | 4 | import re
WILDCARD = '?'
WILDCARD_PATTERN = '\\' + WILDCARD
class WordMagic():
def __init__(self, tile, word):
"""Initialize WordMagic object with tile and word values"""
self.tile = tile
self.word = word
def can_create(self):
"""Return a boolean value if given tile can create the word or not"""
# If length of word is greater than the tile,
# word can never be formed
if len(self.word) > len(self.tile):
return False
tile = self.tile
for letter in self.word:
# At each pass remove the matched letter,
# else regex will match for repeating letters
# Eg, without removal a tile with a single 'e'
# will return True for a word with double 'e'
if re.search(letter, tile) is not None:
tile = tile.replace(letter, "")
elif re.search(WILDCARD_PATTERN, tile) is not None:
tile = tile.replace(WILDCARD, "")
else:
# If neither of the conditions match,
# function can return False immediately
# This prevents logic running for the length of the word
# when a letter at the beginning itself did not match
return False
return True
|
5f83fdd764f87cccec506c22cfe6afcc97cab0f5 | Nihilnia/100daysOfCodePy | /fibonacci Sequence.py | 473 | 4.1875 | 4 | #Fibonacci Sequence
# 1,1,2,3,5,8,13,...
# an example with 1 t0 20
fibonacciList = [0, 1]
key = 0
actualResult = 1
print(actualResult)
for f in range(1, 21):
actualResult = fibonacciList[key] + fibonacciList[key + 1]
print(actualResult)
fibonacciList.append(actualResult)
key += 1
# other short way
x = 1
y = 1
fibonnaciList = [x, y]
for f in range(21):
x, y = y, x + y
fibonnaciList.append(y)
print(fibonnaciList) |
d7db6fadcceb8694a6ac88e09d4ecba961147c4d | henrywallawalla/word_games | /word_games.py | 440 | 3.6875 | 4 | """
with open("scrabble.txt", 'r') as f:
count = 0
for line in f:
if count > 5:
break
print(line)
count += 1
"""
def value(word):
my_dict = {'a':1,"b":3,"c":3,"d":2,'e':1,'f':4,'g':2,'h':4,'i':1,'j':8 ,'k':5,'l':1,'m':3,'n':1,'o':1,'p':3,'q':10,'r':1,'s':1,'t': 1,'u':1,'v':4,'w':4,'x':8,'y':4,'z':10}
value = 0
for character in word:
value += my_dict[character]
print(character)
print(my_dict[character])
print(value) |
e062601d80137d8915866b18dd92e6a6f5097e67 | zosopick/mathwithpython1 | /Excersises/Chapter 7/3. Area Between Two Curves.py | 1,358 | 4.28125 | 4 | '''
Your challenge is to write a program that will allow the user to input any two single-variable
functions of x and print the enclosed area between the two. The program should make it clear that
the first function entered should be the upper function and it should also asl for the values of
x between which to find the area
'''
from sympy import Symbol, Integral, sympify
from sympy.core import SympifyError
def integrator(ftop,fbot,start,final):
x=Symbol('x')
f=ftop-fbot
area=Integral(f,(x,start,final)).doit()
return area
if __name__=='__main__':
ftop=input('Please enter the single-variable function in terms of x which is above: ')
fbot=input('Please enter the single-variable function in terms of x which is below: ')
start=float(input('Please enter the left bound of the integral: '))
final=float(input('Please enter the right bound of the integral: '))
try:
ftop=sympify(ftop)
fbot=sympify(fbot)
except SympifyError:
print('At least one of the functions entered was invalid! Please run the program anew and enter a proper function!')
else:
area=integrator(ftop,fbot,start,final)
print('The area between {0} and {1}, between the values {2} and {3} is {4}.'.format(ftop,fbot,start,final,area))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.