blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
71e8650f93dc843738c3ee2dc8312bdfe38b75a6 | gregspurrier/pymazing | /pymazing/square_board.py | 1,341 | 3.703125 | 4 | from pymazing.board import Board
class SquareBoard(Board):
"""A Board with square tiles."""
# Offsets to neighboring tiles indexed by movement direction.
_offsets = {
'n': (-1, 0),
'w': (0, -1),
'e': (0, 1),
's': (1, 0)
}
_inverted_dirs = {
'n': 's',
'w': 'e',
'e': 'w',
's': 'n'
}
def fill(self, num_rows, num_cols):
for r in range(num_rows):
for c in range(num_cols):
self.tiles.add((r, c))
def paint_tile(self, tile, scr):
r, c = tile
x = c * 3
y = r * 2
scr.addch(y, x, '+')
scr.addch(y, x + 3, '+')
scr.addch(y + 2, x, '+')
scr.addch(y + 2, x + 3, '+')
if 'n' not in self.tile_exits[tile]:
scr.addstr(y, x + 1, '--')
if 'w' not in self.tile_exits[tile]:
scr.addch(y + 1, x, '|')
if 'e' not in self.tile_exits[tile]:
scr.addch(y + 1, x + 3, '|')
if 's' not in self.tile_exits[tile]:
scr.addstr(y + 2, x + 1, '--')
@staticmethod
def board_size(max_y, max_x):
"""Return the maximum board size as (rows, columns) for the given
screen size.
"""
rows = (max_y - 1) // 2
cols = (max_x - 1) // 3
return rows, cols
|
b22eb11b7a49f18bde25011480a5d76c54c77a3f | DavidC117/David_Castillo_1560 | /Arrays_parte2.py | 1,056 | 3.625 | 4 | class Array:
def __init__(self, size):
self.__size = size
self.__data= []
for index in range(size):
self.__data.append(None)
def length( self ):
return self.__size
def get_item( self, index):
if index >=0 and index < self.__size:
return self.__data[index]
else:
return None #Index no valido
def set_item( self, index, valor):
if index >=0 and index < self.__size:
self.__data[index] = valor
else:
print("index fuera de rango")
def clearing( self, valor ):
for i in range(self.__size):
self.__data[i]= valor
def to_string( self ):
print(self.__data)
def main():
adt = Array( 10 )
adt.to_string()
print(f"El tamaño del arreglo es {adt.length()}")
adt.set_item(4,34)
adt.to_string()
print(f"El elemento 4 es { adt.get_item( 4 )}")
adt.clearing(0)
adt.to_string()
adt.set_item(11,15)
main()
|
1fd674f4224c7caddf88f34b8c6ee5067c92e6be | sharath28/leetcode | /prob1221/split_string_in_a_balanced_string.py | 366 | 3.640625 | 4 | class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
result = 0
for char in s:
if char == 'R':
count += 1
else:
count -= 1
if count == 0:
result += 1
return result
|
addbf539340f6bcfc2a82081af74fdb1b92e9bb9 | UWPCE-PythonCert-ClassRepos/Wi2018-Classroom | /students/jchristo/session13/factorial.py | 371 | 4.34375 | 4 | #!/usr/bin/env python3
#factorial problem with recursion solution
def factorial(n):
if n <1: # base case
return 1
else:
returnNumber = n * factorial(n - 1) # recursive call
print(f'{n}! = {returnNumber}')
return returnNumber
def main():
my_fact = factorial(5)
my_fact2 = factorial(10)
if __name__ == '__main__':
main()
|
9e77f847cf197a443c965eefeb21761b12380d0b | renitro/Python | /Estruturas de Decisão/Exerc4.py | 392 | 4.25 | 4 | #4 - Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
letra = input("Digite uma letra: ")
if (letra == 'A' or letra == 'a') or (letra == 'E' or letra == 'e') or (letra == 'I' or letra == 'i') or (letra == 'O' or letra == 'o') or (letra == 'U' or letra == 'u'):
print("\nA letra digitada é uma vogal!")
else:
print("\nA letra digitada é uma consoante!") |
19b2d8b1e67167293547e1a9f26447b03021df4b | maykim51/ctci-alg-ds | /Advanced_Topics/75_topoloical_sort/app.py | 3,025 | 3.578125 | 4 | '''
CTCI Toplogical Sort
https://www.geeksforgeeks.org/topological-sorting/
'''
#Python program to print topological sorting of a DAG
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list) # dictionary containing adjacency List
self.V = vertices # No. of vertices
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSort(self):
order = []
processNext = []
inbounds = {}
for node in self.graph:
for child in self.graph[node]:
if child in inbounds:
inbounds[child] += 1
else:
inbounds[child] = 1
for node in self.graph:
if inbounds.get(node) is None or inbounds[node] is None:
processNext.append(node)
while processNext:
curr = processNext.pop(0)
for child in self.graph[curr]:
inbounds[child] -= 1
if inbounds[child] == 0:
processNext.append(child)
order.append(curr)
if len(order) == len(self.graph):
print(order)
return
else:
print('something went wrong.')
return
##Option 2. Geeks for Geeks : using recursion, and using order in reversed way.
# #Python program to print topological sorting of a DAG
# from collections import defaultdict
# class Graph:
# def __init__(self, vertices):
# self.graph = defaultdict(list) # dictionary containing adjacency List
# self.V = vertices # No. of vertices
# # function to add an edge to graph
# def addEdge(self, u, v):
# self.graph[u].append(v)
# # A recursive function used by topologicalSort
# def topologicalSortUtil(self, v, visited, stack):
# # Mark the current node as visited.
# visited[v] = True
# # Recur for all the vertices adjacent to this vertex
# for i in self.graph[v]:
# if visited[i] == False:
# self.topologicalSortUtil(i, visited, stack)
# # Push current vertex to stack which stores result
# stack.insert(0, v)
# # The function to do Topological Sort. It uses recursive
# # topologicalSortUtil()
# def topologicalSort(self):
# # Mark all the vertices as not visited
# visited = [False]*self.V
# stack = []
# # Call the recursive helper function to store Topological
# # Sort starting from all vertices one by one
# for i in range(self.V):
# if visited[i] == False:
# self.topologicalSortUtil(i, visited, stack)
# # Print contents of the stack
# print(stack)
g = Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
print("Following is a Topological Sort of the given graph")
g.topologicalSort()
|
3b242bc8a4856820cbf52c596fa3603e50143ff5 | DimoDimchev/SoftUni-Python-Basics | /Conditional Statements/personal_titles.py | 192 | 3.875 | 4 | age= float(input())
sex= input()
if sex=="m":
if age>=16:
print("Mr.")
else:
print("Master")
else:
if age>=16:
print("Ms.")
else:
print("Miss") |
fd07f3cd65643b245e74abef971844e15bc57302 | Suru996/SRM-e_lab-Python-Level-1 | /Dictionary using list.py | 217 | 3.65625 | 4 | a = int(input())
b = []
d = []
f = {}
for x in range(0,a):
c = int(input())
b.append(c)
e = int(input())
for x in range(0,e):
c = int(input())
d.append(c)
for x in range(0,a):
f.update({b[x]:d[x]})
print(f)
|
06e14c1418da1819eb5ae55ec8755323c66b4af4 | Ells-Bells/codePlayground | /Assignments/Assignment 3/AssignmentThree.py | 1,197 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Alexander David Leech
@date: Wed Apr 25 22:10:17 2018
@rev: 1
@lang: Python 2.7
@deps: None
@desc: Assignment three
"""
# Assignment 3
#
# Using the main file, create a function that will complete each of the below
# 'mini' tasks. I would like the main function to be formatted as below:
# main():
# partA()
# time.sleep(5)
# partB()
# time.sleep(5)
# partC()
# time.sleep(5)
# etc...
#
# A. Tell me the current date/time
#
#
# B. Output the current python version being used (Hint: import 'sys')
#
#
# C. When i type my first and last name, say it back to me in the format:
# lastname, firstname
#
#
# D. Tell me what items 1 and 4 of this list are:
# holidayPack = ["clothes","shoes","sunglasses","factor 50","tickets"]
#
#
# E. When I type a letter, tell me if the letter I typed is a vowel or not
#
#
# F. Optimise the code I asked you to write in the main file if you think
# it can be done
##
# There are a total of 6 marks avaliable, with a bonus 5 for
# optimised code.
#
# Good luck
# And remember, when the fun stops, stop!
print("Open source, open mind")
|
73819df827f617be29baa6c98fe6a14c9f4c996d | qunderriner/E-rate | /data_cleaning.py | 346 | 3.71875 | 4 | import pandas as pd
def make_database_csv(df, states, num):
'''
Inputs:
df: full dataframe
states: list of states to include in hosted db
num: number of random rows want to sample
'''
rv = pd.DataFrame(columns=df.columns)
for state in states:
df1 = df[df['Applicant State'] == state].sample(n=num)
rv = rv.append(df1)
return rv |
e15693cca9b18722a2b2629a02c1a40dd04db426 | likitha-9/Gene-Prediction-Using-HMM-Stochastic | /emission_probabilities.py | 1,264 | 3.703125 | 4 | """
Initial Emission Probabilities
Transitions from hidden states to observations (amino acids)
"""
import initial_amino_sequence, initial_dna_sequence
amino = initial_amino_sequence.amino
dna = initial_dna_sequence.dna
hidden = ["a","c","g","t"]
file = open("./data/observations.txt",'r')
obs = []
for line in file.readlines():
obs.append(line[:-1]) #'\n' not needed
file.close()
diction = {}
for i in hidden:
diction[i] = {}
for state in sorted(obs):
diction[i][state]=0
def compute_emissions(diction,dna,amino):
dna = [dna[i:i+3] for i in range(0,len(dna),3)]
dna.remove('\n') #dump '\n'
print(amino)
print(dna)
#this loop returns only counts
for i in range(len(amino)):
diction[dna[i][0].lower()][amino[i]] += 1 #dna[i][0].lower() --> returns one of the hidden states; [amino[i]] --> returns corresponding acid
#this loop returns probabilities
for i in diction:
count = 0
for j in diction[i]:
count += diction[i][j]
for j in diction[i]:
diction[i][j] /= count
return diction
emissions = compute_emissions(diction,dna,amino)
|
0971e7937d3a5f64f152989183bfd46246aa1dd5 | shuowenwei/LeetCodePython | /Medium/LC92.py | 2,912 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/reverse-linked-list-ii/
LC92, LC25, LC234, LC206
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseBetween(self, head, left, right):
"""
:type head: ListNode
:type left: int
:type right: int
:rtype: ListNode
"""
def reverseWholeLinkedList(head, till = None): # refer to LC206
pre = None
cur = head
# nxt = head
while cur is not till:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre, cur
# pre is the new head
# cur is till
# 1 -> 2 -> 3 -> 4 -> 5 -> None, left = 2, right = 5
dummyHead = ListNode(-1)
dummyHead.next = head
first_part = dummyHead
for i in range(left-1):
first_part = first_part.next
second_part = head
for j in range(right):
second_part = second_part.next
# first_part = 1
# second_part = 5
# reverse [left-right] --> [2, 4]
pre, cur = reverseWholeLinkedList(first_part.next, second_part) # (2, 5)
# pre = 4, the new head of the reversed part
# cur = 5, which is the "till"
# first_part = 1 still and first_part.next still points to 2
first_part.next.next = cur # point the next of the reversed part to the second part
first_part.next = pre # first_part.next points to the new head of the reversed part
return dummyHead.next
# notes from LC206
"""
# def reverseList(self, head, till=None):
pre = None
cur = head
# nxt = head
while cur is not None: #(cur != till)
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
# pre is the new head,
# cur is till
"""
# solution 2: recursively
self.successor = ListNode(-1)
def reverseN(head, n):
if n == 1:
# // 记录第 n + 1 个节点
self.successor = head.next
return head
# // 以 head.next 为起点,需要反转前 n - 1 个节点
last = reverseN(head.next, n - 1)
head.next.next = head
# // 让反转之后的 head 节点和后面的节点连起来
head.next = self.successor
return last
if left == 1:
return reverseN(head, right)
# // 前进到反转的起点触发 base case
head.next = self.reverseBetween(head.next, left - 1, right - 1)
return head
|
1548274cdebb707d02820d5eeeb30c773fa183fb | plee06/snakify_revision2 | /while_loops/hard/the_number_of_elements_equal_to_the_maximum.py | 493 | 4.15625 | 4 | '''
A sequence consists of integer numbers and ends with the number 0.
Determine how many elements of this sequence are equal to its largest element.
'''
'''
first find the maximum.
then keep count of how many in the sequence are equal to the maximum.
every time we find a new maximum the count needs to be reset.
'''
n = int(input())
max = 0
count = 0
while n != 0:
if n > max:
max = n
count = 0
if n == max:
count += 1
n = int(input())
print(count) |
2bde3d12673a52365c9c403a2a2922480a4405e7 | Just-A-TestUser/SampleRepo | /helloName.py | 114 | 3.796875 | 4 | def greeting(name):
return f"Hello, {name}!"
imya = input("What is your name?\n")
print(greeting(imya)) |
190b11901f11e31d2c205f771024a006c6fd21f0 | addleonel/OOP | /Python/uberx.py | 1,020 | 3.625 | 4 | from car import Car
from driver import Driver
class UberX(Car):
__brand: str
__model: str
def __init__(self, id: int, license: str, driver: Driver, brand: str, model: str):
super(UberX, self).__init__(id, license, driver)
self.__brand = brand
self.__model = model
def print_data(self):
super(UberX, self).print_data()
print(f'Brand: {self.__brand}, Model: {self.__model}')
@property
def get_uberx_passengers(self):
return self.get_passengers
@get_uberx_passengers.setter
def set_uberx_passengers(self, value):
assert value <= 3, 'It should be 3 or lower than 3'
self.set_passengers = value
@property
def get_brand(self):
return self.__brand
@get_brand.setter
def set_brand(self, value):
self.__brand = value
@property
def get_model(self):
return self.__model
@get_model.setter
def set_model(self, value):
self.__model = value |
4338d91d1773e8f017ae26204640ce67245773e4 | CharmingCheol/python-algorithm | /구종만 알고리즘 전략/04. 알고리즘의 시간 복잡도 분석/4.7 배열에서 찾을 숫자 인덱스 찾기.py | 844 | 3.546875 | 4 | import sys
arr = [1, 2, 3, 4, 5, 6, 7]
search = 5
result = 0
for i in range(len(arr)):
if arr[i] == search:
result = i
print(-1 if result == 0 else result)
"""
1. 최선의 수행시간
> 찾을 숫자가 배열의 맨 앞에 있을 때 알고리즘은 한번만 실행되고 종료. 반복문의 횟수는 1
2. 최악의 수행시간
> 찾을 값이 배열에 없을 때 알고리즘은 N번 반복하고 종료. 반복문의 횟수는 N
3. 평균 수행시간
> 평균 수행시간을 구하기 위해서는 존재 할 수 있는 모든 입력의 등장 확률이 모두 같다고 가정.
> 만약 주어진 배열이 항상 찾는 원소를 포함한다고 한다면 수행 시간 기대치와 수행 횟수는 N/2가 됨
4. 3개의 기준 중 주로 최악의 수행시간과 수행 시간 기대치를 사용
"""
|
7dd1e8cbcc84e0638e8a67fd91f6807ef808f776 | ayushgoel1594/Codes | /weighted_string.py | 2,186 | 3.828125 | 4 | '''
Created on May 27, 2017
@author: ayush
A uniform string is a string consisting of a single character repeated zero or more times. For example, ccc and a are uniform strings, but bcb and cd are not (i.e., they consist of more than one distinct character).
Given a string, , let be the set of weights for all possible uniform substrings (contiguous) of string . You have to answer queries, where each query consists of a single integer, . For each query, print Yes on a new line if ; otherwise, print No instead.
Note: The symbol denotes that is an element of set .
Input Format
The first line contains a string denoting (the original string).
The second line contains an integer denoting (the number of queries).
Each line of the subsequent lines contains an integer denoting (the weight of a uniform subtring of that may or may not exist).
Constraints
will only contain lowercase English letters.
Output Format
Print lines. For each query, print Yes on a new line if ; otherwise, print No instead.
Sample Input 0
abccddde
6
1
3
12
5
9
10
Sample Output 0
Yes
Yes
Yes
Yes
No
No
Explanation 0
The weights of every possible uniform substring in the string abccddde are shown below:
image
We print Yes on the first four lines because the first four queries match weights of uniform substrings of . We print No for the last two queries because there are no uniform substrings in that have those weights.
Note that while de is a substring of that would have a weight of , it is not a uniform substring.
Note that we are only dealing with contiguous substrings. So ccc is not a substring of the string ccxxc.
'''
#we can apply the given method since it is given they are continuous substrings
def weighted_string(st,x):
uniform_sub_lengths = set()
prev_letter = ""
weight = 0
for letter in st:
if letter == prev_letter:
weight += ord(letter) - 96
else:
prev_letter = letter
weight = ord(letter) - 96
uniform_sub_lengths.add(weight)
if x in uniform_sub_lengths:
print('Yes')
else:
print('No')
weighted_string('abccddde',6)
weighted_string('abccddde',10) |
994457587f75c8410ab8b40f6c3400f2afcfd4ae | melissa-tan10/mastermind | /mtanp3_nocount.py | 1,990 | 4.09375 | 4 | # Melissa Tan
# October 11, 2020
# This is a Mastermind game between a player and the computer
legal_colors = ['R', 'G', 'B', 'Y', 'W', 'O', 'M', 'V']
def generate_color_sequence():
import random
random.seed()
sequence = random.sample(range(len(legal_colors)), 4)
return [legal_colors[i] for i in sequence]
colors = generate_color_sequence()
### You Code Here
print("Possible colors are R, G, B, Y, W, O, M, V.")
print("Please enter your guess with no spaces between colors. Colors cannot be repeated.")
i = 1
while i <= 5:
guess = input(f"\nGuess {i}:")
guess = guess.upper()
i += 1
if len(guess) != 4:
print("\nPlease enter 4 letters: ")
i -= 1
elif guess[0] == guess[1]:
print("\nCannot repeat letters. Try again.")
i -= 1
elif guess[0] == guess[2]:
print("\nCannot repeat letters. Try again.")
i -= 1
elif guess[0] == guess[3]:
print("\nCannot repeat letters. Try again.")
i -= 1
elif guess[1] == guess[2]:
print("\nCannot repeat letters. Try again.")
i -= 1
elif guess[1] == guess[3]:
print("\nCannot repeat letters. Try again.")
i -= 1
elif guess[2] == guess[3]:
print("\nCannot repeat letters. Try again.")
i -= 1
else:
for index in range(len(guess)):
if guess[index] == colors[index]:
print("R", end = '')
elif guess[index] in colors:
print("W", end = '')
elif guess[index] not in legal_colors:
print(f"\n{guess[index]} is not a valid color. Try again.")
i -= 1
else:
guess[index] not in colors
print("_", end = '')
guess = list(guess)
if guess == colors:
print("\nYou win!")
quit()
if i > 5:
print("\nYou lose!")
|
b2b253ac4c238123111354c25b17493fa1b00e9c | AmuroPeng/CodingForInterview | /2020May-30-day-leetcoding-challenge/11-Flood Fill/Flood Fill.py | 1,241 | 3.515625 | 4 | import collections
class Solution:
def floodFill(self, image: list, sr: int, sc: int, newColor: int) -> list:
queue = collections.deque()
queue.append((sr, sc))
oldColor = image[sr][sc]
image[sr][sc] = newColor
if oldColor == newColor:
return image
while (queue):
m, n = queue.popleft()
# print(f"print m,n ", m, n)
if m > 0 and image[m-1][n] == oldColor:
image[m-1][n] = newColor
queue.append((m-1, n))
if n > 0 and image[m][n-1] == oldColor:
image[m][n-1] = newColor
queue.append((m, n-1))
if m < len(image)-1 and image[m+1][n] == oldColor:
image[m+1][n] = newColor
queue.append((m+1, n))
if n < len(image[0])-1 and image[m][n+1] == oldColor:
image[m][n+1] = newColor
queue.append((m, n+1))
# print(f"print queue: ", queue)
# print(f"print image: ", image, "\n")
return image
if __name__ == "__main__":
s = Solution()
print(s.floodFill(image=[[1, 1, 1], [1, 1, 0],
[1, 0, 1]], sr=1, sc=1, newColor=2))
|
87acc230b872d2772c14f8b00c668e26e99cd055 | gojun077/jun-project-euler | /ProjEuler3.py | 917 | 3.5 | 4 | # Project Euler Problem 3
# The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
# prime factor of the number 600851475143?
import doctest
def genPrimes(n):
'''
Int -> Int
Use a generator to create primes up to n which are memoized
in a list
'''
yield 2
yield 3
primes_list = [2, 3]
last = primes_list[-1]
while last < n:
last += 2
for p in primes_list:
if last % p == 0:
break
# loop falls through without finding a factor
else:
primes_list.append(last)
yield last
def findPrimeFactors(n):
'''
Int -> ListOf Int
Return list of prime factors of n
>>> findPrimeFactors(13195)
[5, 7, 13, 29]
'''
prime_factors = [i for i in genPrimes(int(n**0.5)) if n % i == 0]
return prime_factors
print(findPrimeFactors(600851475143))
doctest.testmod()
|
95bc56410efeba26fc99f9ddaaa556965f1858c6 | Keerthanavikraman/Luminarpythonworks | /regular_expression/keywords.py | 368 | 4.09375 | 4 | #match.start... return positions
#match.group..which object find match
import re
count=0
matcher=re.finditer ( 'ab' , 'abaabbab' ) #finditer is a method to find how many matches in a regular expression
#print(matcher)
for match in matcher:
print("match available at",match.start())
print("group=",match.group())
count += 1
print( "count=" , count )
|
97b2d684364e7210babdc56889e4721fe32af5c5 | siuxoes/Checkio | /Elementary/even-last.py | 234 | 3.515625 | 4 | __author__ = 'Siuxoes'
def checkio(array):
if len(array) == 0:
return 0
else:
suma = sum(array[::2])
total = suma * array[len(array)-1]
return total
array = [1, 2, 3, 4]
print(checkio(array)) |
e0224427fa54bbd5bde36b858aa9bdf07a8a0bbb | 108krohan/codor | /hackerrank-python/contests/week_17/count_fridays_the_13th - time timedelta datetime date increment month add moving traversing days check weekday.py | 3,296 | 3.796875 | 4 | """count_fridays_the_13th at hackerrank.com"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
from datetime import date, timedelta
import time
monthdays = { 1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, \
8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}
testcases = int(raw_input())
for _ in range(testcases) :
do, mo, yo, dt, mt, yt = map(int, raw_input().split())
numfr = 0
date1 = date(yo, mo, do)
while date1.day != 13 :
date1 += timedelta(days = 1)
date2 = date(yt, mt, dt) + timedelta(days = 1)
month = date1.month
while date1 < date2 :
if date1.weekday() == 4 :
numfr += 1
## print date1, date1.weekday()
if month == 13 :
month = 1
if date1.year % 4 == 0 and month == 2 :
date1 += timedelta(1)
date1 += timedelta(days = monthdays[month])
month += 1
print numfr
###correct code below, with a lot of junk comments, informative comments
"""
from datetime import date, timedelta
import time
##from datetime import timedelta, date
monthdays = { 1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, \
8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}
##def daterange(start_date, end_date):
## for n in range(0, int ((end_date - start_date).days)):
## yield start_date + timedelta(n)
testcases = int(raw_input())
for _ in range(testcases) :
do, mo, yo, dt, mt, yt = map(int, raw_input().split())
## days = days_between(do, mo, yo, dt, mt, yt)
numfr = 0
date1 = date(yo, mo, do)
while date1.day != 13 :
date1 += timedelta(days = 1)
date2 = date(yt, mt, dt) + timedelta(days = 1)
## for single_date in daterange(date1, date2):
## print single_date.strftime("%Y-%m-%d")
## numfr += 1
month = date1.month
while date1 < date2 :
## print date1.weekday()
if date1.weekday() == 4 :
numfr += 1
## print date1, date1.weekday()
if month == 13 :
month = 1
if date1.year % 4 == 0 and month == 2 :
date1 += timedelta(1)
date1 += timedelta(days = monthdays[month])
month += 1
print numfr
"""
## while (date1.day != 13) :
## date1.day += 1
## while (date1 < date2) :
## if date1.weekday() == 5 :
## numfr += 1
## date1.month += 1
## print numfr
##monthdates = { 1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, \
## 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}
##def conv(mt, mo) :
## global monthdates
## curr_m = mo
## days = 0
## while curr_m != mt :
## if curr_m > 12 :
## cur_m = 1
## days += monthdates[curr_m]
## return days
##
##def days_between(do, mo, yo, dt, mt, yt) :
## in_days = (yt - yo)*365 + dt - do
## for year in range(yo, yt + 1) :
## if year % 4 == 0 :
## in_days += 1
#### mt -= 1
#### if mt > mo :
#### in_days += conv(mt, mo)
#### elif mt == mo - 1 :
#### in_days +=
## in_days += conv(mt, mo)
## print in_days
## return in_days
##
|
d5e9b34c9c54818a91fe64cb3b24380add2c7c63 | krnets/codewars-practice | /7kyu/Don't give me five/index.py | 742 | 4.03125 | 4 | # 7kyu - Don't give me five!
""" In this kata you get the start number and the end number of a region and should return the count
of all numbers except numbers with a 5 in it. The start and the end number are both inclusive!
Examples:
1,9 -> 1,2,3,4,6,7,8,9 -> Result 8
4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12
The result may contain fives.
The start number will always be smaller than the end number. Both numbers can be also negative! """
# def dont_give_me_five(start, end):
# return sum(1 for x in range(start, end+1) if "5" not in str(x))
def dont_give_me_five(start, end):
return sum("5" not in str(x) for x in range(start, end + 1))
q = dont_give_me_five(1, 9) # 8
q
q = dont_give_me_five(4, 17) # 12
q
|
d424796179cd441d7a866e606023f49b322f898f | HeardLibrary/digital-scholarship | /code/pylesson/challenge4/schools_b.py | 1,705 | 3.921875 | 4 | import requests
import csv
r = requests.get('https://raw.githubusercontent.com/HeardLibrary/digital-scholarship/master/data/gis/wg/Metro_Nashville_Schools.csv')
fileText = r.text.split('\n')
# take care of case where there is a trailing newline at the end of the file
if fileText[len(fileText)-1] == '':
fileText = fileText[0:len(fileText)-1]
fileRows = csv.reader(fileText)
schoolData = []
for row in fileRows:
schoolData.append(row)
inputSchoolName = input("What's the name of the school? ")
found = False
for school in range(1, len(schoolData)):
if inputSchoolName.lower() == schoolData[school][3].lower(): # column 3 has the school name
found = True
# this section adds up the students in all of the grades
totalEnrollment = 0
# the grade enrollments are in columns 6 through 21
for grade in range(6, 21):
enrollment = schoolData[school][grade]
# only add the column if it isn't empty
if enrollment != '':
totalEnrollment += int(enrollment) # csv.reader reads in numbers as strings, so convert to integers
print(schoolData[school][3] + ' has a total of ' + str(totalEnrollment) + ' students.')
for category in range(22, 32):
if schoolData[school][category] != '':
# turn strings into floating point numbers
numerator = float(schoolData[school][category])
# find fraction, get the percent, and round to 1 decimal place
value = round(numerator/totalEnrollment*100, 1)
print(schoolData[0][category] + ': ' + str(value) + '%')
if not found:
print("Didn't find that school") |
1a69b6ba57116cf896908f0304827b72d7d87a95 | SkirdaMP/Check-valid-pasport | /speech_to_text.py | 1,085 | 3.59375 | 4 | import speech_recognition as sr
# obtain path to "english.wav" in the same folder as this script. path.join(path.dirname(path.realpath(__file__)),)
#from os import path
def SpeechToText():
text_in_audio = ""
for i in range(1, 7):
AUDIO_FILE = "C:\\Users\\Skirda\\Desktop\\" + str(i) + ".wav"
# use the audio file as the audio source
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio = r.record(source) # read the entire audio file
# recognize speech using Wit.ai
# Wit.ai keys are 32-character uppercase alphanumeric strings
WIT_AI_KEY = "BHKRRZVCRA456NELAYDKN5GB72QLVPPB"
try:
text_in_audio+=(r.recognize_wit(audio, key=WIT_AI_KEY))#дописать обработку полученного числа типа: если ... == "семь": то что-то
except sr.UnknownValueError:
return "Wit.ai could not understand audio"
except sr.RequestError as e:
return "Could not request results from Wit.ai service; {0}".format(e)
return text_in_audio
|
99864978404334fd3bdbd7289a60e0e4e973591d | wmm98/homework1 | /7章之后刷题/8章2/求最大公因子.py | 926 | 3.875 | 4 | '''
【问题描述】用递归方法编写求最大公因子程序。两个正整数x和y的最大公因子定义为:如果y<=x且x mod y=0时,
gcd(x,y)=y;如果y>x时,gcd(x,y)=gcd(y,x);其他情况,gcd(x,y)=gcd(y,x mod y)。这里,x mod y是求x除以y的余数。
【输入形式】用户在第一行输入两个数字,数字之间用空格分割。
【输出形式】程序在下一行输出前面输入的两个数字的最大公因子。
【样例输入】36 24
【样例输出】12
【样例说明】用户输入36,24,程序输出它们的最大公因子12
'''
def hcf(x, y):
"""该函数返回两个数的最大公约数"""
# 获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
a, b = input().split()
result = hcf(int(a), int(b))
print(result) |
7df713c6d27a30122bb093277d9212602c441695 | 108krohan/codor | /hackerrank-python/contests/world_cup/world_cup_team_formation.py | 236 | 3.765625 | 4 | """world_cup_team_formation at hackerrank.com"""
lst = [int(raw_input()) for _ in xrange(10)]
lst.sort(reverse = True)
print lst[0] + lst[2] + lst[4]
"""
take sum of the first odd three numbers sorted in reverse order.
"""
|
f110dcbfc5fcc468235545589ce32d06fb2a6096 | trialnerror404/beginner-projects | /rock paper scissor.py | 578 | 4.03125 | 4 | import random
def play():
user = input("What's your choice? \n 'r' for rock, 'p' for paper, 's' for scissors \n").lower()
computer = random.choice(['r', 'p', 's'])
print (f'The computer chose {computer}')
if user == computer:
return "tie"
if is_win (user, computer):
return 'You won!'
return 'You lost!'
def is_win (player, opponent):
# return true if player wins
# r > s, s > p, p > r
if (player == "r" and opponent =="s") or (player == "s" and opponent == "p") or (player == "p" and opponent == "r"):
return True
play() |
b811c63ad740f11cd67f040231b300ecd354a884 | S1LV3RJ1NX/CodingNinjas-DSA | /04 - MultiDimensional Arrays/07 - rotate_matrix_anitclockwise.py | 932 | 4.25 | 4 | '''
Algo for clockwise:
- Find transpose
- Take every row and swap ele from either end
Algo for anticlockwise
- Find transpose
- Take every col and swap ele from either end
'''
def inplaceRotate(arr, n):
# transpose
# This code can be imagined as traversing along the diagonal
# and swapping elements above and below the diagonal
for i in range(n):
for j in range(i):
arr[i][j], arr[j][i] = arr[j][i], arr[i][j]
# Swap col ele - Anticlk rotn
for i in range(n//2):
for j in range(n):
arr[i][j], arr[n-i-1][j] = arr[n-i-1][j], arr[i][j]
# Swap row ele - Clk rotn
# for i in range(n):
# for j in range(n//2):
# arr[i][j], arr[i][n-j-1] = arr[i][n-j-1], arr[i][j]
return arr
for _ in range(int(input())):
n = int(input())
arr = [ [ int(x) for x in input().split()] for i in range(n) ]
inplaceRotate(arr, n)
print(arr) |
d0c08b9a7ce5966ed5bf7a91719b2a0ecf1ecd95 | mohammedjasam/Coding-Interview-Practice | /Internet/Strings/ReverseStringIterationandRecursion/code.py | 179 | 3.53125 | 4 | s = "JASAM"
r = ""
for x in range(len(s)-1,-1,-1):
r += s[x]
print(r)
def rev(s):
if len(s)<2:
return s
else:
return rev(s[1:]) + s[0]
print(rev(s))
|
c63ff2a0ddcb5424a6abe7dcd4e60af1bc889d26 | Psingh12354/Python-practice | /AbsCount.py | 140 | 3.796875 | 4 | n=int(input('Enter the numbers : '))
a=int(input('Enter the sum number : '))
count=0
for i in range(n):
count+=a
print(abs(count))
|
217f6c94710ae297d01863455a5153d20bdf9288 | jagadeshwarrao/programming | /colorfulnumber.py | 1,118 | 4 | 4 | #InfyTQ - Colorful Number
#A number is a COLORFUL number, if the product of every digit of a contiguous subsequence is different.
#A number can be broken into different contiguous sub-subsequence parts.
#Suppose, a number = 3245, it can be broken into parts like 3 2 4 5 32 24 45 324 245 and since the product of every digit of a contiguous subsequence is different therefore 3245 is COLORFUL number.
#Given a number A, return 1 if A is COLORFUL else return 0.
#Input :3245
#Output :1
class Solution:
def colorful(self, A):
# write your method here
l1=list(str(A))
#return s
l=[]
s=""
for i in range(len(l1)+1):
for j in range(i+1,len(l1)+1):
s1=[]
s1.extend(l1[i:j])
#print(s1)
a=1
for k in s1:
a*=int(k)
l.append(a)
for i in l:
s=s+str(i)
for i in l:
if s.count(str(i))==1:
return 1
else:
return 0 |
b8b08895fdf9703474a24e97e1fa0bda7a78ffed | shubhra2/PythonC | /lab2.py | 2,015 | 4.25 | 4 |
def readnum() :
nm = float(input("Enter Number(s) : "))
return nm
def add() :
numarr = []
for i in range(2) :
n1 = readnum()
numarr.append(n1)
print("{} + {} = {}".format(numarr[0], numarr[1], numarr[0] + numarr[1]))
def maxmin() :
maxminnumary = []
for i in range(3) :
n2 = readnum()
maxminnumary.append(n2)
print("The Maximum and minimun of {} numbers are : {}, {} respectively." .format(maxminnumary, max(maxminnumary), min(maxminnumary)))
def palindrome():
str = input("Enter a string : ")
strrev = ''.join(reversed(str))
if(str == strrev):
print("{} is a palindrome.".format(str))
else:
print("{} is not a palindrome.".format(str))
def factorialnonfunc():
import math
num = int(readnum())
print("The factorial of {} is : {}".format(num, math.factorial(num)))
def factorialfunc():
def factorial(num1):
if num1 == 1:
return 1
else:
return (num1 * factorial(num1-1))
print(factorial(int(readnum())))
def selection():
sel = int(input('''
choose from the following :
1. Addition of two numbers.
2. Maximum and minimum from three numbers
3. Check wether a given string is a palindrome or not
4. Factorial of a number without using a function
5. Factorial of a number using a function
6. Exit
'''))
while sel < 7:
if(sel == 1):
add()
selection()
break
elif(sel == 2):
maxmin()
selection()
break
elif(sel == 3):
palindrome()
selection()
break
elif(sel == 4):
factorialnonfunc()
selection()
break
elif(sel == 5):
factorialfunc()
selection()
break
elif(sel == 6):
break
else:
print("\n\nPlease choose from 1 to 6.")
selection()
# selection()
|
212c04152e8c0adcaf544b7f7cce015144ceb07e | sherqy/homework-younghwan- | /homework/python/prime_numbers.py | 927 | 4.09375 | 4 | # Finding prime numbers
#2018. 10. 30
#version 2: printing prime numbers in the function is_prime ()
def is_prime (primes, number, printed_cnt):
count= 0
for prime_number in primes :
if (number % prime_number) == 0 :
break
else :
count += 1
if count == len (primes) :
primes.append (number)
print ("%7i" %number, end = " ")
printed_cnt += 1
if printed_cnt % 10 == 0 :
print ( )
return printed_cnt
prime_num = [2, 3, 5, 7]
Maxnumber = int (input("Enter the maximum integer of prime numbers: ") )
printed_cnt = 4
for n in prime_num :
print ("%7i" %n, end = " ") #처음 4개만 출력
for n in range (11,Maxnumber+1) :
printed_cnt = is_prime (prime_num, n, printed_cnt)
#count = 0
#for n in prime_num :
# print ("%7i" %n, end = " ")
# count += 1
# if count % 10 == 0 :
# print ( )
|
d96668250e2f715e6927b6061611aae5226ee2fc | Khalida02/Week1 | /informatics/Целочисленная арифметика/3469.py | 141 | 3.578125 | 4 | n = int(input())
n = n % (24 * 3600)
hour = n // 3600
n = n % 3600
minute = n // 60
seconds = n % 60
print(hour, ":", minute, ":", seconds) |
1455e689ad8cd3581588ead0a3ab1276a85d16ee | mounirsabry/Assignment_3 | /Game_3.py | 4,494 | 3.984375 | 4 | main_array=[1,2,3,4,5,6,7,8,9] #The Group Of All Available Numbers.
#Define The Function
def Game():
used_array=[] #The Group of All numbers That Will be used over players turns.
array1=[] #Player 1 Numbers.
array2=[] #Player 2 Numbers.
while(len(used_array)<9): #To Give Players 9 Turns .
print("\n")
if(len(used_array)!=0): #To not display empty array.
print("The Used Numbers are ",used_array) #to display used used numbers for each player.
if(len(array1)!=0):
print("Player 1 Your Numbers Are ",array1)
print("Player 1 Enter A Number") #player 1 Turn
while(True): #Because we didn't know how many times we will loop to be free up of mistakes.
temp=int(input()) #Take The Number From Player 2
if(temp>9 or temp<1): #To Make Sure That The Playe Will Enter A number Between 1 and 9.
print("Please Enter A Number Between 1 and 9")
continue
if(temp in used_array): #To Make Sure That The Player Will Not Enter A Used Number.
print("Please Enter A non Used Number")
else:
used_array.append(temp) #ADD The Number To The Used Numbers List.
array1.append(temp) #ADD The Number To Player 1 Numbers.
break
if(len(array1)>=3): #To Start Look For Winning Number When The Player Have 3 Numbers At Least.
for i in range(0,len(array1)):
for j in range(0,len(array1)):
if(i==j):
j=j+1
else:
for k in range(0,len(array1)):
if(k==i):
k=k+1
if(k==j):
k=k+1
if(k==len(array1)):
break
if(array1[i]+array1[j]+array1[k]==15):
print(array1[i],array1[j],array1[k],array1[i]+array1[j]+array1[k])
return("Player 1 Is The Winner"); #To Stop The Game When The Winner Is Found.
if(len(used_array)==9): #To Stop The Game When The Nine numbers Are All Used.
break
print("\n")
print("The Used Numbers are ",used_array)
if(len(array2)!=0):
print("player 2 Your Numbers are ",array2)
print("Player 2 Enter A Number")
while(True):
temp=int(input()) #Take The Number From Player 2
if(temp>9 or temp<1): #To Make Sure That The Playe Will Enter A number Between 1 and 9.
print("Please Enter A Number Between 1 and 9")
continue
if(temp in used_array): #To Make Sure That The Player Will Not Enter A Used Number.
print("Please Enter A non Used Number")
else:
used_array.append(temp) #ADD The Number To The Used Numbers List.
array2.append(temp) #ADD The Number To Player 2 Numbers.
break
if(len(array2)>=3): #To Start Look For Winning Number When The Player Have 3 Numbers At Least.
for i in range(0,len(array2)):
for j in range(0,len(array2)):
if(i==j):
j=j+1
else:
for k in range(0,len(array2)):
if(k==i):
k=k+1
if(k==j):
k=k+1
if(k==len(array2)):
break
if(array2[i]+array2[j]+array2[k]==15):
print(array2[i],array2[j],array2[k],array2[i]+array2[j]+array2[k])
return("Player 2 Is The Winner"); #To Stop The Game When The Winner Is Found.
return("Draw")
#Call The Function Game.
print(Game())
while(True): #Ask If The User Want to Play Again.
try_again=str(input("Play Again(yes or no)"))
if(try_again=="yes" or try_again=="Yes"):
print(Game())
elif(try_again=="no" or try_again=="No"):
break
else:
print("Please Enter A Clear Order")
print("Thank You For Playing Come Back Later")
|
c4f67d2002e25380e7a415a2924cf573a0efa5a6 | BRaguiarpereira/Aula04Python | /ex19.py | 1,864 | 3.84375 | 4 | v = float(input('Digite valor :'))
con = 0
cont = 0
cont1 = 0
cont2 = 0
cont3 = 0
cont4 = 0
sc = 0
sc1 = 0
sc2 = 0
sc3 = 0
sc4 = 0
if v==0:
print('Seu retardado não me deu nada e ainda quer troco !!asdhgqw')
else:
while v!=0:
if v>=100:
v = v-100
con = con + 1
elif v>=50:
v = v-50
cont = cont + 1
elif v>=20:
v = v-20
cont1 = cont1 + 1
elif v>=10:
v = v-10
cont2 = cont2 + 1
elif v>=4:
v = v-4
cont3 = cont3 + 1
elif v>=1:
v = v-1
cont4 = cont4 + 1
elif v>=0.50:
v = v-0.50
sc = sc + 1
elif v>=0.10:
v = v-0.10
sc1 = sc1 + 1
elif v>=0.05:
v = v-0.05
sc2 = sc2 + 1
elif v>=0.02:
v = v-0.02
sc3 = sc3 + 1
elif v>=0.01:
v = v-0.01
sc4 = sc4 + 1
print('Quantidade de notas de 100 reais foram : {}'.format(con))
print('Quantidade de notas de 50 reais foram : {}'.format(cont))
print('Quantidade de notas de 20 reais foram : {}'.format(cont1))
print('Quantidade de notas de 10 reais foram : {}'.format(cont2))
print('Quantidade de notas de 4 reais foram : {}'.format(cont3))
print('Quantidade de notas de 1 real foram : {}'.format(cont4))
print('Quantidade de moedas de 50 centavos foram : {}'.format(sc))
print('Quantidade de moedas de 10 centavos foram : {}'.format(sc1))
print('Quantidade de moedas de 5 centavos foram : {}'.format(sc2))
print('Quantidade de moedas de 2 centavos foram : {}'.format(sc3))
print('Quantidade de moedas de 1 centavos foram : {}'.format(sc4))
|
d61e6d012aefec4ba6def5ab2d5d5b362cb0cde1 | dicao425/algorithmExercise | /LeetCode/closestBinarySearchTreeValue.py | 1,669 | 3.984375 | 4 | #!/usr/bin/python
import sys
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
result = root.val
while root:
if abs(root.val - target) < abs(result - target):
result = root.val
root = root.left if target < root.val else root.right
return result
class Solution1:
def closestValue(self, root, target):
if not root:
return
lower = self.findLower(root, target)
upper = self.findUpper(root, target)
if lower and upper:
if target - lower.val > upper.val - target:
return upper.val
else:
return lower.val
if lower:
return lower.val
if upper:
return upper.val
def findLower(self, root, target):
cur = root
last = None
while cur:
if cur.val <= target:
last = cur
cur = cur.right
else:
cur = cur.left
return last
def findUpper(self, root, target):
cur = root
last = None
while cur:
if cur.val > target:
last = cur
cur = cur.left
else:
cur = cur.right
return last
def main():
aa = Solution()
return 0
if __name__ == "__main__":
sys.exit(main()) |
bab2b8f954ec61ddd194b46797612b1f0925622f | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/sttbar001/question3.py | 1,035 | 4.25 | 4 | """encrypt a message by converting all lowercase characters to the next character (with z transformed to a)
barak setton
04/05/2014"""
def enc(s):
if len(s)==1: # telling it when to stop
num = ord(s)
if s[0].isupper() or s[0] ==" " or ord(s[0])<97 or ord(s[0])>122: # checking that the charater is not in uppercase, is a space or is not in the alphabet
return s[0]
elif s=="z": # is z take it to a and not {
return "a"
else:
return chr(num+1) # return the last charature in the string
else:
if s[0].isupper() or s[0] ==" ": # checking if character in uppercase
return s[0]+enc(s[1:]) # return with the uppercase remaining
elif s[0]=="z":
return "a"+enc(s[1:])
else:
return chr(ord(s[0])+1)+enc(s[1:]) # return the new charater with the rest of string
s =input("Enter a message: \n")
encode = enc(s)
print("Encrypted message: ")
print(encode)
|
7a8e301dcaf3d1c6e9a5c7f9a7dcec65c097cd23 | cristhiantito/Python_clases | /practica_1/ejercicio_3.py | 193 | 3.625 | 4 | def velocidad(velocidad_cm,):
velocidad_cm = round(velocidad_km * 1000000, 3)
velocidad_km = float(input(f'Hola igresa la velociada en Km: '))
print(f'La velocidad en es:{velocidad_cm}cm')
|
73ce9fca1c00cd13a7b0a942ac6042f1466a5346 | flerdacodeu/CodeU-2018-Group8 | /aliiae/assignment1/question2.py | 2,308 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Assignment 1, Q2:
"Implement an algorithm to find the kth to last element of a singly linked list."
My assumptions:
1. I can use an implementation of linked list that can return its current size (length) after construction.
2. Return value of the kth to last node (instead of the node itself).
3. Return None in case of a negative k, return the first element (root) in case of k > size.
'''
import unittest
class Node:
'''
Node class, each node has a value and a pointer to the next node.
'''
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return 'Node_{}'.format(self.value)
class LinkedList:
'''
Singly linked list structure with possibility to store the current length (number of nodes)
and add new nodes to the end of the list.
'''
def __init__(self):
self.root = None
self.tail = None
self.length = 0
def add(self, value):
'''
Add a new node to the end of the linked list, with a specified value.
:param value: Value to initialize the new node with.
:return: None
'''
curr_node = Node(value)
if not self.root:
self.root = curr_node
else:
self.tail.next = curr_node
self.tail = curr_node
self.length += 1
def __len__(self):
return self.length
def kth_to_last(linked_list, k):
'''
Find the kth to last element of a singly linked list.
Returns value of the element, or None if k is a negative number.
If k is greater than the size of the linked_list, returns the first element.
:param linked_list: LinkedList object in which we need to find the element.
:param k: Integer specifying kth to last element.
:return: Value of the kth to last node in the linked list, or None if k is a negative number,
or value of the first element if k is larger than the size of the linked list.
'''
if k < 0:
return None
target_index = len(linked_list) - k
curr_node = linked_list.root
curr_index = 0
while curr_node and curr_index < target_index - 1:
curr_node = curr_node.next
curr_index += 1
return curr_node.value |
fc95892d4a776f42b6dbc23d53bd829d3b654fb4 | MADtest/AutotestCourse | /Lesson7/Class/Door.py | 2,368 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Door(object):
color = 'brown'
def __init__(self, number, state):
self.number = number
self.state = state
def open(self):
self.state = 'open'
def close(self):
self.close = 'close'
@classmethod
def knock(cls):
print ('Knock! Knock!!!')
class SecurityDoor(Door):
color = 'grey'
locked = True
def open(self):
if not self.locked:
print ('Opening')
super(SecurityDoor, self).open()
# Door.open(self)
# self.state = 'open'
class CompositeDoor(object):
color = 'composite'
locked = True
def __init__(self, number, state):
self.door = Door(number, state)
def open(self):
if not self.locked:
print ('Opening')
self.door.open()
def close(self):
self.door.close()
def __getattr__(self, attr):
return getattr(self.door, attr)
if __name__ == '__main__':
cdoor = CompositeDoor(1, 'open')
print (cdoor.__dict__)
print (cdoor.color)
cdoor.open()
cdoor.close()
# sdoor = SecurityDoor(1, 'closed')
# print (sdoor.open())
# print (sdoor.color)
# print (sdoor.locked)
# print (sdoor.state)
# print (sdoor.__class__.__dict__)
# print (sdoor.__class__.__bases__[0].__dict__)
# sdoor = SecurityDoor(1, 'closed')
# print (sdoor.__dict__)
# print (sdoor.color is Door.color)
# print (sdoor.__class__.__dict__)
# print (sdoor.__class__)
# print (sdoor.__class__.__bases__)
# print (sdoor.__class__.__bases__[0].__dict__)
# print (sdoor.__class__.__bases__[0].__dict__['color'])
# print (sdoor.__class__.__bases__[0].__dict__['knock'])
# print (sdoor.__class__.__bases__[0].__dict__['knock'].__get__(sdoor, Door))()
# door1 = Door(1, 'open')
# print (door1.__dict__)
# door2 = Door(2, 'closed')
# print (door1.knock)
# print (door2.knock)
# print (Door.knock)
# print (door1.open)
# print (type(Door.open))
# print (door1.__class__.__dict__['knock'])
# print (type(door1.__class__.__dict__['knock']))
# print (type(door1.__class__.__dict__['open']))
# print (door1.__class__.__dict__['knock'].__get__(door1, Door))
# print (type(door1.__class__.__dict__['knock'].__get__(door1, Door)))
|
77f17a8a0b59af18574c0c6563c44910b5291a10 | tejasgondaliya5/advance-python-for-me | /Exception Handling/Info_exception_and_basic_program.py | 1,888 | 3.8125 | 4 | '''
- an Exception is a runtime error which can be handled by the programmer.
- all exception are represented as classes in python.
- TWO TYPES OF EXCEPTION:-
-- Built-in Exception :- Exception which are already available in python language.
The base class for all built-in exception is baseException class.
-- User Defined Exception :- a programmer can create his own Exceptions, called user-defined exception.`
(1) try:- the try block contains code which may cause exceptions.
syntax:-
try:
statements
(2) Except:- The except block is used to catch an exception that is raised in the try block. There can be multiple except
block for try block.
syntax:-
except ExceptionName:
statements
(3) Else:- This block will get executed when no exception is raised. Else block is executed after try block.
syntax:-
else:
statement
(4) Finally:- This block will get executed irrespective of whether there is an exception or not.
syntax:-
finally:
statement
Example:-
try:
statement
except Exception class name:
statement
else:
statement # try block ma error na ave tyare else chale. or except run nathay tyare else run thay.
finally:
statement # try block ma error ave ke na ve pan finally to run thay j.
'''
a = 10
b = 5
try:
d = a/b
print(d)
except ZeroDivisionError:
print('divide by zero is not allowed')
print('rest of the code')
print()
print('.......................................')
print()
a = 10
b = 0
try:
d = a/b
print(d)
except ZeroDivisionError:
print('divide by zero is not allowed')
print('rest of the code')
|
4bed454ec8746d1e032211c7bc40ce48df495f2b | GuiRibeiro2412/Complete-Python-3-Bootcamp | /08-Milestone Project - 2/Milestone-2-Warmup-Project - Gui/test_player.py | 1,799 | 3.921875 | 4 | import unittest
import player
import card
class TestPlayer(unittest.TestCase):
def test_players_start_with_empty_hand(self):
player1 = player.Player("John")
self.assertEqual(player1.cards, [])
def test_remove_card_method_decreases_card_count_by_one(self):
two_hearts = card.Card("Two", "Hearts")
three_clubs = card.Card("Three", "Clubs")
player1 = player.Player("John")
player1.cards = [two_hearts, three_clubs]
player1.remove_card()
self.assertEqual(len(player1.cards), 1)
def test_remove_card_method_returns_card_in_first_position_of_player_hand(self):
two_hearts = card.Card("Two", "Hearts")
three_clubs = card.Card("Three", "Clubs")
player1 = player.Player("John")
player1.cards = [two_hearts, three_clubs]
drawn_card = player1.remove_card()
self.assertEqual(drawn_card, two_hearts)
def test_add_card_method_places_card_at_end_of_player_hand(self):
player1 = player.Player("John")
three_clubs = card.Card("Three", "Clubs")
two_hearts = card.Card("Two", "Hearts")
player1.cards = [three_clubs]
player1.add_card(two_hearts)
self.assertEqual(player1.cards, [three_clubs, two_hearts])
def test_add_card_method_can_add_multiple_cards_without_nesting_lists(self):
player1 = player.Player("John")
two_hearts = card.Card("Two", "Hearts")
three_clubs = card.Card("Three", "Clubs")
four_spades = card.Card("Four", "Spades")
new_cards = [three_clubs, four_spades]
player1.cards = [two_hearts]
player1.add_card(new_cards)
self.assertEqual(player1.cards, [two_hearts, three_clubs, four_spades])
if __name__ == "__main__":
unittest.main()
|
99ca4d50f28772ec3e2bbacd5298fb669328c893 | MyHiHi/myLeetcode | /leetcode+牛客/求连续子数组的最大和.py | 1,037 | 3.5 | 4 | # -*- encoding: utf-8 -*-
'''
@File : 求连续子数组的最大和.py
@Time : 2020/03/03 09:42:16
@Author : Zhang tao
@Version : 1.0
@Desc : 求连续子数组的最大和.py
'''
'''
题目描述
一个非空整数数组,选择其中的两个位置,使得两个位置之间的数和最大。
如果最大的和为正数,则输出这个数;如果最大的和为负数或0,则输出0
输入描述:
3,-5,7,-2,8
输出描述:
13
'''
# 代码一
num=list( map(int,input().strip().split(',')));
maxn,n=0,0;
for i in num:
k=n+i;
n=k if k>0 else 0;
maxn=max(maxn,n);
print(maxn)
# 代码二
num=list( map(int,input().strip().split(',')));
su=0;
maxn=0;
for i in num:
su+=i;
su = su if su>0 else 0;
maxn=max(maxn,su);
print(maxn)
# 代码三
# 最大子段和问题
# lis记录 num[:idx+1] 的最大字段和
num=list( map(int,input().strip().split(',')));
lis=[0];
t=0
for i in num:
t=max(0,t)+i;
lis+=[t];
print(max(lis))
|
cc3d0b569ab403cc61c7ea1dbf0bbffb075cd797 | Tom-Harkness/projecteuler | /Python/problem37.py | 1,372 | 3.8125 | 4 | # Project Euler problem 37: https://projecteuler.net/problem=37
# Author: Tom Harkness
# June 1, 2021
def isPrime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while (i*i<=n):
if n % i == 0:
return False
i += 2
return True
def sieve_of_eratosthenes(limit):
"""returns a list of the primes under `limit`"""
numbers = (limit+1)*[True]
numbers[0] = False
numbers[1] = False
n = 2
while n*n <= limit:
if numbers[n]:
m = n*n
while m <= limit:
numbers[m] = False
m += n
n += 1
return [_ for _ in range(len(numbers)) if numbers[_]]
def checkLeftToRight(p):
p = str(p)
while p != '':
if not isPrime(int(p)):
return False
p = p[1:]
return True
def checkRightToLeft(p):
while p != 0:
if not isPrime(p):
return False
p //= 10
return True
if __name__ == "__main__":
limit = 10**6
primes = sieve_of_eratosthenes(limit)
psum = 0
count = 0
# 2, 3, 5, and 7 not included as per question
for p in primes[4:]:
if checkLeftToRight(p) and checkRightToLeft(p):
psum += p
count += 1
print(f"found {p}, count: {count}, sum: {psum}")
|
237e3a9ad4c46aad1357ead04cad64debf9635c1 | penghuiping/python-learn | /src/c1_basic/FunctionTest.py | 415 | 3.8125 | 4 | # encoding=utf8
# 普通函数
def my_print():
print("hello")
my_print()
# 函数返回多个值
def pointAdd1(x, y):
return x + 1, y + 1
print("函数可以返回多个值:", pointAdd1(1, 2))
# 内部函数
def my_print2():
def test():
print("hello")
test()
my_print2()
# 匿名函数lambda
def add(x1, y1):
f = lambda x, y: x + y
return f(x1, y1)
print(add(1, 2))
|
1a26cef4f444f41182c047978f083001d00a3ea6 | nickest14/Leetcode-python | /python/medium/Solution_47.py | 646 | 3.59375 | 4 | # 47. Permutations II
from typing import List
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
result = [[]]
temp = []
for num in nums:
for sub in result:
for i in range((sub + [num]).index(num) + 1):
temp.append(sub[:i] + [num] + sub[i:])
result = temp
temp = []
# # List comperhension:
# for num in nums:
# result = [sub[:i] + [num] + sub[i:] for sub in result for i in range((sub + [num]).index(num) + 1)]
return result
ans = Solution().permuteUnique([1, 1, 2])
print(ans)
|
4b123aaf49e4892024d747f070aeaa4027a3ead4 | bicho1003/BASE_PY | /SysFunc.py | 1,178 | 3.546875 | 4 | import pandas as pd
import csv
import numpy as np
def SeeClients (verifi):
if verifi == True:
print("Usted puede ver la lista de los clientes")
else:
print("Usted no puede ver la lista de los clientes")
nombre = input("Escribe el nombre: ")
archivo = open("BD.txt","a")
archivo.write(nombre+"\t")
archivo.close()
apellido = input("Escribe el Apellido: ")
archivo = open("BD.txt","a")
archivo.write(apellido+"\t")
archivo.write("\n")
archivo.close()
a = np.loadtxt('BD.txt',dtype=str)
cols = 2
row_labels = []
column_labels = ['Nombre','Apellido']
print("\n")
#Row count function
def row_count():
e = 0 #Elementos del array totales
f = 0 #Filas del Array
for row in a:
for elem in row:
e = e+1
f = f+1
#Establecer Columnas con un for
#row_labels = [] #Se empieza un array vacio para llenarlo con nueva info
cont = 1 #Contador del while son las filas que hay
while cont < f+1:
row_labels.append(cont) #Agregar la fila numero x al array
cont = cont+1
#column_labels = ['C1','C2']
df = pd.DataFrame(a,columns=column_labels,index=row_labels)
print(df)
row_count() |
9e56f09c2a937dd14749083b6fe41108af4ff4cb | send2manoo/All-Repo | /myDocs/pgm/python/ml/01-LinearAlgebra/05-InverseMatrix.py | 301 | 3.71875 | 4 | # invert matrix
from numpy import array
from numpy.linalg import inv
# define matrix
A = array([[1.0, 2.0], [3.0, 4.0]])
print(A)
# invert matrix
B = inv(A) #In other words: swap the positions of a and d, put negatives in front of b and c, and divide everything by the determinant (ad-bc).
print(B)
|
78055f03c64788bdb80467650d9bd6d131c5fbf2 | caofang/OpenCV | /face_detection.py | 1,942 | 3.5625 | 4 | # image
# https://techtutorialsx.com/2017/05/02/python-opencv-face-detection-and-counting/
# streaming
# https://towardsdatascience.com/face-detection-in-2-minutes-using-opencv-python-90f89d7c0f81
import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
def capture(src):
cap = cv2.VideoCapture(src, cv2.CAP_DSHOW)
while True:
# Read the frame
_, img = cap.read()
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect the faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# Draw the rectangle around each face
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('img', img)
if cv2.waitKey(30) & 0xff == 27:
break
cap.release()
def still_image(src):
image = cv2.imread(src)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2, 4)
print(type(faces))
if len(faces) == 0:
print("No faces found")
else:
print(faces)
print(faces.shape)
print("Number of faces detected: " + str(faces.shape[0]))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 1)
cv2.rectangle(image, (0, image.shape[0] - 25), (270, image.shape[0]), (255, 255, 255), -1)
cv2.putText(image, "Number of faces detected: " + str(faces.shape[0]), (0, image.shape[0] - 10),
cv2.FONT_HERSHEY_TRIPLEX, 0.5, (0, 0, 0), 1)
cv2.imshow('Image with faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def main():
img_src = 'img/portugal_team.jpg'
capture(0)
# still_image(img_src)
# if cv2.waitKey(30) & 0xff == 27:
# cv2.destroyAllWindows()
if __name__ == '__main__':
main() |
6ec556eb09f973325d0ad7e23626b2e2146a03fc | kristinnk18/NEW | /Skipanir/FilesAndExeptions/File/contentOfFileInOneLine.py | 849 | 4.40625 | 4 | # Write a program that reads a file called 'test.txt' and prints out the contents on the screen after removing all spaces and newlines.
# Punctuations will be preserved.
# For example, if 'test.txt' contains:
# This is a test file, for chapter 06.
# This a new line in the file!
# Then, your program's output will show:
# Thisisatestfile,forchapter06.Thisanewlineinthefile!
# Hint:
# Consider using the strip() and replace() functions.
#################################################################
with open("test.txt", "r") as file_content:
for word in file_content:
print(word.replace(" ", "").strip("\n"), end="")
############################# Önnur Utgafa ########################
# file_content = open("test.txt", "r")
# for word in file_content:
# print(word.replace(" ", "").strip("\n"), end="")
# file_content.close() |
3d979f698dae0f5dc5c71985f13dee9e5267e7b2 | milescarberry/blockchain_in_python | /main.py | 1,789 | 3.65625 | 4 | import hashlib
class NambiCoinBlock():
# Our Special Constructor Method of our class:
def __init__(self, previous_block_hash, latest_transaction_list):
self.previous_block_hash = previous_block_hash
self.latest_transaction_list = latest_transaction_list
self.block_data = "-".join(latest_transaction_list) + "-" + previous_block_hash
self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()
# hexdigest() method returns the hexadecimal code in the form of a string object.
# Now, let's perform some transactions.
t1 = "Aditya sends 1.56 NBC to Ramesh."
t2 = "Ramesh sends 4.3 NBC to Ahilya."
t3 = "Gaurav sends 3.2 NBC to Aditya."
t4 = "Aditya sends 4.22 NBC to Ahilya."
t5 = "Ramesh sends 7.1234 NBC to Gaurav."
t6 = "Mathew sends 9.260 NBC to Aditya."
t7 = "Ravish sends 2.1245 NBC to Ramesh."
genesis_block = NambiCoinBlock("Genesis Block", [t1, t2])
# genesis_block is the "initial" Nambi Coin block.
# genesis_block is an "instance" of the NambiCoinBlock class.
print()
print(genesis_block.block_data)
print()
# print(type(genesis_block.block_hash))
print(genesis_block.block_hash)
second_block = NambiCoinBlock(genesis_block.block_hash, [t3, t4])
print()
print(second_block.block_data)
print()
print(second_block.block_hash)
third_block = NambiCoinBlock(second_block.block_hash, [t5, t6])
print()
print(third_block.block_data)
print()
print(third_block.block_hash)
def create_block(block_hash_code, transaction_list):
return NambiCoinBlock(block_hash_code, transaction_list)
fourth_block = create_block(third_block.block_hash, [t7])
print()
print()
print(fourth_block.block_data)
print()
print()
print(fourth_block.block_hash)
|
a48d0e9624c737b33a6de96d3f0eaff26ff32e56 | jgp77/NAU-CS-126-Fall-2016 | /Python Files/Lab11.py | 11,714 | 3.84375 | 4 | import random
class DiceRoller:
# a utility class for dice rolling.
def roll(self, times, sides):
# rolls times number of sides-sided dice; returns the total
total=0
for i in range(times):
roll=random.randint(1, sides)
total += roll
return total
r=DiceRoller()
class Attack:
# encapsulates the concept of an attack
def __init__(self, name, number_of_dice, sides_of_die, damage_type):
# creates an attack with private attributes
self._name=name
self._sides=sides_of_die
self._number=number_of_dice
self._type=damage_type
# getters
def get_attack_type(self):
# returns the type of attack as a string
return self._type
def get_damage(self):
# returns a damage value for this attack
# rolls _number number of _sides sided dice, using DiceRoller r, and
# returns the resulting value.
self.damage_value=r.roll(self._number, self._sides)
return self.damage_value
def get_name(self):
# returns the name of attack as a string
return self._name
def get_sides_of_die(self):
# returns the number of sides on the die as a string
return str(self._sides)
def get_number_of_die(self):
# returns the number of die as a string
return str(self._number)
# setters
def set_attack_type(self, damage_type):
# sets the type of attack
self._type=damage_type
def set_damage(self):
# sets a damage value for the attack
# rolls _number number of _sides sided dice, using DiceRoller r, and
# returns the resulting value.
self.damage_value=r.roll(self._number, self._sides)
def set_name(self, name):
# sets the name of attack
self._name=name
def set_sides_of_die(self, sides_of_die):
# sets the number of sides on the die
self._sides=sides_of_die
def set_number_of_die(self, number_of_dice):
# sets the number of dice
self._number=number_of_dice
class Adventurer:
# encapsulates the concept of an adventurer
def __init__(self, name, hit_points, defense, magic_defense, initiative):
# creates an adventurer w private attributes
self._name=name
self._hit_points=hit_points
self._defense=defense
self._magic_defense=magic_defense
self._initiative=initiative
def is_alive(self):
# returns True if object has more than 0 hit points
if self._hit_points > 0:
return True
else:
return False
def roll_initiative(self):
# returns a random integer between 0 and object's initiative value
roll_initiative=random.randint(0, self._initiative)
return roll_initiative
def take_damage(self, amount, damage_type):
# applies damage to object's attributes
'''
if damage type is 'physical',
reduce the object's hit points by
what is left after reducing
amount by the object's defense.
'''
if damage_type.lower() == 'physical':
new_amount=amount - self._defense
# makes sure hit points do not get added to
if new_amount < 0:
new_hit_points=self._hit_points
else:
new_hit_points=self._hit_points - new_amount
# makes sure hit points can not be negative
if new_hit_points < 0:
new_hit_points=0
self._hit_points=new_hit_points
print(self._name +
' suffers ' +
str(new_amount) +
' damage after ' +
str(self._defense) +
' magic defense and has ' +
str(self._hit_points) +
' hit points left.')
'''
if damage type is ”magic”,
reduce the object’s hit points
by what is left after reducing
amount by the object’s magic defense.
'''
if damage_type.lower() == 'magic':
new_amount=amount - self._magic_defense
# makes sure hit points do not get added to
if new_amount < 0:
new_amount=0
new_hit_points=self._hit_points - new_amount
else:
new_hit_points=self._hit_points - new_amount
# makes sure hit points can not be negative
if new_hit_points < 0:
new_hit_points=0
self._hit_points=new_hit_points
print(self._name.capitalize() +
' suffers ' +
str(new_amount) +
' damage after ' +
str(self._magic_defense) +
' magic defense and has ' +
str(self._hit_points) +
' hit points left.')
# getters
def get_name(self):
# returns name of adventurer as string
return self._name
def get_hit_points(self):
# returns hit points of adventurer as string
return str(self._hit_points)
def get_defense(self):
# returns defense of adventurer as string
return str(self._defense)
def get_magic_defense(self):
# returns magic defense of adventurer as string
return str(self._magic_defense)
def get_initiative(self):
# returns initiative of adventurer as string
return self._initiative
# setters
def set_name(self, name):
# sets name of adventurer
self._name=name
def set_hit_points(self, hit_points):
# sets hit points of adventurer
self._hit_points=hit_points
def set_defense(self, defense):
# sets defense of adventurer
self._defense=defense
def set_magic_defense(self, magic_defense):
# sets magic defense of adventurer
self._magic_defense=magic_defense
def set_initiative(self, initiative):
# sets initiative of adventurer
self._initiative=initiative
class Fighter(Adventurer):
# encapsulates a a fighter class inheriting from adventurer
# class member variables
# health points/hit points
_HP=40
# defense
_DEF=10
# magic defense
_MAG_DEF=4
def __init__(self, name, initiative):
# creates a fighter object
# calls super class __init__ method
super().__init__(name, Fighter._HP,
Fighter._DEF, Fighter._MAG_DEF, initiative)
# variable _melee references an instance of attack class (a fixed
# attack)
self._melee=Attack('Slash', 2, 16, 'physical')
def strike(self):
'''
calculates and returns info about a physical strike from object:
returns a tuple of damage value and damage type
damage value is obtained by calling get_damage() method on _melee
damage type is obtained by calling get_attack_type() on _melee
prints information about strike
'''
self._damage_value=self._melee.get_damage()
self._damage_type=self._melee.get_attack_type()
print(self._name +
' attacks with ' +
self._damage_type.capitalize() +
' for ' +
str(self._damage_value) +
' physical damage.')
return (self._damage_value, self._damage_type)
def __str__(self):
# returns a string representation of this object
return self._name + ' with '\
+ str(self._hit_points) + ' hit points and a '\
+ self._melee.get_name().capitalize() + ' attack ('\
+ str(self._melee.get_number_of_die()) + 'd'\
+ str(self._melee.get_sides_of_die()) + ').'
class Wizard(Adventurer):
# encapsulates a wizard class inheriting from adventurer
# class member variables
# health points/hit points
_HP=20
# defense
_DEF=4
# magic defense
_MAG_DEF=10
def __init__(self, name, initiative):
# creates wizard object
# calls super class __init__ method
super().__init__(name, Wizard._HP,
Wizard._DEF, Wizard._MAG_DEF, initiative)
# variable _spell that references an instance of attack class (a fixed
# attack)
self._spell=Attack('Vortex', 4, 6, 'magic')
def cast(self):
'''
calculates and returns info about a spell from object:
returns a tuple of damage value and damage type
damage value is obtained by calling get_damage() method on _spell
damage type is obtained by calling get_attack_type() on _spell
prints information about strike
'''
self._damage_value=self._spell.get_damage()
self._damage_type=self._spell.get_attack_type()
print(self._name +
' attacks with ' +
self._damage_type.capitalize() +
' for ' +
str(self._damage_value) +
' physical damage.')
return (self._damage_value, self._damage_type)
def __str__(self):
# returns a string representation of this object
return self._name + ' with ' \
+ str(self._hit_points) + ' hit points and a '\
+ self._spell.get_name().capitalize() + ' attack ('\
+ str(self._spell.get_number_of_die()) + 'd'\
+ str(self._spell.get_sides_of_die()) + ').'
if __name__ == '__main__':
# create a fighter object
ajax=Fighter('Ajax', 50)
# print fighter object out
print('Created:', ajax)
# create a wizard object
akb=Wizard('AbbraKaddaBruh', 100)
# print wizard object out
print('Created:', akb)
# create variable to keep track of rounds of combat
rounds=0
# as long as both combatants are alive– keep fighting rounds
while akb._hit_points > 0 and ajax._hit_points > 0:
# round counter
print('Round ', str(rounds))
rounds += 1
# roll initiative for both combatants
fighter_init=ajax.roll_initiative()
print("Ajax's initiative is: ", fighter_init)
wizard_init=akb.roll_initiative()
print("AbbraKaddaBruh's initiative is: ", wizard_init)
# higher init gets to attack this round
if fighter_init == wizard_init:
# roll initiative for both combatants until different
while fighter_init == wizard_init:
fighter_init=ajax.roll_initiative()
# print("Ajax's initiative is: ", fighter_init)
wizard_init=akb.roll_initiative()
# print("AbbraKaddaBruh's initiative is: ", wizard_init)
# if fighter init greater than wizard init
if fighter_init > wizard_init:
print('Ajax wins initiaive!')
# ajax strikes
strike=ajax.strike()
# print(strike)
# akb takes damage
akb.take_damage(strike[0], strike[1])
# if fighter init lesser than wizard init
if fighter_init < wizard_init:
print('AbbraKaddaBruh wins initiative!')
# akb strikes
spell=akb.cast()
# print(spell)
# ajax takes damage
ajax.take_damage(spell[0], spell[1])
# print message indicating which combatant won and remaining hit points
final_fighter_hp=ajax.get_hit_points()
final_wizard_hp=akb.get_hit_points()
if final_fighter_hp > final_wizard_hp:
print('Ajax wins with ' + final_fighter_hp + ' hit points left.')
else:
print(
'AbbraKaddaBruh wins with ' +
final_wizard_hp +
' hit points left.')
|
4082dd7d52687014a9849e6206c38a84606ec831 | Aasthaengg/IBMdataset | /Python_codes/p02577/s767783464.py | 92 | 3.53125 | 4 | n = list(input())
ans = 0
for i in n:
ans += int(i)
print('Yes' if ans%9==0 else 'No')
|
aee9e02f36c961830e41063c0eef53de80c3e04e | RedTeamMedic/pyCrypt | /ReverseCipher/reversecipher.py | 699 | 4.21875 | 4 | choice = input("Do you want to encrypt or decrypt? Enter e for encrypt or d for decrypt: ")
if choice == 'd':
message = input("Enter the message to be decrypted: ")
translated = ' ' #decrypted text will be stored in this variable
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print("The decrypted text is : ", translated)
elif choice == 'e':
message = input("Enter the message to be encrypted: ")
translated = ' ' #cipher text is stored in this variable
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print("The cipher text is : ", translated)
else:
print("Sorry, I didn't get that. Try again. Goodbye.")
|
9dfdc7675a32f4c4ec6500d1b7ef86d9efe2875a | vivekbarsagadey/data-analisys-poc | /code/com/whiz/dap/mathplot/second.py | 217 | 3.8125 | 4 | import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 2, 6, 7]
plt.plot(x,y,'ro')
# axis -- [xmin, xmax, ymin, ymax]
plt.axis([0, max(x)+2, 0, max(y)+2])
plt.ylabel('y numbers')
plt.xlabel('x numbers')
plt.show() |
a7b0d21a3141705862e2d42471172004751b5ad0 | NSCC-Fall-2020/PROG1700-DBA-course-notes | /functions/magic_eight_ball.py | 1,136 | 4.03125 | 4 |
import random
ANSWERS = (
"It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes – definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful.",
)
def ask_question():
return input("Ask the almighty eightball a question (ENTER to quit): ")
def give_answer():
#answer = random.randrange(len(ANSWERS))
#answer = random.randint(0,len(ANSWERS)-1)
return random.choice(ANSWERS)
# if this returns True, keep asking questions
# if this returns False, end the program
def the_magic_eight_ball():
# user asks the eight ball a question
if len(ask_question()) == 0:
return False
# reply with random answer
print(give_answer())
return True
# loop until user is done
while the_magic_eight_ball():
pass
|
29b5779818876d264b9c75624656eb09e251cd4e | stacygo/2021-01_UCD-SCinDAE-EXS | /14_Cluster-Analysis-in-Python/14_ex_4-07.py | 913 | 3.546875 | 4 | # Exercise 4-07: Top terms in movie clusters
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.cluster.vq import kmeans
from functions import remove_noise
movies = pd.read_csv('input/movies_plot.csv')
plots = list(movies['Plot'])
tfidf_vectorizer = TfidfVectorizer(max_df=0.75, min_df=0.1, max_features=50, tokenizer=remove_noise)
tfidf_matrix = tfidf_vectorizer.fit_transform(plots)
num_clusters = 2
# Generate cluster centers through the kmeans function
cluster_centers, distortion = kmeans(tfidf_matrix.todense(), num_clusters)
# Generate terms from the tfidf_vectorizer object
terms = tfidf_vectorizer.get_feature_names()
for i in range(num_clusters):
# Sort the terms and print top 3 terms
center_terms = dict(zip(terms, list(cluster_centers[i])))
sorted_terms = sorted(center_terms, key=center_terms.get, reverse=True)
print(sorted_terms[:3])
|
38f20d5fd79779d4eb2aa68306b235abae9058aa | calendula547/python_fundamentals_2020 | /python_fund/data_types_variables/biggest_of_three_nums.py | 146 | 3.828125 | 4 | first_num = int(input())
second_num = int(input())
third_num = int(input())
max_num = (max(first_num, second_num, third_num))
print(max_num) |
2d15e7826196169139cf47e0b37f8fe5e92014e5 | rohansaini7/python-beginning | /factorial.py | 131 | 4.125 | 4 | ##factorial
x=int(input("enter number to find factorial"))
a=1
#total=1
for i in range(x,1,-1):
a=i*a
print('factorial is',a)
|
e3c873495089bf2596ea9ed4245de414b4de6732 | Brundha14/PYTHON | /printntimes.py | 59 | 3.640625 | 4 | a=input("")
print (a)
for i in range(a):
print ("Hello")
|
5d050b434a8d90ff6e4790f266145bcb44e6f54a | enicolasgomez/effective-python | /comprenhension-and-generators.py | 5,879 | 4.1875 | 4 | #Item 27: Use Comprehensions Instead of map and filter
# Comprenhension (iterable to list)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in a] # List comprehension
even_squares = [x**2 for x in a if x % 2 == 0]
#same with map and filter
alt = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a))
assert even_squares == list(alt)
# Item 28: Avoid More Than Two Control Subexpressions in Comprehensions
my_lists = [
[[1, 2, 3], [4, 5, 6]],
]
flat = [x for sublist1 in my_lists
for sublist2 in sublist1
for x in sublist2]
# better
flat = []
for sublist1 in my_lists:
for sublist2 in sublist1:
flat.extend(sublist2)
# Item 29: Avoid Repeated Work in Comprehensions by Using Assignment Expressions
# ✦ Assignment expressions make it possible for comprehensions and
# generator expressions to reuse the value from one condition elsewhere in the same comprehension, which can improve readability
# and performance.
# ✦ Although it’s possible to use an assignment expression outside of
# a comprehension or generator expression’s condition, you should
# avoid doing so.
# Item 30: Consider Generators Instead of Returning Lists
def read_csv(file_name):
for row in open(file_name, "r"):
yield row
# By introducing the keyword yield,
# we’ve essentially turned the function into a generator function.
# This new version of our code opens a file, loops through each line,
# and yields each row.
def index_words_iter(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ' ':
yield index + 1
# When called, a generator function does not actually run but instead
# immediately returns an iterator. With each call to the next built-in
# function, the iterator advances the generator to its next yield expression.
# Each value passed to yield by the generator is returned by the
# iterator to the caller:
it = index_words_iter(address)
print(next(it))
print(next(it))
# ✦ Using generators can be clearer than the alternative of having a
# function return a list of accumulated results.
# ✦ The iterator returned by a generator produces the set of values
# passed to yield expressions within the generator function’s body.
# ✦ Generators can produce a sequence of outputs for arbitrarily large
# inputs because their working memory doesn’t include all inputs and
# outputs.
# Item 31: Be Defensive When Iterating Over Arguments
# normalization problem ( percentage from total)
def normalize(numbers):
total = sum(numbers)
result = []
for value in numbers:
percent = 100 * value / total
result.append(percent)
return result
# say that values come from a generator
def read_visits(data_path):
with open(data_path) as f:
for line in f:
yield int(line)
# calling
it = read_visits('my_numbers.txt')
percentages = normalize(it)
print(percentages)
#[] never calls iterator next before normalizing
#alternatives
# 1. numbers_copy = list(numbers) # copy iterator, works but could be extremely large
# 2. percentages = normalize_func(lambda: read_visits(path)) # pass a lambda expression, difficult to read
# 3. implementing the __iter__ (iterator protocol)
class ReadVisits:
def __init__(self, data_path):
self.data_path = data_path
def __iter__(self):
with open(self.data_path) as f:
for line in f:
yield int(line)
visits = ReadVisits(path)
percentages = normalize(visits)
print(percentages)
assert sum(percentages) == 100.0
# defensive check: if isinstance(numbers, Iterator):
# Item 32: Consider Generator Expressions for Large List Comprehensions
# read a file and return the number of
# characters on each line. Doing this with a list comprehension would
# require holding the length of every line of the file in memory
# big file or stream : problem
value = [len(x) for x in open('my_file.txt')]
print(value)
# solution: generator expression
it = (len(x) for x in open('my_file.txt'))
print(next(it))
# generator expression composition
roots = ((x, x**0.5) for x in it)
# Item 33: Compose Multiple Generators with yield from
# animation using combined generators
#noisy approach
def animate():
for delta in move(4, 5.0):
yield delta
for delta in pause(3):
yield delta
for delta in move(2, 3.0):
yield delta
def render(delta):
print(f'Delta: {delta:.1f}')
# Move the images onscreen
def run(func):
for delta in func()
#better approach
def animate_composed():
yield from move(4, 5.0)
yield from pause(3)
yield from move(2, 3.0)
# Item 34: Avoid Injecting Data into Generators with send
# Python generators support the send method, which upgrades yield
# expressions into a two-way channel. The send method can be used to
# provide streaming inputs to a generator at the same time it’s yielding
# outputs.
# SIN(X) function plus step
def wave_modulating(steps):
step_size = 2 * math.pi / steps
amplitude = yield # Receive initial amplitude
for step in range(steps):
radians = step * step_size
fraction = math.sin(radians)
output = amplitude * fraction
amplitude = yield output # Receive next amplitude
def run_modulating(it):
amplitudes = [None, 7, 7, 7, 2, 2, 2, 2, 10, 10, 10, 10, 10]
for amplitude in amplitudes:
output = it.send(amplitude)
transmit(output)
run_modulating(wave_modulating(12))
#hard to read but works
# ✦ The send method can be used to inject data into a generator by giving the yield expression
# a value that can be assigned to a variable.
# ✦ Using send with yield from expressions may cause surprising behavior,
# such as None values appearing at unexpected times in the generator output.
# ✦ Providing an input iterator to a set of composed generators is a better approach than using the send method,
# which should be avoided.
# Item 35 and 36 : TODO |
d7db6e925921b64c2ba95a6e8355854ab019b594 | xrlie/pirple_python | /homeworks/homework_5/main.py | 2,502 | 4.40625 | 4 | # # # # # # # # # # # # # # # # # # # # # # #
# Homework Assignment #5: Basic Loops #
# # # # # # # # # # # # # # # # # # # # # # #
"""
You're about to do an assignment called "Fizz Buzz", which is one of the
classic programming challenges. It is a favorite for interviewers, and a
shocking number of job-applicants can't get it right. But you won't be one
of those people. Here are the rules for the assignment (as specified by
Imran Gory):
Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number and
for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
For extra credit, instead of only printing "fizz", "buzz", and "fizzbuzz",
add a fourth print statement: "prime". You should print this whenever you
encounter a number that is prime (divisible only by itself and one).
As you implement this, don't worry about the efficiency of the algorithm
you use to check for primes. It's okay for it to be slow.
"""
# First part of the homework:
# I used a for to print all the numbers from 1 to 100
for number in range(1,101):
# First we check if the number is divisible by 3 and 5
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
# Second, if the previous condition wasn't fulfilled, we check if it is only divisible by 3
elif number % 3 == 0:
print("Fizz")
# Third, if the previous condition wasn't fulfilled, we check if it is only divisible by 5
elif number % 5 == 0:
print("Buzz")
# Fourth, if none of the previous condition was fulfilled, then we just print the number.
else:
print(number)
### Extra credit
# I define a function to check if the number is prime or not comparing it with the first 100 numbers
def is_prime(number):
counter = 0
for divisor in range (1,101):
if counter == 3:
break
else:
if number >= divisor :
if number % divisor == 0:
counter += 1
else:
continue
else:
continue
if counter == 1 or counter == 3:
return False
else:
return True
# Then I use the same code from the first part of this homework just that I add the new function in the loop.
for number in range(1,101):
if is_prime(number):
print("prime")
else:
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number) |
261361132e77f1eeaea0cdc3fd4505c227ac4473 | cosah/Project-Euler-SPOILERS | /prob16.py | 96 | 3.640625 | 4 | digits = str(2**1000)
totalSum = 0
for num in digits:
totalSum += int(num)
print(totalSum)
|
1176dd00061f3996f2fb1276e6a0b34bef57f839 | fardinhakimi/python-advanced | /src/lambda_fns_practice.py | 408 | 3.859375 | 4 |
from functools import reduce
uppercase_list = list(map(lambda x: x.upper(), ['cat', 'dog', 'cow']))
filtered_list = list(filter(lambda x: 'o' in x, ['cat', 'dog', 'cow']))
reduced_list = reduce(lambda acc, x: f'{acc} | {x}', ['cat', 'dog', 'cow'])
names = ['fardin']
print(list(map(lambda x: x.upper(), names)))
print([uppercase_list, filtered_list, reduced_list])
if __name__ == '__main__':
pass
|
92af1079c917ed05ad110e97dcd05e6c0af9c435 | likendev/Sorting | /Sort.py | 729 | 4.0625 | 4 | def bubble_sort(nums: list[int]) -> list[int]:
for i in range(len(nums)):
for j in range(len(nums) - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
return nums
def selection_sort(nums: list[int]) -> list[int]:
for i in range(len(nums)):
min_index = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[i]:
min_index = j
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
if __name__ == '__main__':
nums = [45, 55, 35, 25]
print('Bubble Sort: ' + ', '.join(str(e) for e in bubble_sort(nums)))
print('Selection Sort: ' + ', '.join(str(e) for e in selection_sort(nums)))
|
110f6f58fb4a88ba54917e06cd91e6a0da7d0598 | greenfox-zerda-lasers/tamas.tatai | /week-04/day-4/07.py | 268 | 3.84375 | 4 | def string_change(string):
if len(string) == 0:
return ""
else:
if string[0] == "x":
return "y" + string_change(string[1:])
else:
return string[0] + string_change(string[1:])
print string_change("xnkjanskjxajsnasjkx")
|
ef2039785bd9ab3625d24bfb5aefb57bc4d0f30a | shubhamsaraf26/python | /code-withherry/variable.py | 197 | 3.59375 | 4 | a="shubham"
b=35
c=45.31
'''data types in poython
integer
float
string
boolean
None
'''
d=None
a='''shubham
this "is" my program'''
print(a)
print(type(a))
print(d)
#python is case sensiitive
|
737451813b217dfe5c1e3e2154276793b90b50ac | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/allergies/cf810681e7b2425baa8e234a00225efc.py | 668 | 3.8125 | 4 | class Allergies(object):
score_to_allergen = {
1: 'eggs',
2: 'peanuts',
4: 'shellfish',
8: 'strawberries',
16: 'tomatoes',
32: 'chocolate',
64: 'pollen',
128: 'cats'
}
def __init__(self, score):
self._score = score
self.list = []
self.determine_allergens()
print self.list
def is_allergic_to(self, item):
return item in self.list
def determine_allergens(self):
for score, allergen in sorted(self.__class__.score_to_allergen.items(), key=lambda i: i[0]):
if self._score & score:
self.list.append(allergen)
|
e8cffd3a4b8566a75486e560373f3c1b26351da6 | zinking/acmcatchups | /leetcode/findKth.py | 1,114 | 3.65625 | 4 | class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n = len(nums)
if n == 0: return None
def radixSort(nums):
print "Sort"*15
buckets = [ [] for i in range(10)]
allZero = False
i = 1
r = nums
while not allZero:
allZero = True
for n in r:
di = (n/(10**(i-1)))%(10)
if di != 0: allZero = False
buckets[di].append(n)
print i, buckets
r = []
for i1 in range(0,10):
r.extend(buckets[i1])
buckets[i1] = []
print '#:',r
i+=1
return r
snums = radixSort(nums)
print snums
return snums[k-1]
solver = Solution()
print ""
print solver.findKthLargest([1],1)
print solver.findKthLargest([-1,-1],2)
print solver.findKthLargest([10,128398,32,12321],1)
|
73a89cdfc813ca99a340a84d4f98829f2f417d24 | derlung/atom_python | /section4/google/4-7-5.py | 398 | 3.796875 | 4 | import matplotlib.pyplot as plt
#figure 객체 생성
fig = plt.figure()
#서브 슬롯 생성(2행 1열)
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
#x,y축 생성
x=range(0,256)
#y1축 생성
y1=[v*v for v in x]
#y2축 생성
y2 = [v*v*2 for v in x]
#멀티 라인(1행 1열)
ax1.plot(x,y1,'b',y2,'r--')
#멀티 라인(2행 2열)
ax2.bar(x,y1)
plt.show()
#출력
plt.show()
|
77c614e1f53e0df4be91d8368c7416b3645c11f6 | Pierre-siddall/Codewars | /pig_latin.py | 360 | 3.609375 | 4 | import string
def pig_it(text):
wordlist = text.split()
for i in range(len(wordlist)):
if wordlist[i] in string.punctuation:
pass
else:
tmp = wordlist[i][0]
wordlist[i]=wordlist[i][1:]+tmp+'ay'
return' '.join(wordlist)
if __name__ == '__main__':
pig_it('O tempora o mores !')
|
487d10deed73525654db0fd9fac75c8103cb9a28 | daniel-reich/ubiquitous-fiesta | /4QLMtW9tzMcvG7Cxa_23.py | 186 | 3.5 | 4 |
def resistance_calculator(resistors):
s = sum(resistors)
if 0 in resistors:
return [0, s]
p = 1 / sum([1/x for x in resistors])
return [round(p,2), round(s,2)]
|
5f7d03627f21d31a7533762b0e36cb59f1ef9620 | dxong96/group14-1008 | /block.py | 712 | 3.546875 | 4 | from predicate import Predicate
class Block:
up = None
below = None
value = None
held = False
def __init__(self, value, up, below):
self.value = value
self.up = up
self.below = below
def ontable(self):
return self.below == None and not self.held
def on(self, block):
if self.below == None:
return False
return self.below.value == block.value
def clear(self):
return self.up == None and not self.held
def predicates(self):
ret = []
if self.ontable():
ret.append(Predicate('ontable', (self.value, )))
if self.below != None:
ret.append(Predicate('on', (self.value, self.below.value)))
if self.clear():
ret.append(Predicate('clear', (self.value, )))
return ret |
ea8135c100682f1cec90011fe50a9d93a36d3365 | raj4217/Python | /Algos/Linked lists/Linked List Nth to Last Node.py | 1,475 | 3.984375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.nextnode = None
def nth_to_last_node_1(n, head):
nd = head
pos = 1
d = dict()
while nd:
d[pos] = nd
nd = nd.nextnode
pos += 1
if pos < n:
raise LookupError('Error: n is larger than the linked list.')
print(pos, d[5].value)
return d[pos - (n - 1)]
def nth_to_last_node_2(n, head):
left_pointer = head
right_pointer = head
# Set right pointer at n nodes away from head
for i in xrange(n - 1):
# Check for edge case of not having enough nodes!
if not right_pointer.nextnode:
raise LookupError('Error: n is larger than the linked list.')
# Otherwise, we can set the block
right_pointer = right_pointer.nextnode
# Move the block down the linked list
while right_pointer.nextnode:
left_pointer = left_pointer.nextnode
right_pointer = right_pointer.nextnode
# Now return left pointer, its at the nth to last element!
return left_pointer
if __name__ == '__main__':
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
a.nextnode = b
b.nextnode = c
c.nextnode = d
d.nextnode = e
# This would return the node d with a value of 4, because its the 2nd to last node.
target_node = nth_to_last_node_1(3, a)
target_node = nth_to_last_node_2(3, a)
print(target_node.nextnode.value)
|
f2df5307ea592bedb8cd9b45142acfe9a8c10389 | tippitytapp/python_guided | /week1/wednesday/tkwork.py | 1,334 | 3.546875 | 4 | class Animal:
def __init__(self, name, hunger, diet):
self.name = name
self.hunger = hunger
self.diet = diet
def eat(self, food):
if food > 0 and self.hunger <25:
self.hunger += food
from datetime import datetime
class User:
def __init__(self, name, is_admin=False):
self.name = name
self.is_admin = is_admin
class Admin(User):
def __init__(self, name):
super().__init__(name, is_admin=True)
class Customer(User):
def __init__(self, name):
super().__init__(name)
self.purchases = []
def purchase_product(self, product):
purchase = Product(product, self)
self.purchases.append(purchase)
class Vendor(User):
def __init__(self, name):
super().__init__(name)
self.products = []
def create_product(self, product_name, product_price):
product = Product(product_name, product_price, self)
self.products.append(product)
class Product:
def __init__(self, name, price, vendor):
self.name = name
self.price = price
self.vendor = vendor
class Purchase:
def __init__(self, product, customer):
self.product = product
self.customer = customer
self.purchase_price = product.price
self.purchase_date = datetime.now() |
bf06b44589f63d3839a82b4eb9ed2b67a95cbabc | Jyllove/Python | /DataStructures&Algorithms/Sort/simpleselectsort.py | 601 | 4.15625 | 4 | def simple_select_sort(raw_array):
ordered_array = []
for i in range(len(raw_array)):
minimum = raw_array[0]
for j in range(1,len(raw_array)):
if minimum > raw_array[j]:
minimum = raw_array[j]
raw_array.remove(minimum)
ordered_array.append(minimum)
return ordered_array
if __name__ == "__main__":
raw_array = [1,4,6,7,3,8,9,2,5,10]
print("raw array:",end="")
print(raw_array)
ordered_array = simple_select_sort(raw_array)
print("ordered array:",end="")
print(ordered_array)
|
b8325581f857662475b1d8c4fc1065c911d61472 | proishan11/codeforces-problems | /codeforces div2 a/141a_ammusing.py | 263 | 3.75 | 4 | host = input()
guest = input()
shuffled = input()
combined = host+guest
list1 = []
list2 = []
for i in combined:
list1.append(i)
for i in shuffled:
list2.append(i)
list1 = sorted(list1)
list2 = sorted(list2)
if(list1 == list2):
print("YES")
else:
print("NO")
|
6729c7ae1f60d27fb8b2e40008554245efa7bd66 | tsuchan19991218/atcoder_achievement | /atcoder.jp/abc169/abc169_c/Main.py | 147 | 3.5625 | 4 | import math
A, B = input().split()
A = int(A)
B = int(B[0] + B[2] + B[3])
ans = str(A * B)
if len(ans) > 3:
print(ans[:-2])
else:
print(0)
|
8a3bcdff99915a83ef4c527932db3c7dd96292fa | ramyasutraye/Python-6 | /44.py | 89 | 3.90625 | 4 | a=int(input("enter the number"))
if(1<=a<=10):
print("yes")
else:
print("no") |
aecb14522e880757931917018112c04822ea2d89 | Ashwini-sys/Python | /Matplot_Code.py | 6,878 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 21:16:24 2021
@author: khilesh
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
x = [1,2,3,4,5,6,7] # days
y = [25,32, 45, 21, 39, 52, 45] #Sales
plt.plot(x, y)
#you can set the plot title, and lables for x and y axes
x = [1,2,3,4,5, 6, 7] #days
y = [25,32, 45, 21, 39, 52, 45] #Sales
plt.plot(x,y, 'r') #red
plt.xlabel("Days")
plt.ylabel("Sales")
plt.title("Sales per Day")
plt.show()
#------************ Line chart ***********----------
#-------------colrs--------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45] #sales
plt.plot(x,y, 'm') #MAgneta
plt.xlabel("Days")
plt.ylabel("Sales")
plt.title('Sales per day')
plt.show()
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45] #sales
plt.plot(x,y, 'gD')#green dotted-- , hat ^, filled circle 0, Diamond D
plt.xlabel("Days")
plt.ylabel("Sales")
plt.title('Sales per day')
plt.show()
# ----------multilines plot------------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45] #sales
z = [18,30,28, 18, 29, 47, 35]# Sold on Credit
plt.plot(x,y, 'g--')
plt.plot(x,z, 'r')
plt.xlabel("Days")
plt.ylabel('Sales & Credit per Day')
plt.legend(labels= ('Sales', 'credit sales'), loc = 'upper left')
plt.show()
#------------------Sub plot-----------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45] #sales
z = [18,30,28, 18, 29, 47, 35]# Sold on Credit
plt.figure(figsize =(6,4))
fig, (ax1,ax2) = plt.subplots(1,2)
ax1.plot(x,y, 'g--')
ax2.plot(x,z, 'r')
plt.show()
#------------------Sub plot with title-----------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45] #sales
z = [18,30,28, 18, 29, 47, 35]# Sold on Credit
plt.figure(figsize =(6,4))
fig, (ax1,ax2) = plt.subplots(1,2)
ax1.plot(x,y, 'g--')
ax1.set_title("Sales vs Days")
ax2.plot(x,z, 'r')
ax2.set_title("credit vs Days")
plt.show()
#-----------Grid-------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45]#sales
plt.plot(x,y, 'r')#red
plt.xlabel("Days")
plt.ylabel("Sales")
plt.title("Sales per Day")
plt.grid(True)
plt.show()
#-----------Grid-------
x = [1,2,3,4,5,6,7]#days
y = [25,32,45,21,39,52,45]#sales
plt.plot(x,y, 'r', lw = 2)#red
plt.xlabel("Days")
plt.ylabel("Sales")
plt.title("Sales per Day")
plt.grid(color = 'b', ls ='-.', lw =0.35)
plt.show()
#------------Histogram-----------
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a, bins =[0,25,50,75,100])
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no.of students')
plt.show()
#-------------with diff color and bin size 10--------
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a,bins = [0,10,20,30,40,50,60,70,80,90,100], facecolor = 'm')
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
#----------bin size = 20----------#
fig,ax = plt.subplots(1,1)
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
ax.hist(a,bins = [0,20,40,60,80,100], facecolor = 'mediumspringgreen')
ax.set_title("histogram of result")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('marks')
ax.set_ylabel('no. of students')
plt.show()
cs2m =pd.read_csv("D:/data _science/Basic_Notes/Manupuation/cs2m.csv")
cs2m = pd.DataFrame(cs2m)
fig,ax = plt.subplots(1, 1)
ax.hist(cs2m.Age, bins = [0,20,40,60,80,100], facecolor = 'deeppink')
ax.set_title("Histogram of Age")
ax.set_xticks([0,25,50,75,100])
ax.set_xlabel('Age')
ax.set_ylabel('Count ladies')
plt.show()
#----Boxplot-------
import matplotlib.pyplot as plt
import numpy as np
#-------------creating dataset-----------
np.random.seed(10)
data = np.random.normal(100,20,200)
fig = plt.figure(figsize = (10,7))
#creating plot
plt.boxplot(data)
#show plot
plt.show()
#-*************More boxplots*************
data_1 = np.random.normal(100,10,200)
data_2 = np.random.normal(90, 20, 200)
data_3 = np.random.normal(80, 30, 200)
data_4 = np.random.normal(70, 40, 200)
data = [data_1, data_2, data_3, data_4]
fig = plt.figure(figsize= (10,7))
#creating axes instance
ax = fig.add_axes([0,0,1,1])#(xaxis, yaxis, width, height)
#creating plot
bp = ax.boxplot(data, vert = False)
plt.show()
#------Age, cs2m -------
Age = cs2m['Age']
#-------making colorful----
props2 = {'boxes': 'red', 'whiskers': 'green', 'medians': 'black', 'caps': 'blue'}
Age.plot.box(color = props2)
#fiilling whole box with red color
Age.plot.box(color=props2, patch_artist = True, vert = True)
#Horizontal plot, by vert = false
Age.plot.box(color=props2, patch_artist = True, vert = False)
cs2m.boxplot(color = props2, patch_artist = True)
#-------*****Pie chart************----------
# creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES' ]
data = [23, 17, 35, 29, 12, 41]
#creating plot
fig = plt.figure(figsize = (10,7))
plt.pie(data, labels = cars)
plt.show()
#-------pie from df grades---------
grades = pd.read_csv("D:/data _science/Basic_Notes/Manupuation/grades.csv")
grades = pd.DataFrame(grades)
grades.ethnicity.value_counts()
ethnicity = ['Australians', 'Brazilians', 'Americans', 'Chinese', 'Russians']
data = [5,11,20,24,45]
plt.pie(data, labels = ethnicity)
#---------Scatter plot-------
x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
y = [99,86,87,88,100,86,103,87,94,78,77,85,86]
plt.scatter(x, y, c ="blue")
plt.show()
mtcars = pd.read_csv("D:\data _science\PYTHON\Matplot\mtcars.csv")
mtcars = pd.DataFrame(mtcars)
mtcars.info()
plt.scatter(mtcars.hp, mtcars.mpg, c="red",
linewidths = 2,
marker ="o",
edgecolors="k",
s = 200,
alpha= 0.8)
plt.xlabel("Horse Power")
plt.ylabel("Mileage Per Gallan")
plt.title( 'MPG VS HP')
plt.grid()
plt.show()
mtcars.info()
mtcars.cyl.value_counts()
fig, ax = plt.subplots()
colors = {4:'red', 6:'green', 8:'blue'}
grouped = mtcars.groupby('cyl')
for key, group in grouped:
group.plot(ax=ax, kind='scatter', x= 'hp', y ='mpg', label = key, color=colors[key])
plt.xlabel("Horse Power")
plt.ylabel("Mileage Per Gallan")
plt.title( 'MPG VS HP')
plt.grid()
plt.show()
x = mtcars['hp']
y = mtcars['mpg']
colors = {4:'red', 6:'green', 8:'blue'}
plt.scatter(x, y, s = 1.25*mtcars['hp'], alpha=0.8,
c = mtcars['cyl'].map(colors))
plt.xlabel("Horse Power")
plt.ylabel("Mileage Per Gallan")
plt.title( 'MPG VS HP')
plt.grid()
lables = {4:'red', 6:'green', 8:'blue'}
plt.legend(loc='upper right')
plt.show() |
20c45153a1c08971705b77cf04433301d9ca6ebb | saintifly/leetcode | /反转链表.py | 807 | 3.765625 | 4 | class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
if head.next.next==None:
headcurrent=head
head=head.next
headcurrent.next=None
head.next=headcurrent
return head
headbefore=None
headcurrent=head
headnext=headcurrent.next
headcurrent.next=headbefore
while headnext.next!=None:
headbefore=headcurrent
headcurrent=headnext
headnext=headnext.next
headcurrent.next=headbefore
headcurrent.next=headbefore
headnext.next=headcurrent
return headnext
|
d385ddce6da528dabe009561604bcf90573c8d39 | randhir408/sk | /data type.py | 633 | 3.890625 | 4 |
a=range(5)
print(a)
str1="6/2"
print("str1")
a="hello world"
a.isalpha()
print(a)
import random
lst=[1,2,3,100,24,43]
print(random.choice(lst))
print(random.choice(lst))
print(random.choice(lst))
print(random.randrange(1,10))
print(random.randrange(10))
print(random.random())
str3="hello everyone"
print(str3.capitalize())
print(str3.upper())
str4="this is python"
print(str4.count(' '))
print(str4.count('py',1,15))
str5="this is an example"
str6="exam"
print(str5.find(str6))
print(str5.find(str6,13))
string="there"
print(string.isalpha())
print(string.isdigit())
s="table1223"
print(s.isalnum())
list=[1,2,3,4,5,6]
print(list)
|
bccfd2b84963122e2bb03edac1d1948d72b64aaf | Krokette29/Commonly-Used-Programming-Templates-Python | /二叉树/preorderDFS.py | 678 | 3.703125 | 4 | from Tree import *
def preorderDFS_iterative(root: Node):
if not root: return []
res = []
stack = [root]
while stack:
pop = stack.pop()
res.append(pop.val)
if pop.right: stack.append(pop.right)
if pop.left: stack.append(pop.left)
return res
def preorderDFS_recursion(root: Node):
if not root: return []
res = []
def dfs(node):
res.append(node.val)
if node.left: dfs(node.left)
if node.right: dfs(node.right)
dfs(root)
return res
tree = Tree([i for i in range(1, 8)])
res1 = preorderDFS_iterative(tree.root)
res2 = preorderDFS_recursion(tree.root)
tree.draw()
print("preorder using stack: \t\t", res1)
print("preorder using recursion: \t", res2)
|
ca9e609635ce3fbfa00abe40555433542b2ffbb4 | projeto-de-algoritmos/Grafos2_Skyrim_Routes | /dijkstra.py | 1,074 | 3.828125 | 4 | def shortest_path(graph, start, target):
path = []
visited = []
temp_parents = {}
to_visit = [start]
distances = {key : float("inf") for key in graph.get_vertices()}
distances[start] = 0
final_distance = 0
while to_visit:
current = min([(distances[vertex], vertex) for vertex in to_visit])[1]
if current == target:
break
visited.append(current)
to_visit.remove(current)
for neighbour, distance in graph.get_neighbors()[current].items():
if neighbour in visited:
continue
vertex_distance = distances[current] + distance
if vertex_distance < distances[neighbour]:
distances[neighbour] = vertex_distance
temp_parents[neighbour] = current
to_visit.append(neighbour)
final_distance = distances[target]
if target not in temp_parents:
return []
while target:
path.append(target)
target = temp_parents.get(target)
return path[::-1] + [final_distance]
|
434bb2b9078e494f98a9f34157628932a6f50a0d | pierrerousseau/games | /matrix/rotate.py | 1,366 | 4.15625 | 4 | """ Given an image represented by an NxN matrix, write a method to rotate the
image by 90 degrees. Can you do this in place?
from : Craking the Coding Interview, 4th edition, Gayle Laakmann
"""
from matrix import to_str
def rotate(matrix, depth=0):
""" :returns: the matrix after rotation by 90 degrees
:param list matrix: a matrix
"""
last = len(matrix) - depth - 1
if last:
for index in range(depth, last):
lastindex = last - index + depth
tmp = matrix[depth][index]
matrix[depth][index] = matrix[index][last]
matrix[index][last] = matrix[last][lastindex]
matrix[last][lastindex] = matrix[lastindex][depth]
matrix[lastindex][depth] = tmp
rotate(matrix, depth + 1)
return matrix
def answer(matrix):
""" :returns: a readable answer
:param list matrix: a matrix
"""
str_matrix = to_str(matrix)
rotate(matrix)
str_rotated = to_str(matrix)
return "{} \n rotated is \n\n{}".format(str_matrix, str_rotated)
if __name__ == "__main__":
mat = [
[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[29, 30, 31, 32, 33, 34],
]
print(answer(mat))
|
ef7f1e63a8d52ca96f2026d3229f53b32f9b7c35 | LinkWoong/LC-Solutions | /DynamicProgramming/Medium_UniquePathII_63_WYH.py | 1,765 | 3.609375 | 4 |
# coding: utf-8
# In[ ]:
#算法思路:
#这道题跟上道题类似
#也是用动态规划做的
#dp[m][n]同样代表着走到(m,n)的unique paths的数量
#基本思路也是加上上面一个和左边一个dp的值
#但这里要加上对block是否存在的判断:
#如果block存在,则这个地方的可达到的unique path的数量为零
class Solution():
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# If the starting cell has an obstacle, then simply return as there would be
# no paths to the destination.
if obstacleGrid[0][0] == 1:
return 0
# Number of ways of reaching the starting cell = 1.
obstacleGrid[0][0] = 1
# Filling the values for the first column
for i in range(1,m):
obstacleGrid[i][0] = int(obstacleGrid[i][0] == 0 and obstacleGrid[i-1][0] == 1)
# Filling the values for the first row
for j in range(1, n):
obstacleGrid[0][j] = int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j-1] == 1)
# Starting from cell(1,1) fill up the values
# No. of ways of reaching cell[i][j] = cell[i - 1][j] + cell[i][j - 1]
# i.e. From above and left.
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] == 0:
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
else:
obstacleGrid[i][j] = 0
# Return value stored in rightmost bottommost cell. That is the destination.
return obstacleGrid[m-1][n-1]
|
74cc7cc3ecad059537cb0ed42e36a1ad37002e3d | DPontes/AdventofCode | /2018/Day2/pt2-commonLetters.py | 709 | 3.890625 | 4 | #!/usr/bin/python
def getCommonChars(str1, str2):
# Returns a string of unique chars of the input strings
uniqueList = []
for elem1, elem2 in zip(str1, str2):
if elem1 == elem2:
uniqueList.append(elem1)
if len(uniqueList) == (len(str1) - 1):
return ''.join(uniqueList)
else:
return 0
def loopThrough():
f = open('input.txt').readlines()
# TODO(diogo): This double loop can be expressed in a better way
for str1 in f:
for str2 in f:
uniqueString = getCommonChars(str1, str2)
if uniqueString:
return uniqueString
return "No result"
if __name__ == '__main__':
print(loopThrough())
|
0f924e7a3ed8f4a3783103cd0d2097334eccb5a3 | tonylixu/devops | /algorithm/507-perfect-number/solution2.py | 398 | 3.546875 | 4 | def check_perfect_numer(num):
if num <=1 or num > 100000000:
return False
nums = [1]
for i in range(2, int(num**0.5)+1):
if num % i == 0 and i not in nums:
nums.append(i)
nums.append(num/i)
print nums
if sum(nums) == num:
return True
return False
if __name__ == '__main__':
num = 28
print check_perfect_numer(num) |
c93a61d9a737833a5dc91ce7c0d20b0bc1bdc403 | TrellixVulnTeam/pythonclass_23WQ | /NumberEvenOdd.py | 267 | 4.125 | 4 | iNum = int(input("Enter a Number: "))
#iNum = int(Num)
if iNum < 0:
print("It is a Negative Number")
if iNum > 0:
print("It is a Positive Number")
else:
print("It is a ZERO")
if iNum % 2 == 0:
print(" and even")
else:
print(" and odd")
|
20c24f0d99f99dd0bdae93517634ef1cc9ab65ab | csc201spring2016/2016spr_csc201_program01 | /program01.py | 253 | 4.25 | 4 | #Half Pyramid
#user input
user_input = input("Enter a word")
user_input = user_input.lower()
#while loop to check if the user entered the word stop
while(user_input != "stop"):
user_input = input("Enter a word")
user_input = user_input.lower()
|
ea4f233b5df637662a17dc3d2c8dac93fba857a3 | walidAbbassi/python_Utils | /src/algorithm(leetcode题库)/删除排序数组中的重复项.py | 1,115 | 3.734375 | 4 | #!/user/bin python
# -*- coding:utf-8 -*-
import sys
import os
class Solution:
@classmethod
def removeDuplicates(cls, nums):
"""
:type nums: List[int]
:rtype: int
"""
data = set()
i = 0
while i < len(nums):
try:
if nums[i] not in data:
data.add(nums[i])
else:
del nums[i]
continue
except IndexError:
break
else:
i += 1
return len(nums)
def removeDuplicates1(self, nums: list):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
while True:
try:
a = nums[i]
b = nums[i + 1]
except:
break
else:
if a == b:
del nums[i + 1]
else:
i += 1
return len(nums)
if __name__ == '__main__':
s = Solution()
print(s.removeDuplicates1([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
|
127b0917f97c67dca4f5e42d5428b21c4ec59c01 | Oliunin/Djbootcamp | /12-Python_Level_One/ex15/func.py | 519 | 3.796875 | 4 | def my_func(par1="awesome"):
"""
DOCSTRING
"""
return "my_func"+par1
def addNum (num1=1,num2=2):
if type(num1)==type(num2)==int:
return num1+num2
else:
return "need integers"
my_func()
print(type(addNum(2,4)),addNum(2,4))
#lambda expression
#filter
mylist = [1,2,3,4,5,6,7,8]
def even_bool(num):
return num%2 == 0
evens = filter(even_bool,mylist)
print("filter check:",list(evens))
evens = filter(lambda num:num%2 == 0,mylist)
print("lambda func result:",list(evens))
|
0f75cbb5a8ac162ece9bd8426c6d51f7a9c93742 | nkukarl/leetcode | /remove_duplicates_from_sorted_list_ii.py | 823 | 3.578125 | 4 | from utils_linked_list import ListNode
class Solution(object):
def delete_duplicates(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(head.val - 1)
tail = dummy
node = head
while node is not None:
if node.next is None:
tail.next = node
node = node.next
else:
if node.next.val != node.val:
next_ = node.next
tail.next = node
tail = node
tail.next = None
node = next_
else:
cur_val = node.val
while node is not None and node.val == cur_val:
node = node.next
return dummy.next
|
0c610daf385feb66679d8d1ef3b9a5f7d971f154 | gutierrezOrlando/cursoPhyton | /ejercicio3.py | 265 | 3.828125 | 4 | prueba1=float(input("Ingresa la nota 1 "))
prueba2=float(input("Ingresa la nota 2 "))
prueba3=float(input("Ingresa la nota 3 "))
examen=float(input("Ingresa la nota del examen: "))
promedio=(prueba1*0.2+prueba2*0.2+prueba3*0.2+examen*0.4)>=4.0
print(promedio)
|
d05fef04df408f4842b9b3e60465942ac5994912 | Uday-Vulchi/UVa_Solutions | /secret_research.py | 305 | 3.78125 | 4 | T=int(input())
while(T):
i=input()
if (i == "1" or i == "4" or i == "78"):
print('+')
elif (i[len(i) - 2] == '3' and i[len(i) - 1] == '5'):
print('-')
elif (i[0] == '9' and i[len(i) - 1] == '4'):
print('*')
else:
print('?')
T-=1
|
6039d4ea450ee59729bb5b75870fab8c098ac23a | Andrew-Kelley/Age_of_kingdoms | /map_etc/iterate_around.py | 4,949 | 3.8125 | 4 | from map_etc.position import Position, Vector
from map_etc.make_map import game_map
def within_given_distance(obj1, obj2, distance):
vector = obj1.position - obj2.position
return vector.magnitude <= distance
def everything_within_given_distance_on(the_map, distance, position):
"""Iterates through everything on the_map.bldngs_n_rsrcs that is
within the given distance of position.
This portion of the_map is in the shape of a diamond.
position must be of type Position
distance must be a non-negative int"""
if not type(distance) is int:
print('distance must be an int')
return
if distance < 0:
print('distance must not be negative')
return
# The following is the center of the diamond-shaped portion of the map.
x0, y0 = position.value
# The following iterates through the diamond shaped portion of the_map
# from bottom to top, left to right.
for y_delta in range(-1 * distance, distance + 1):
sign_to_mult_by = 1 if y_delta <= 0 else -1
horizontal_radius = distance + y_delta * sign_to_mult_by
# height is how far up or down the map, we need to go
for x_delta in range(-1 * horizontal_radius, horizontal_radius + 1):
x = x0 + x_delta
y = y0 + y_delta
this_position = Position(x, y)
if this_position.is_on_the_map(the_map):
yield the_map.bldngs_n_rsrcs[y][x]
def positions_around(center, radius):
"""An iterator of all positions within radius of center.
This first starts with the center and then goes around
and around going further and further out.
center must be an instance of Position"""
if not type(radius) is int:
print('radius must be an int')
return
if radius < 0:
print('radius must not be negative')
return
if not center.is_on_the_map(game_map):
return
yield center
for distance in range(1, radius+1):
for position in down_left(center, distance):
yield position
for position in down_right(center, distance):
yield position
for position in up_right(center, distance):
yield position
for position in up_left(center, distance):
yield position
# The following implements down_left, down_right, up_right, and up_left
def traverse_side(offset, delta):
"""Start at center + offset and traverse side of diamond
This excludes the last vertex at the end of the side."""
def iterator(center, distance):
start = center + offset * distance
for i in range(distance):
current = start + delta * i
if not current.is_on_the_map(game_map):
continue
yield current
return iterator
# For equivalent code, see the commented section
down_left = traverse_side(Vector(0, 1), Vector(-1, -1))
down_right = traverse_side(Vector(-1, 0), Vector(1, -1))
up_right = traverse_side(Vector(0, -1), Vector(1, 1))
up_left = traverse_side(Vector(1, 0), Vector(-1, 1))
# def down_left(center, distance):
# """start at the top and go down to the left
# but stop before the far left point.
#
# Each point this yields is exactly distance away form center.
# The length of this side of the diamond is distance"""
# start = center + Vector(0, distance)
# for i in range(distance):
# current = start + Vector(-i, -i)
# if not current.is_on_the_map(game_map):
# continue
# yield current
#
# def down_right(center, distance):
# """start at the far left and go down to the right
# but stop before the bottom point."""
# start = center + Vector(-distance, 0)
# for i in range(distance):
# current = start + Vector(i, -i)
# if not current.is_on_the_map(game_map):
# continue
# yield current
#
# def up_right(center, distance):
# """start at the bottom and go up to the right
# but stop before the far right point."""
# start = center + Vector(0,-distance)
# for i in range(distance):
# current = start + Vector(i, i)
# if not current.is_on_the_map(game_map):
# continue
# yield current
#
# def up_left(center, distance):
# """start at the far right and go up to the left
# but stop before the top point."""
# start = center + Vector(distance, 0)
# for i in range(distance):
# current = start + Vector(-i, i)
# if not current.is_on_the_map(game_map):
# continue
# yield current
if __name__ == '__main__':
# Testing the function positions_around
from time import sleep
center = Position(70, 70)
for position in positions_around(center, radius = 4):
x, y = position.value
game_map.bldngs_n_rsrcs[y][x] = '*'
game_map.print_centered_at(center, width = 20, height = 20 )
sleep(.2) |
84af77fbe6f79452f58c483f037e08764ce0733f | junque1r4/treino.py | /Py3Guanabara/des060.py | 272 | 3.921875 | 4 | # fatorial
número = int(input('Qual o número deseja tirar o fatorial: '))
contador = número
fatoração = 1
while contador > 0:
print(f'{contador}', end='')
print(' x ' if contador > 1 else ' = ', end='')
fatoração *= contador
contador -= 1
print(fatoração)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.