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 |
|---|---|---|---|---|---|---|
2641fb80715dea3da84a463c049dea07dff806eb | Xmn0721/MTA-python | /Day2-3或5的倍數.py | 154 | 3.796875 | 4 | for i in range(1,101):
if i%3==0 or i%5==0:
print("i=",i)
j=1
while j<=100:
if j%3!=0 and j%5!=0:
print("j=",j)
j=j+1 |
7362bc098ff06e3db45916f1b10266703127220f | kj0y/edX-MITx-6.00.1x | /Wk3 Ex how many.py | 423 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 16 18:24:25 2018
@author: Kandis
"""
aDict = {'B': [15], 'u': [10, 15, 5, 2, 6]}
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
x = 0
for i in aDict.values():
for word in i:
x += 1
return x
print(how_many(aDict)) |
1fc4167135d40d27a43c4b9570ce65ca803e27ce | hexcity/snippets | /py/peterwashere.py | 397 | 3.546875 | 4 | #!/usr/bin/env python3
'''
@author: Peter Howlett
@description: Across the screen
'''
from time import sleep
import time
str = "Peter Was Here"
columns = 79
sleeptime = 0.05
while True:
for col in range(len(str),columns):
print(str.rjust(col))
time.sleep(sleeptime)
for coly in range(columns,len(str),-1):
print(str.rjust(coly))
time.sleep(sleeptime)
exit()
|
d58d5405b1626cc7121f8f0e1cffb8a9fab0ca04 | suyalmukesh/python | /HackerRank/linked_list.py | 738 | 4.03125 | 4 | import sys
class node:
def __init__(self,val):
self.val = val
self.next = None
def traverse(self,a):
while(a != None):
print(a.val)
a = a.next
def add_to_last(self,node):
while(self != None):
self = self.next
self.next = node
def delete_last(self):
while(self.next.next != None):
self.next = None
def print_backward(self,list):
if list is None: return
head = list
tail = list.next
list.print_backward(tail)
print(head, end=" ")
if __name__ == '__main__':
a = node(5)
b = node(5)
c = node(6)
a.next = b
b.next = c
a.traverse(a)
c.print_backward(c)
|
8fd5268f63a2e24fd57bdceea53c81a75f82eb16 | nicowjy/practice | /JianzhiOffer/43把数组排成最小的数.py | 1,113 | 4.09375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2019-07-17 23:22:39
# @Author : Nico
# @File : 把数组排成最小的数
"""
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
"""
class Solution:
def PrintMinNumber(self, numbers):
# write code here
res = ''
if not numbers:
return res
tmp = sorted(numbers, cmp = lambda x,y: self.Compare(x, y)) # O(nlogn)
for item in tmp:
res += str(item)
return res
def Compare(self, num1, num2): # 定义新的比较函数
a = str(num1)+str(num2)
b = str(num2)+str(num1)
while a and b:
if a[0] > b[0]:
return 1
elif a[0] < b[0]:
return -1
else:
a = a[1:]
b = b[1:]
return 0
'''
comment
注意一下sorted函数中cmp参数的用法
''' |
92ba8108566ae9aa8060e0c6220d779506770847 | samuelhwolfe/pythonPractice | /programs/loops/triangle.py | 166 | 3.734375 | 4 |
for x in range(6):
for y in range(x):
print('*', end='')
print()
for x in range(4):
for y in range(4-x):
print('*', end='')
print()
|
b53308154172f2e410142464b3afe98b9a1cc36d | AdriBird/SiteWeb | /projet HTML 1.0/Exercices/Boucles/exercice40.py | 792 | 3.6875 | 4 | from random import *
def choix_nombre(min, max):
nombre = randint(min, max)
print("L'ordinateur a trouvé son nombre")
return nombre
alea = choix_nombre(int(input("Chiffre minimum: ")), int(input("Chiffre maximum: ")))
def jeu(hypothèse):
trouve = 1
while trouve == 1:
if hypothèse > alea:
print("plus petit!")
hypothèse = int(input("Dommage! Retente ta chance: "))
if hypothèse < alea:
print("Plus grand!")
hypothèse = int(input("Dommage! Retente ta chance: "))
if hypothèse == alea:
print("Bien joué, tu as trouvé le bon nombre!")
trouve = 0
jeu(int(input("Choisis un nombre: ")))
"GG bg t'as trouvé le nombre caché! Tu as gagné ma fierté !" |
ebeb3c800b32ef0160f7de729e2ec2926c8de19b | sasidharan2303/Python-project | /Error_Free_main_ prog.py | 9,304 | 4.28125 | 4 | ### DEFINING FUNCTION FOR ARITHMETIC OPERATIONS ###
def Arithmetic():
try:
if choice_1 == 1:
## Printing Instructions of Arithmetic Opearations ##
print('*************************************')
print(' Enter 1 for Addition Operation\n','Enter 2 for Subtraction Operation\n','Enter 3 for Multiplication Operation\n','Enter 4 for Division Operation\n','Enter 5 for Floor_Division Operation\n','Enter 6 for Modulus Operation\n','Enter 7 for Exponetial Operation')
print('*************************************\n')
while True:
try:
choice_2 = int(input('Enter Your Choice :')) ## Getting choice from user to perform Arithmetic Operations
if choice_2 <= 7:
try:
if choice_2 == 1:
error_free.add()
if choice_2 == 2:
error_free.sub()
if choice_2 == 3:
error_free.mul()
if choice_2 == 4:
error_free.div()
if choice_2 == 5:
error_free.f_div()
if choice_2 == 6:
error_free.mod()
if choice_2 == 7:
error_free.exp()
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\nThere is no choice like',choice_2,'in given instruction..','\nKindly enter valid choice..!!\n')
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('/// You Have Choosen Nothing ///\n')
except ValueError:
print('ValueError Raised..!!','\nPlease Enter Valid Number\n')
### DEFINING FUNCTION FOR TRIGNOMETRIC OPERATIONS ###
def Trignometric():
try:
if choice_1 == 2:
## Printing Instructions of Trignometric Opearations ##
print('*************************************\n')
print(' Enter 1 for Log Operation\n','Enter 2 for Sin Operation\n','Enter 3 for Cos Operation\n','Enter 4 for Tan Operation\n')
print('*************************************\n')
while True:
try:
choice_3 = int(input('Enter Your Choice :')) ## Getting choice from user to perform Arithmetic Operations
if choice_3 <= 4:
try:
if choice_3 == 1:
error_free.log()
if choice_3 == 2:
error_free.sin()
if choice_3 == 3:
error_free.cos()
if choice_3 == 4:
error_free.tan()
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\nThere is no choice like',choice_3,'in given instruction..','\nKindly enter valid choice..!!\n')
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('/// You Have Choosen Nothing ///\n')
except ValueError:
print('ValueError Raised..!!','\nPlease Enter Valid Number\n')
### DEFINING FUNCTION FOR TIME_CONVERSION OPERATION ###
def Timeconversion():
try:
if choice_1 == 3:
## Printing Instructions of Timeconversion Opearations ##
print('*****************************************')
print(' Enter 1 for Hours_to_Minutes Operations\n','Enter 2 for Minutes_to_Hours Operation\n','Enter 3 for Seconds_to_Hours Operation\n','Enter 4 for Hours_to_Seconds Operation\n','Enter 5 for Seconds_to_Minutes Operation\n','Enter 6 for Minutes_to_Seconds Operation\n')
print('*****************************************\n')
while True:
try:
choice_4 = int(input('Enter Your Choice :')) ## Getting choice from user to perform Arithmetic Operations
if choice_4 <= 6:
try:
if choice_4 == 1:
error_free.h2m()
if choice_4 == 2:
error_free.m2h()
if choice_4 == 3:
error_free.s2h()
if choice_4 == 4:
error_free.h2s()
if choice_4 == 5:
error_free.s2m()
if choice_4 == 6:
error_free.m2s()
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\nThere is no choice like',choice_4,'in given instruction..','\nKindly enter valid choice..!!\n')
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\n/// You Have Choosen Nothing ///')
except ValueError:
print('ValueError Raised..!!','\nPlease Enter Valid Number\n')
### DEFINING FUNCTION FOR CURRENCY_CONVERSION OPERATION ###
def currency():
try:
if choice_1 == 4:
## Printing Instructions of Timeconversion Opearations ##
print('*********************************')
print(' Enter 1 for Rupees to Dollars\n','Enter 2 for Dollars to Rupees\n','Enter 3 for Rupees to Euro\n','Enter 4 for Euro to Rupees\n','Enter 5 for Dollars to Euro\n','Enter 6 for Euro to Dollars\n')
print('*********************************\n')
while True:
try:
choice_5 = int(input('Enter Your Choice :')) ## Getting choice from user to perform Arithmetic Operations
if choice_5 <= 6:
try:
if choice_5 == 1:
error_free.INR_to_USD()
if choice_5 == 2:
error_free.USD_to_INR()
if choice_5 == 3:
error_free.INR_to_EUR()
if choice_5 == 4:
error_free.EUR_to_INR()
if choice_5 == 5:
error_free.USD_to_EUR()
if choice_5 == 6:
error_free.EUR_to_USD()()
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\nThere is no choice like',choice_5,'in given instruction..','\nKindly enter valid choice..!!\n')
except ValueError:
print('Value Error Raised','\nPlease Read The Instruction And Enter Valid Choice\n')
else:
print('\n/// You Have Choosen Nothing ///')
except ValueError:
print('ValueError Raised..!!','\nPlease Enter Valid Number\n')
## Importing package ##
import error_free
## Printing Instructions ##
print('*********************************************')
print(' Enter 1 for Arithmatic operations\n','Enter 2 for Trignometric Operations\n','Enter 3 for Time_conversion operations\n','Enter 4 for Currency_conversion operations')
print('*********************************************\n')
## Getting choice from user ##
while 1:
try:
choice_1 = int(input('Enter Your Choice :'))
if choice_1 <= 4:
if choice_1 == 1:
while 1:
Arithmetic() ## Function call of Arithmetic Operations
if choice_1 == 2:
while 1:
Trignometric() ## Function call of Trignometric Operations
if choice_1 == 3:
while 1:
Timeconversion() ## Function call of Time_conversion Operations
if choice_1 == 4:
while 1:
currency() ## Function call of Currency_conversion Operations
else:
print('\nThere is no choice like',choice_1,'in given instruction..','\nKindly enter valid choice..!!\n')
except ValueError:
print('ValueError Raised..!!','\nPlease Enter Valid Number Within (1 to 4) As per the Instructions..\n')
|
f3539ee122a3c75fb2dda2bfe4fd93fb027f732f | omelchert/MCS2012 | /MCS2012_Melchert_LectureMST_supplMat/MCS2012_mstKruskal.py~ | 2,766 | 3.75 | 4 | ## \file MCS2012_mstKruskal.py
# \brief implementation of Kruskals minimum weight
# spanning tree algorithm using a union
# find data structure
#
# \author OM
# \date 12.06.2012
class unionFind_cls:
"""union find data structure that implemnts
union-by-size
"""
def __init__(self):
self.nSets = 0
self.root = dict()
self.size = dict()
self.mySet = dict()
def makeSet(self,i):
self.mySet[i]=set()
self.mySet[i].add(i)
self.root[i] = i
self.size[i] = 1
self.nSets += 1
def find(self,i):
while(i!=self.root[i]):
i = self.root[i]
return i
def union(self,i,j):
if self.size[i]<self.size[j]:
dum = i; i=j; j=dum
self.root[j] =i
self.size[i]+= self.size[j]
self.size[j] =0
self.nSets -=1
self.mySet[i].union(self.mySet[j])
del self.mySet[j]
def mstKruskal(G):
"""Kruskals minimum spanning tree algorithm
algorithm for computing a minimum spanning
tree T=(V,E') for a connected, undirected and weighted
graph G=(V,E,w) as explained in
'Introduction to Algorithms',
Cormen, Leiserson, Rivest, Stein,
Chapter 23.2 on 'The algorithms of Kruskal and Prim'
Input:
G - weighted graph data structure
Returns: (T,wgt)
T - minimum spanning tree stored as edge list
wgt - weight of minimum weight spanning tree
"""
uf = unionFind_cls()
T=[]
K = sorted(G.E,cmp=lambda e1,e2: cmp(G.wgt(e1),G.wgt(e2)))
for i in G.V:
uf.makeSet(i)
for (v,w) in K:
if uf.find(v)!=uf.find(w):
uf.union(uf.find(v),uf.find(w))
T.append((v,w))
return T, sum(map(lambda e: G.wgt(e),T))
def mstGraphviz(G,T):
"""print graph in graphviz format
"""
string = 'graph G {\
\n rankdir=LR;\
\n node [shape = circle,size=0.5];\
\n // graph attributes:\
\n // nNodes=%d\
\n // nEdges=%d\
\n'%(G.nNodes,G.nEdges)
string += '\n // node-list:\n'
for n in G.V:
string += ' %s; // deg=%d\n'%\
(str(n),G.deg(n))
string += '\n // edge-list:\n'
for n1 in G.V:
for n2 in G.adjList(n1):
if n1<n2:
myStyle="setlinewidth(3)"; myColor='grey'
if tuple(sorted([n1,n2])) in T: myStyle="setlinewidth(6)"; myColor='black'
string += ' %s -- %s [style=\"%s\",label=%d,len=1.5,color=\"%s\"];\n'%\
(str(n1),str(n2),myStyle,int(G.wgt((n1,n2))),myColor)
string += '}'
return string
# EOF: MCS2012_mstKruskal.py
|
7ac4f56c4b647e80629b82b3e3b0369b7d1463bf | daniel-reich/ubiquitous-fiesta | /YEwPHzQ5XJCafCQmE_10.py | 55 | 3.5 | 4 |
def odd_or_even(word):
return (len(word) % 2 == 0)
|
6f1acba32e37f91b5b0635aeecc293add7e31b9b | vimalkkumar/Basics-of-Python | /Functions.py | 3,298 | 4.375 | 4 | """
Syntax Location Interpretation
func(value) Caller Normal argument: matched by position
func(name=value) Caller Keyword argument: matched by name
func(*name) Caller Pass all objects in name as individual positional arguments
func(**name) Caller Pass all key/value pairs in name as individual keyword arguments
def func(name) Function Normal argument: matches any by position or name
def func(name=value) Function Default argument value, if not passed in the call
def func(*name) Function Matches and collects remaining positional arguments (in a tuple)
def func(**name) Function Matches and collects remaining keyword arguments (in a dictionary)
"""
def fun():
print("Python function is useful")
fun()
print(fun()) # function return type is None
# def addition(num_first, num_second): # Parameter in function
# num_sum = num_first + num_second
# print('Sum of {} and {} is {}'.format(num_first, num_second, num_sum))
#
#
# addition(num_first=10, num_second=20)
#
# def addition(num_first, num_second): # Parameter in function
# return num_first + num_second
# # print('Sum of {} and {} is {}'.format(num_first, num_second, num_sum))
#
#
# print(addition(num_first=10, num_second=20))
# print(addition(20, 20))
# one = int(input("enter first number :"))
# two = int(input("enter second number :"))
# print("Sum of {} and {} is {}.".format(one, two, addition(one, two)))
#
# def center_text(text):
# text = str(text)
# left_margin = (100 - len(text)) // 2
# print(" " * left_margin, text)
#
#
# center_text("Hello, World")
# center_text("How the things going on")
# center_text("Hope, Everything going in the thoughtful direction")
# center_text(12)
# center_text("*")
# def center_text(*args):
# text = ""
# for arg in args:
# text += str(arg) + " "
# left_margin = (100 - len(text)) // 2
# print(" " * left_margin, text)
# def center_text(*args, sep=' ', end='\n', file=None, flush=False): # Like print function
# text = ""
# for arg in args:
# text += str(arg) + sep
# left_margin = (100 - len(text)) // 2
# print(" " * left_margin, text, end=end, file=file, flush=flush)
# center_text("Hello, World")
# center_text("How the things going on")
# center_text("Hope " + "Everything going in the thoughtful direction", 15, "Wind mill")
# center_text(12)
# center_text("*")
# def center_text(*args):
# text = ""
# for arg in args:
# text += str(arg) + " "
# left_margin = (100 - len(text)) // 2
# return " " * left_margin + text
# with open("centerText", "w") as centerFile:
# s1 = center_text("Hello, World")
# print(s1, file=centerFile)
# s2 = center_text("How the things going on")
# print(s2, file=centerFile)
# s3 = center_text("Hope " + "Everything going in the thoughtful direction", 15, "Wind mill")
# print(s3, file=centerFile)
# s4 = center_text(12)
# print(s4, file=centerFile)
# with open("centerText", 'r') as centerFile:
# lines = centerFile.readlines()
# for line in lines:
# print(line, end='')
|
cfb6176ed79332b02c7710bdcc10b4ed5931b635 | daniel-reich/ubiquitous-fiesta | /k9usvZ8wfty4HwqX2_4.py | 313 | 3.71875 | 4 |
def cuban_prime(n):
root = (3 + (12*n - 3)**0.5) / 6
return '{} {} cuban prime'.format(n, 'is' if is_prime(n) and root == int(root) else 'is not')
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if not n%i:
return False
return True
|
ccc3f65eedf05af4aeb8070969eda82b4d7a57f9 | noorul90/Python_Learnings | /Arrays.py | 647 | 3.84375 | 4 | #array will contain all the value of same type unlike list, in python aarays are not fix in side unlike java, u can expand and shrink it
from array import *
vals = array('i', [1,2,5,6])
print(vals)
#creating new array from existing one
newArray = array(vals.typecode, (a*a for a in vals))
print("new array ", newArray)
#print(vals.buffer_info()) #output format is (address, array_size)
#print(vals.typecode)
#vals.reverse()
#print(vals)
print(vals[0])
for i in range(len(vals)):
print(vals[i])
#OR
for e in vals:
print(e)
#declaring char arrays
chararr = array('u', ['a','b', 'c', 'd'])
print(chararr)
for ch in chararr:
print(ch) |
3808f5356c4f63045b0809bf2564e3c8ec4ac574 | valeriacavalcanti/IP-2020.2---R | /semana_18/01_1006_adaptado.py | 276 | 3.90625 | 4 | n1 = int(input('Nota 1: '))
n2 = int(input('Nota 2: '))
n3 = int(input('Nota 3: '))
media = ((n1 * 3) + (n2 * 3) + (n3 * 4)) / 10
print("Média = {}".format(media))
if (media >= 70):
print("Aprovado")
elif (media >= 40):
print("Final")
else:
print("Reprovado")
|
8431f9e4a5aa4783656aa9ff7cfa8dfdf9ba1c1b | gabriel-valenga/CursoEmVideoPython | /ex030.py | 199 | 3.90625 | 4 | from random import randint
numeroDigitado = int(input('Adivinhe o número entre 0 e 5:'))
numeroSorteado = randint(0,5)
print('Você acertou' if numeroDigitado == numeroSorteado else 'Você Errou')
|
5f1b3bc2f31499c6f0a9fe27c78a3cd3745ad250 | camcottle/Game-Public | /game1.py | 2,609 | 4.21875 | 4 | print ("Welcome to Chose your own adventure python edition")
print ("")
def playerNames():
playerNum = int(input("How many players are playing? "))
print(playerNum)
# Great place to consider using a for loop
if playerNum == 1:
player1 = input("What is player one's first name? ")
print("Welcome ", player1, "!")
elif playerNum == 2:
player1 = input("What is player one's first name? ")
player2 = input("What is player two's first name? ")
print("Welcome ", player1, "&", player2, "!")
elif playerNum == 3:
player1 = input("What is player one's first name? ")
player2 = input("What is player two's first name? ")
player3 = input("What is player three's first name? ")
print("Welcome ", player1, ",", player2, "&", player3, "!")
elif playerNum == 4:
player1 = input("What is player one's first name? ")
player2 = input("What is player two's first name? ")
player3 = input("What is player three's first name? ")
player4 = input("What is player four's first name? ")
print("Welcome ", player1, ",", player2, ",", player3, ",", player4, "!")
elif playerNum >= 5:
print ("I am sorry unfortunately only four players are permitted.")
def characters():
### Artibuttes each char will have: Name, Dice(1-2), Acceptable Dice Values(each dice has a seperate value), Role type(Builder,Recruiter,Both(Builder and Recruiter)), current state(available,active, tired, injured),which player controls them(determined by how many players in the game, and if unowned their cost if they are avail for purchase)
continueCreation = input("do you have a char to create? ").lower()
charNames = []
charDice = []
charRole = []
if continueCreation == "yes":
getCharNames = input("Enter Next Char name ")
getCharDice = input("Please enter the number of dice this char will use. ")
getCharRole = input("Please enter the villagers role. ")
charNames.append(getCharNames)
charDice.append(getCharDice)
charRole.append(getCharRole)
print (charNames)
print (charRole)
print (charDice)
continueCreationNext = input("Do you have another char to enter? ").lower()
if continueCreationNext == "yes":
characters()
else:
print("Thanks for entering these chars" )
else:
print("Thanks for entering these chars" )
# diceNumber = int(input("How many dice does this character have? "))
playerNames()
characters()
|
cbc0f8bbc42f763a44c67b7afa4a83f53b21b23d | djaychela/PythonWorkBook | /25.py | 83 | 3.546875 | 4 | from string import ascii_lowercase
for letter in ascii_lowercase:
print(letter) |
e33c09ec8df35d64028ac7c749375631a2063f2b | vit6556/sudoku | /classes/sudoku_board.py | 5,662 | 3.59375 | 4 | import os, itertools
from random import shuffle, randint
from copy import deepcopy
sudoku_banner = " ____ _ _\n/ ___| _ _ __| | ___ | | ___ _\n\___ \| | | |/ _` |/ _ \| |/ / | | |\n ___) | |_| | (_| | (_) | <| |_| |\n|____/ \__,_|\__,_|\___/|_|\_\\\__,_|\n"
class SudokuBoard:
def __init__(self, amount_of_filled_cells):
self.__board = [[0] * 9 for _ in range(9)]
self.__number_list = [i for i in range(1, 10)]
self.__message_to_show = ""
self.__fill_board(deepcopy(self.__board))
self.__delete_numbers(amount_of_filled_cells)
self.__start_board = deepcopy(self.__board)
self.__players_steps = []
def return_to_start_board(self):
self.__board = deepcopy(self.__start_board)
self.__players_steps = []
def next_solution_step(self):
step = self.__solution[0]
del self.__solution[0]
return step
def __clear(self):
os.system('cls' if os.name=='nt' else 'clear')
def add_message_to_show(self, message):
self.__message_to_show = message
def show(self):
self.__clear()
print(sudoku_banner)
for i in range(len(self.__board)):
if i % 3 == 0:
if i == 0:
print(" ----------------------- ")
else:
print("|-------+-------+-------|")
for j in range(len(self.__board[i])):
if j % 3 == 0:
print("| ", end="")
if self.__board[i][j] != 0:
print(self.__board[i][j], end="")
else:
print(".", end="")
if j == 8:
print(" |\n", end="")
else:
print(" ", end="")
if i == 8:
print(" ----------------------- ")
if self.__message_to_show != "":
print(self.__message_to_show)
self.__message_to_show = ""
def put_value(self, x, y, val):
if (x < 0 or x > 8 or y < 0 or y > 8 or val < 1 or val > 9):
self.__message_to_show = "Все числа должны находиться в диапазоне от 1 до 9"
elif self.__board[x][y] != 0:
self.__message_to_show = "В этой клетке уже есть число, выберите другую"
else:
self.__board[x][y] = val
self.__players_steps.append((x, y))
def delete_last_player_step(self):
if len(self.__players_steps) == 0:
return False
else:
row, col = self.__players_steps[-1][0], self.__players_steps[-1][1]
self.__board[row][col] = 0
del self.__players_steps[-1]
self.show()
return True
def board_full(self):
for line in self.__board:
if 0 in line:
return False
return True
def check_cell_empty(self, row, col):
return self.__board[row][col] == 0
def __valid(self, board, value, row, col):
for i in range(len(board[0])):
if board[row][i] == value and col != i:
return False
for j in range(9):
if board[j][col] == value:
return False
square_x = col // 3
square_y = row // 3
for i in range(square_y * 3, square_y * 3 + 3):
for j in range(square_x * 3, square_x * 3 + 3):
if board[i][j] == value and (i, j) != (row, col):
return False
return True
def __find_empty(self, board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
def __fill_board(self, board, solution=[], find_solution=False):
pos = self.__find_empty(board)
if not pos:
self.__board = deepcopy(board)
self.__solution = deepcopy(solution)
shuffle(self.__solution)
return True
else:
row, col = pos
if board[row][col] == 0:
shuffle(self.__number_list)
for value in self.__number_list:
if self.__valid(board, value, row, col):
board[row][col] = value
solution.append((row, col, value))
if self.__fill_board(board, solution, find_solution):
return True
del solution[-1]
board[row][col] = 0
return False
def check_board_valid(self):
for row in self.__board:
if len(row) != len(set(row)):
return False
for i in range(9):
col = [row[i] for row in self.__board]
if len(col) != len(set(col)):
return False
for i in range(0, 9, 3):
for j in range(0, 9, 3):
square = []
for row in self.__board[i:i+3]:
square += row[j:j+3]
if len(square) != len(set(tuple(square))):
return False
return True
def __delete_numbers(self, amount_of_filled_cells):
amount_of_deleted = 0
while 81 - amount_of_deleted > amount_of_filled_cells:
row = randint(0,8)
col = randint(0,8)
while self.__board[row][col] == 0:
row = randint(0,8)
col = randint(0,8)
self.__board[row][col] = 0
amount_of_deleted += 1
|
7df01a906406cf7131057ed17333eaa1951059ce | zzhang10/RSA-Machine | /RSA Machine.py | 18,959 | 3.5625 | 4 | #========================================================================================#
# #
# RSA ENCRYPTOR 1.0 #
# #
# BY ZACK ZHANG #
# #
#========================================================================================#
#========================================================================================#
# INTRODUCTION #
#========================================================================================#
#This program is written in python 3.7.0. It simulates a basic RSA encryption machine, but
# with some limitations in the characters it encrypts. Although each allowed character
# corresponds to only one number, the machine uses a special algorithm to prevent unintended
# decryption as a Caesar cypher. This algorithm combines the corresponding 2-digit numbers
# of every two adjacent characters into a 4-digit number before processing the encryption.
# Thus many different numbers may appear in the coded message, making it difficult
# to decypher the original text.
#
#The machine offers three modes: setting up the public/private keys, encrypting a message,
# and decrypting a message.
#========================================================================================#
# CONFIGS AND MESSAGES #
#========================================================================================#
#General:
#=========================================================================================
#The variable names (VN) in the program:
VN1,VN2,VN3,VN4,VN5= "p", "q", "n", "e", "d"
#All valid characters in the messages, and their correcponding number codes:
valid_chars = [["a",[91]],["b",[92]],["c",[93]],["d",[94]],["e",[95]],["f",[96]],["g",[97]],
["h",[98]],["i",[99]],["j",[10]],["k",[11]],["l",[12]],["m",[13]],["n",[14]],
["o",[15]],["p",[16]],["q",[17]],["r",[18]],["s",[19]],["t",[20]],["u",[21]],
["v",[22]],["w",[23]],["x",[24]],["y",[25]],["z",[26]],["A",[27]],["B",[28]],
["C",[29]],["D",[30]],["E",[31]],["F",[32]],["G",[33]],["H",[34]],["I",[35]],
["J",[36]],["K",[37]],["L",[38]],["M",[39]],["N",[40]],["O",[41]],["P",[42]],
["Q",[43]],["R",[44]],["S",[45]],["T",[46]],["U",[47]],["V",[48]],["W",[49]],
["X",[50]],["Y",[51]],["Z",[52]],["1",[53]],["2",[54]],["3",[55]],["4",[56]],
["5",[57]],["6",[58]],["7",[59]],["8",[60]],["9",[61]],["0",[62]],[",",[63]],
[".",[64]],["?",[65]],["!",[66]],["(",[67]],[")",[68]],["[",[69]],["]",[70]],
["{",[71]],["}",[72]],["<",[73]],[">",[74]],["-",[75]],[":",[76]],[";",[77]],
["@",[78]],["#",[79]],["$",[80]],["%",[81]],["^",[82]],["&",[83]],["*",[84]],
["+",[85]],["_",[86]],['"',[87]],["'",[88]],[" ",[89]]]
#Greeting message:
greeting=\
"""
=========================Welcome to RSA Machine 1.0==============================
This machine will teach you the basics of RSA encryption, and will help you set up
your own RSA system. The name RSA comes from the initials of its creators: Rivest,
Shamir, and Adleman. It is one of the first cryptosystems with public keys, and is
widely used for secure data transmission.
"""
#Prompting the user to choose what to do:
mode_selection=\
"""
Enter 1 if you would like to set up RSA,
2 to encrypt your RSA message, or
3 to decrypt
: """
#Error message when the user's mode selection is invalid:
invalid_mode_selection="Input invalid. You may only enter 1, 2 or 3."
#Setup mode:
#===========================================================================================
#Message when entering setup mode:
setup_greeting=\
"""
>>>You have entered setup mode.<<<
To set up your RSA, we begin by choosing two distinct prime numbers. To make sure
your encryption is relative secure, let's use primes with at least three digits."""
#Prompting user to choose primes:
prime_selection="\n Please choose your {} prime: "
#Messages for invalid prime selections:
invalid_prime_not_number="Input invalid. A prime must be a number."
invalid_prime_not_natural="Input invalid. A prime must be a natural number."
invalid_prime_not_prime= "Input invalid. {} is not a prime."
invalid_prime_too_small= "Input invalid. Please choose a prime that is larger than 100."
invalid_second_prime_duplicate="Your two primes must not be the same."
#Messages after prime selections are successful:
first_prime_chosen="\nYour first prime is {}."
second_prime_chosen="\nYour second prime is {}."
#Messages for variable assignment for the primes chosen:
first_prime_variable_assignment="We will let the variable {} represent this prime."
second_prime_variable_assignment="We will let the variable {} represent this prime."
#Announcing the product of the two primes:
n_value_announcement="\nWe let the variable {} be the product of {} and {}, which is {}."
#Prompting the user to select a number coprime with the product of subtracting 1 from both primes:
e_explanation=\
"""
Now we need to choose a(n) {} value that is between 1 and ({}-1)({}-1), and is coprime
with ({}-1)({}-1)={}, that is, the greatest common divisor of {} and {} is 1."""
e_selection="\n Enter your desired {} value: "
#Messages for invalid selection of "coprime variable":
invalid_e_not_number="Input invalid. Your {} value must be a number."
invalid_e_not_natural="Input invalid. Your {} value must be a natural number."
invalid_e_not_coprime="Invalid input. Your {} value must be coprime with {}."
invalid_e_bounds="Invalid input. Your {} value must be between 1 and {}."
#Messages after the "coprime variable" is selected:
e_selected="You have chosen your {} value to be {}."
#Announcing the public key:
public_key_announcement="\nYour public key value is ({},{}), or ({},{}). Make this known to the world!"
#Message for solving the congruence to find multiplicative inverse:
congruence_solve=\
"""
Now we solve the congruence for an integer {} such that ({})({}) is
congruent to 1 mod ({}-1)({}-1),or mod {}."""
#Warning the user to keep the private key secret:
private_key_warning="Look around, make sure there is no one spying on you, and then hit enter..."
#Announcing the result of the multiplicative inverse, and the private key:
mult_inv_announcement="The multiplicative inverse of {} is {} in mod {}. This will be your {} value."
private_key_announcement="Your private key value is ({},{}), or ({},{}). SHHH! Don't tell anybody!"
#Finishing the setup for RSA:
setup_end="You have finished setting up your RSA."
#Encryption mode:
#===========================================================================================
#Message at the beginning of the encryption mode:
encryption_greeting=\
"""
>>>You have entered encryption mode.<<<
Please obtain the public key for the recipient of the message."""
#Prompting the user to enter the public key of the recipient:
key_value_entry="\n Enter the {} value of the key: "
#Messages for invalid inputs of the public key:
key_invalid_not_number="Input invalid. Your {} value must be a number."
input_invalid_not_natural="Input invalid. Your {} value must be a natural number."
#Announcement after the public key is inputted:
target_public_key_announcement="Your target public key is ({},{})"
#Prompt to input the plain text message:
encrypt_input="Please input your message here: "
#Message containing the encrypted numbers:
coded_message_announcement="Your encoded message is {}."
#Error message when the user tries to encrypt invalid chacaters:
encryption_error=\
"""
Unfortunately the machine does not currently support some of the characters you entered.
The machine currently supports the encryption of all alphanumeric characters, spaces, and
the following special characters:
, . ? ! ( )[ ]{ }< > - : ; @ # $ %" ^ & * + _ " ' """
#Decryption mode:
#===========================================================================================
#Message at the beginning of the decryption mode:
decryption_greeting=\
"""
>>>You have entered decryption mode.<<<
Please refer to your private key."""
#Prompt for an entry of the encrypted number list:
cypher_entry=\
"""
Please input your encrypted numbers here in the form of
a list of numbers,separated by commas: """
#Error message when the encrypted list input is invalid:
cypher_entry_invalid="Your cypher must contain only natural numbers, commas and spaces."
#Message when the drcyphering process is going on:
decyphering_message="\nDecyphering your code..."
#Announcement of the decrypted message
decrypted_message_announcement="If your inputs are correct, your message is: "
#If the decryption fails due to incorrect input:
decryption_fail=\
"""Hmm... the decryption didn't work. Make sure you have entered the correct numbers,
and that the message is encrypted by this machine as well."""
#========================================================================================#
# CODE #
#========================================================================================#
#Returns True if the input, n, is a number, and false otherwise:
def is_number(n):
try:
float(n)
return True
except:
return False
#Guides the user to enter their private/public keys for de/encryption:
def key_entry():
e_entered=False
while e_entered==False:
e=input (key_value_entry.format("first"))
if not is_number(e):
print (key_invalid_not_number.format("first"))
elif str(e)[-1]==".":
print (key_invalid_not_number.format("first"))
else:
if float(e)!= int(float(e)) or float(e) <= 0:
print (input_invalid_not_natural.format("first"))
else:
e_entered=int(e)
n_entered=False
while n_entered==False:
n=input (key_value_entry.format("second"))
if not is_number(n):
print (key_invalid_not_number.format("second"))
elif str(n)[-1]==".":
print (key_invalid_not_number.format("second"))
else:
if float(n)!= int(float(n)) or float(n) <= 0:
print (input_invalid_not_natural.format("second"))
else:
n_entered=int(n)
return e_entered, n_entered
#Takes in five variable names and guides the user to set up their RSA:
def setup (variable1, variable2, variable3, variable4, variable5):
#Choose the two primes for RSA:
def choose_prime(order):
# Makes sure the numbers entered are prime:
def prime_check (item):
if item <= 1:
return False
elif item <= 3:
return True
elif item % 2==0 or item % 3==0:
return False
else:
i=5
while i*i <= item:
if item % i==0 or item % (i+2)==0:
return False
break
i+=6
return True
chosen = False
while chosen == False:
user_input=input (prime_selection.format(order))
if not is_number(user_input):
print (invalid_prime_not_number)
elif float(user_input)!= int(float(user_input)) or float(user_input) <=0:
print (invalid_prime_not_natural)
elif str(user_input)[-1]==".":
print (invalid_prime_not_number)
elif not prime_check(int(user_input)):
print (invalid_prime_not_prime.format(user_input))
elif int(user_input) < 100:
print (invalid_prime_too_small)
else:
return user_input
chosen=True
# Choose a number coprime to the product of when both primes are subtracted 1:
def choose_e (limit,variable1, variable2, variable4):
def gcd(a,b):
while b != 0:
(a, b) = (b, a % b)
return a
e_chosen = False
print(e_explanation.format(variable4,variable1,variable2,variable1,variable2,\
limit,limit,variable4))
while e_chosen==False:
e=input (e_selection.format(variable4))
if not is_number(e):
print (invalid_e_not_number.format(variable4))
elif str(e)[-1]==".":
print (invalid_e_not_number.format(variable4))
elif float(e)!= int(float(e)) or float(e) <= 0:
print (invalid_e_not_natural.format(variable4))
elif not 1 < int(e) < limit:
print (invalid_e_bounds.format(variable4,limit))
elif gcd (int(e), limit) != 1:
print (invalid_e_not_coprime.format(variable4, limit))
else:
print (e_selected.format (variable4,e))
e_chosen = True
return e
#Returns the inverse of input a mod m, or an exception if none is found:
def modinv(a, m):
def pre_modinv(c, d):
if c == 0:
return (d, 0, 1)
else:
g, y, x = pre_modinv(d % c, c)
return (g, x - (d // c) * y, y)
g, x, y = pre_modinv(a, m)
if g != 1:
raise Exception('Mod inverse not found.')
else:
return x % m
print (setup_greeting)
prime_1 = int (choose_prime("first"))
print (first_prime_chosen.format(prime_1))
print (first_prime_variable_assignment.format (variable1))
same_prime=True
while same_prime:
prime_2 = int (choose_prime("second"))
if prime_2 != prime_1:
same_prime=False
else:
print (invalid_second_prime_duplicate)
print (second_prime_chosen.format(prime_2))
print (second_prime_variable_assignment.format (variable2))
product_value = prime_1 * prime_2
e_limit=(prime_1-1)*(prime_2-1)
print (n_value_announcement .format(variable3,variable1,variable2,product_value))
e_value=int(choose_e (e_limit,variable1, variable2, variable4))
print (public_key_announcement.format(variable4,variable3,e_value,product_value))
print (congruence_solve.format (variable5, variable4,variable5,variable1,variable2,e_limit))
d=modinv(e_value, e_limit)
print (private_key_warning)
input()
print (mult_inv_announcement.format (variable4,d,e_limit,variable5))
print (private_key_announcement.format(variable5,variable3,d,product_value))
print(setup_end)
#Guides the user through the encryption process of RSA:
def encrypt ():
#Matches given code to the valid characters:
def encode (item):
for index in valid_chars:
if index[0]==item:
return index[1][0]
break
#Applies the special algorithm described in the introduction:
def process_numlist(numlist):
processed=[]
start=0
while len(numlist)-start >= 2:
processed.append(int(str(numlist[start])+str(numlist[start+1])))
start+=2
if len(numlist)-start ==1:
processed.append(numlist[start])
start+=1
return(processed)
print (encryption_greeting)
e_value,n_value=key_entry()
print (target_public_key_announcement.format(e_value,n_value))
message=input(encrypt_input)
message_split=list(message)
try:
code_list=[]
for item in message_split:
code_list.append(encode(item))
recoded_list=process_numlist(code_list)
final_list=[]
for item in recoded_list:
cipher=pow(int(item),e_value,n_value)
final_list.append(cipher)
print (coded_message_announcement.format(final_list))
except:
print (encryption_error)
#Decrypts a message for the user:
def decrypt ():
#Does a basic check on the entry of the encoded text and will filter out invalid
# characters, but will not actually check if the numbers are correct:
def valid_cypher(cypher):
validity=True
for item in cypher:
if item not in ["1","2","3","4","5","6","7","8","9","0",","," "]:
validity=False
return validity
#Tries to match the input with the valid character list:
def match (item):
for index in valid_chars:
if index[1][0]==item:
return index[0]
break
print (decryption_greeting)
d_value,n_value=key_entry()
cypher_chosen=False
while cypher_chosen==False:
cypher=input(cypher_entry)
if valid_cypher (cypher)==False:
print(cypher_entry_invalid)
else:
cypher_chosen=True
print (decyphering_message)
code_list=[x.strip() for x in cypher.split(',')]
decoded_list=[]
try:
for item in code_list:
decoded=pow(int(item),d_value,n_value)
if decoded > 999:
decoded_list.append(match(int(decoded/100)))
decoded_list.append(match(decoded%100))
else:
decoded_list.append(match(decoded))
try:
print(decrypted_message_announcement+"\n\n"+"".join(decoded_list))
except:
print(decryption_fail)
except:
print(decryption_fail)
#Main loop for the program:
def RSA ():
mode_chosen=False
while mode_chosen==False:
mode=input (mode_selection)
if mode not in ["1","2","3"]:
print (invalid_mode_selection)
elif mode == "1":
mode_chosen=True
setup(VN1,VN2,VN3,VN4,VN5)
elif mode == "2":
mode_chosen=True
encrypt()
else:
mode_chosen=True
decrypt()
print(greeting)
while True:
RSA()
|
a09a376f921143691ccb1ec9a7eb96fe6cad0e76 | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-adam_mentorbot | /passwordgen/passwordgen_module.py | 1,043 | 3.640625 | 4 | from random import randint
word_list_path = '/usr/share/dict/words'
abc = ["0123456789",
"ABCDEFGHIJKLMNOPQRSTUVXYZ",
"abcdefghijklmnopqrstuvxyz",
"!@#$%^&*()?"]
def wordsgen():
f = open(word_list_path, "r")
words = f.readlines()
word_1 = words[randint(0, len(words))].strip()
word_2 = words[randint(0, len(words))].strip()
return word_1 + " " + word_2
def passwordgen():
while True:
abc_used = [False] * 4
password = ""
for i in range(8):
rand_abc = randint(0, 3)
abc_used[rand_abc] = True
chars = abc[rand_abc]
password += chars[randint(0, len(chars)-1)]
if abc_used == [True] * 4:
break
return password
def main():
while True:
mode = input("Weak or a strong password? (weak/strong)").lower()
if mode in ["weak", "strong"]:
break
password = wordsgen() if mode == "weak" else passwordgen()
print(password)
if __name__ == '__main__':
main()
|
6ccbb7aedd31b95f8c4bb64992bcd83edf73bd09 | weflossdaily/Project-Euler | /113.py | 708 | 3.609375 | 4 | def countDescending(prefix,numDigits):
count = 0
if numDigits > 1:
for i in range(int(prefix[len(prefix) - 1]) + 1):
count += countDescending(prefix + str(i),numDigits - 1)
else:
#for i in range(int(prefix[len(prefix) - 1]) + 1):
# print prefix + str(i)
return int(prefix[len(prefix) - 1]) + 1
return count
def countAscending(prefix,numDigits):
count = 0
if numDigits > 1:
for i in range(int(prefix[len(prefix) - 1]),10):
count += countAscending(prefix + str(i),numDigits - 1)
else:
#for i in range(int(prefix[len(prefix) - 1]),10):
# print prefix + str(i)
return len(range(int(prefix[len(prefix) - 1]),10))
return count
digits = 100
print 2*countDescending('9',digits) -10 -1 |
010db25633ca13b307c1e15ce5446acf2c015775 | zhouwangyiteng/python100 | /t16.py | 365 | 3.609375 | 4 | # _*_ coding: UTF-8 _*_
import datetime
print datetime.date.today().strftime('%d/%m/%Y')
birthDate = datetime.date(1995, 3, 2)
print birthDate.strftime("%Y-%m-%d")
birthNextDate = birthDate + datetime.timedelta(days=1)
print birthNextDate.strftime("%Y-%m-%d")
firstBirthday = birthDate.replace(year=birthDate.year+21)
print firstBirthday.strftime("%Y-%m-%d")
|
4c791eb124c6078a9693233453699305b0f2f6b0 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2617/60752/298158.py | 198 | 3.671875 | 4 | i=input()
i1=input()
i2=input()
if i=='2' and i1=="10010 1"and i2=="100101 1":print("9\n11")
else:
if i=='2' and i1=="10010 1"and i2=="100101 2":print("9\n5")
else:
print("3\n11")
|
ec9b54f1d5293505a669a212581e97f4196aa78b | GlebFedorovich/Moon | /fifith_stage.py | 11,594 | 3.625 | 4 |
# units: kilometer, kilogram, second
# coordinate system: the origin is in the center of the moon
#at the initial moment oX is directed at the Moon, oY is directed at the North pole
import math
import sys
import matplotlib.pyplot as plt
import pylab
from numpy import *
output = open('moontoearth.txt', 'w')
INPUT_FILE = 'input1.txt'
gEarth = 0.00981
gMoon = 0.00162
rEarth = 6375
rMoon = 1738
GM = gEarth * rEarth * rEarth#G * Earth_mass
Gm = gMoon * rMoon * rMoon #G * Moon_mass
R = 384405 # radius of the Moon's orbit
pi = math.pi
Tmoon = 2 * pi * math.sqrt(R * R * R / GM)
dryMass = 10300 #dry mass of the accelerating stage
F = 95.75 #jet force of the accelerating stage
u = 3.05 #actual exhaust velocity of the accelerating stage
q = F / u #fuel consumption (kilograms per second) of the accelerating stage
class Vector:
def plus(a, b):
# returns the sum of a and b
ans = Vector()
ans.x = a.x + b.x
ans.y = a.y + b.y
ans.z = a.z + b.z
return ans
def minus(a, b):
# returns the difference between a and b
ans = Vector()
ans.x = a.x - b.x
ans.y = a.y - b.y
ans.z = a.z - b.z
return ans
def absV(a):
# returns the absolute value of a
return math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z)
def mult(k, a):
# returns product of scalar k and vector a
ans = Vector()
ans.x = k * a.x
ans.y = k * a.y
ans.z = k * a.z
return ans
def angle(v, u):
# returns value of the angle between v and u
a = Vector.absV(v)
b = Vector.absV(u)
c = v.x * u.x + v.y * u.y + v.z * u.z
return math.acos(c / a / b)
def copy(a):
ans = Vector()
ans.x = a.x
ans.y = a.y
ans.z = a.z
return ans
class RVTME:
# contains current position, velocity, time total mass and boolean state of the engine (0 - off, q - acceleration)
# (0 - off, q - acceleration)
def copy(rvtme):
ans = RVTME()
ans.r = Vector.copy(rvtme.r)
ans.v = Vector.copy(rvtme.v)
ans.t = rvtme.t
ans.m = rvtme.m
ans.engine = rvtme.engine
return ans
def moonPosition(time):
# returns the vector of Moon's position
global R, pi, Tmoon
ans = Vector()
ans.x = R * math.cos(2 * pi * time / Tmoon)
ans.y = R * math.sin(2 * pi * time / Tmoon)
ans.z = 0
return ans
def moonV(time):
# returns the vector of Moon's velocity
global Tmoon, pi, R
ans = Vector()
ans.x = -2 * pi * R / Tmoon * math.sin(2 * pi * time / Tmoon)
ans.y = 2 * pi * R / Tmoon * math.cos(2 * pi * time / Tmoon)
ans.z = 0
return ans
def timestep(a, deltaT=0.00005):
# returns non-constant timestep so as to make our model more accurate
return deltaT / Vector.absV(a)
def acc(r, v, time, mass, engine):
# returns the acceleration of the apparatus
global GM, Gm, q, F, q2, F2
aEarth = Vector.mult(-GM / (Vector.absV(r) * Vector.absV(r) * Vector.absV(r)), r)
moon = Vector.minus(r, moonPosition(time))
aMoon = Vector.mult(-Gm / (Vector.absV(moon) * Vector.absV(moon) * Vector.absV(moon)), moon)
aEngine = Vector()
if engine == 0:
aEngine.x = 0
aEngine.y = 0
aEngine.z = 0
if engine == q:
aEngine = Vector.mult(F / mass / Vector.absV(v), v)
# let jet force and velocity be co-directed
return Vector.plus(aEngine, Vector.plus(aEarth, aMoon))
def nextRVTME(previous, timestep):
# returns the next value of position and velocity of the apparatus (by the Runge-Kutta method)
ans = RVTME()
v1 = Vector.mult(timestep, acc(previous.r, previous.v, previous.t, previous.m, previous.engine))
r1 = Vector.mult(timestep, previous.v)
v2 = Vector.mult(timestep,
acc(Vector.plus(previous.r, Vector.mult(0.5, v1)), Vector.plus(previous.v, Vector.mult(0.5, v1)),
previous.t + timestep / 2, previous.m - 0.5 * previous.engine * timestep, previous.engine))
r2 = Vector.mult(timestep, Vector.plus(previous.v, Vector.mult(0.5, v2)))
v3 = Vector.mult(timestep,
acc(Vector.plus(previous.r, Vector.mult(0.5, v2)), Vector.plus(previous.v, Vector.mult(0.5, v2)),
previous.t + timestep / 2, previous.m - 0.5 * previous.engine * timestep, previous.engine))
r3 = Vector.mult(timestep, Vector.plus(previous.v, Vector.mult(0.5, v3)))
v4 = Vector.mult(timestep, acc(Vector.plus(previous.r, v3), Vector.plus(previous.v, v2),
previous.t + timestep, previous.m - previous.engine * timestep, previous.engine))
r4 = Vector.mult(timestep, Vector.plus(previous.v, v4))
ans.r = Vector.plus(previous.r, Vector.mult(1.0 / 6,
Vector.plus(r1, Vector.plus(r2, Vector.plus(r2, Vector.plus(r3,
Vector.plus(
r3,
r4)))))))
ans.v = Vector.plus(previous.v, Vector.mult(1.0 / 6,
Vector.plus(v1, Vector.plus(v2, Vector.plus(v2, Vector.plus(v3,
Vector.plus(
v3,
v4)))))))
ans.t = previous.t + timestep
ans.m = previous.m - timestep * previous.engine
ans.engine = previous.engine
return ans;
def test(rvtme):
# returns the distance to the Earth when our velocity is parallel to the Earth's surface
angle = pi / 2 - Vector.angle(rvtme.r, rvtme.v)
while (angle < 0) or (Vector.absV(rvtme.r) > 100000):
rvtme = nextRVTME(rvtme, timestep(acc(rvtme.r, rvtme.v, rvtme.t, rvtme.m, rvtme.engine)))
angle = pi / 2 - Vector.angle(rvtme.r, rvtme.v)
return Vector.absV(rvtme.r)
def readFloat(f):
return float(f.readline().strip())
def main():
global dryMass, GM, Gm, q, q2, R, rMoon, pi, u
f = open(INPUT_FILE, 'r')
string = open('to3.txt').readlines()
mm = array([[float(i) for i in string[k].split()] for k in range((len(string)))])
mSpent = int(mm[0][4]) # Fuel in the SM, spent on the flight to the Moon
v = readFloat(f)
h = readFloat(f)
mFuel = 17700 - mSpent # Remaining fuel in the SM
# We calculate the appropriate start point, based on the data of the output file of stage 4
x = R + (rMoon + h / 1000) * math.cos(math.asin(math.sqrt(GM * (rMoon + h / 1000) / 2 / Gm / R)))
y = (rMoon + h / 1000) * math.sqrt(GM * (rMoon + h / 1000) / 2 / Gm / R)
z = 0
vx = (math.sqrt(GM * (rMoon + h / 1000) / 2 / Gm / R)) * v
vy = 1.0184 - math.cos(math.asin(math.sqrt(GM * (rMoon + h / 1000) / 2 / Gm / R))) * v
vz = 0
rvtme = RVTME()
rvtme.r = Vector()
rvtme.v = Vector()
rvtme.r.x = x
rvtme.r.y = y
rvtme.r.z = z
rvtme.v.x = vx
rvtme.v.y = vy
rvtme.v.z = vz
rvtme.t = 0
rvtme.m = dryMass + mFuel
deltaV = -Vector.absV(Vector.minus(rvtme.v, moonV(rvtme.t))) + \
math.sqrt(2 * Gm / Vector.absV(Vector.minus(rvtme.r, moonPosition(rvtme.t)))) + \
math.sqrt(100 / Vector.absV(Vector.minus(rvtme.r, moonPosition(rvtme.t))))
# we need to increase our velocity approximately by this value
tau = rvtme.m / q * (1 - math.exp(-deltaV / u))
print(deltaV, " ", tau)
# we need to keep the engine on for approximately this time (according to the Tsiolkovsky equation)
# -------------------------------------------acceleration-------------------------------------
rvtme.engine = q
i = 0
while rvtme.t < tau:
rvtme = nextRVTME(rvtme, timestep(acc(rvtme.r, rvtme.v, rvtme.t, rvtme.m, rvtme.engine)))
output.write(str(rvtme.r.x) + '\t'
+ str(rvtme.r.y) + '\t'+ str(Vector.absV(rvtme.r)) +
'\t' + str(Vector.absV(rvtme.v)) + '\t' + str(rvtme.t) + '\n')
i += 1
if i % 10000 == 0:
print(rvtme.r.x, " ", rvtme.r.y)
rvtme.engine = 0
print(Vector.absV(Vector.minus(rvtme.v, moonV(rvtme.t))))
print(math.sqrt(2 * Gm / Vector.absV(Vector.minus(rvtme.r, moonPosition(rvtme.t)))))
print(Vector.absV(Vector.minus(rvtme.r, moonPosition(rvtme.t))))
# -------------------------------------------acceleration-------------------------------------
# --------------------------------------------waiting for 1 hour------------------------------
while rvtme.t < 3600:
rvtme = nextRVTME(rvtme, timestep(acc(rvtme.r, rvtme.v, rvtme.t, rvtme.m, rvtme.engine)))
output.write(str(rvtme.r.x) + '\t'
+ str(rvtme.r.y) + '\t' + str(Vector.absV(rvtme.r)) +
'\t' + str(Vector.absV(rvtme.v)) + '\t' + str(rvtme.t) + '\n')
i += 1
if i % 50000 == 0:
print(rvtme.r.x, " ", rvtme.r.y)
# --------------------------------------------waiting for 1 hour-----------------------------
# --------------------------------------------correction-------------------------------------
copy = RVTME.copy(rvtme)
testR = test(copy)
print(testR)
while abs(testR - rEarth - 70) > 0.00001:
copy.v = Vector.mult(1 - 0.0000085 * (rEarth + 70 - testR) / Vector.absV(copy.v), copy.v)
testR = test(copy)
print(testR - rEarth)
print("Reached 1 cm tolerance")
print("We must increase our velocity by ", 1000 * Vector.absV(Vector.minus(copy.v, rvtme.v)), " m/s")
rvtme.v = Vector.copy(copy.v)
# --------------------------------------------correction-------------------------------------------------
angle = pi / 2 - Vector.angle(rvtme.r, rvtme.v)
while angle < 0:
rvtme = nextRVTME(rvtme, timestep(acc(rvtme.r, rvtme.v, rvtme.t, rvtme.m, rvtme.engine), 0.00001))
angle = pi / 2 - Vector.angle(rvtme.r, rvtme.v)
i += 1
if i % 50000 == 0:
print(rvtme.r.x, " ", rvtme.r.y)
output.write(str(rvtme.r.x) + '\t' + str(rvtme.r.y) + '\t' + str(Vector.absV(rvtme.r)) +
'\t' + str(Vector.absV(rvtme.v)) + '\t' + str(rvtme.t) + '\n')
print("-----------------------------------")
print("Finish!")
print(math.sqrt(rvtme.r.x*rvtme.r.x + rvtme.r.y*rvtme.r.y)-rEarth) #height of our orbit
print(rvtme.m - dryMass)#check that the fuel is enough
main()
string = open('moontoearth.txt').readlines()
m = array([[float(i) for i in string[k].split()] for k in range((len(string)))])
from matplotlib.pyplot import *
plt.title(' y(x) ', size=11)
plot(list(m[:, 0]/1000), list(m[:, 1]/1000), "blue", markersize=0.1)
plt.xlabel('Coordinate x, km*10^3')
plt.ylabel('Coordinate y, km*10^3')
plt.grid()
show()
plt.title(' r(t) ', size=11)
plot(list(m[:, 4]/1000), list(m[:, 2]/1000), "blue", markersize=0.1)
plt.ylabel('Distance, km*10^3')
plt.xlabel('Time, s*1000')
plt.grid()
show()
plt.title(' V(t) ', size=11)
plot(list(m[:, 4]/1000), list(m[:, 3]), "blue", markersize=0.1)
plt.ylabel('Velocity, km/с ')
plt.xlabel('Time, s*1000')
plt.grid()
show()
|
78ba5ae264b4b22c676764d4992b079ebb50e8a4 | JaneNjeri/exercises_to_functions | /Scripts/write_genelist.py | 1,462 | 3.796875 | 4 | #! /home/user/miniconda3/bin/python
"""
write_genelist.py takes a gene annotation file
and writes gene names to file
Usage:
python write_genelist.py <gene_file> <outfile>
"""
import sys
in_file = sys.argv[1]
out_file = sys.argv[2]
def getGeneList():
with open(in_file, 'r') as humchr:
tag = False
gene_list = []
for line in humchr:
if line.startswith('Gene'):
tag = True
if tag:
line_split = line.split()
if len(line_split) != 0:
if '-' in line_split[0]:
continue
else:
gene_list.append(line_split[0])
return gene_list[3:0][:-2]
clean_gene_list = getGeneList()
def writeGeneList(clean_gene_list, out_file):
with open(out_file, 'w') as gene_names:
for gene in clean_gene_list:
gene_names.writelines(gene+'\n')
print('Genes have been written succesfully')
if len(sys.argv) <3: ##provides the user when importing the specifications of your module
print(_Doc_)
else:
print()
in_file = sys.argv[1]
out_file = sys.argv[2]
clean_gene_list = getGeneList()
writeGeneList(clean_gene_list)
##In command line, the first argument is the program e.g python denoted by [0], the second argument is the script(file) [1], the third argument is the output file [2]
|
fabed1027ab6ff93b3bcf48ef45944ef70ff055b | Aasthaengg/IBMdataset | /Python_codes/p02712/s356101445.py | 106 | 3.53125 | 4 | n=int(input())
a=[]
for i in range(1,n+1):
if not(i%3==0 or i%5==0):
a.append(i)
print(sum(a)) |
1431a5b5620fafacc29f30d2a8d3fe9e71819e77 | lelik9416/Homework | /task_validator.py | 3,449 | 3.515625 | 4 | from abc import ABCMeta, abstractmethod
import os
import datetime
class ValidatorException(Exception):
pass
class Validator(metaclass=ABCMeta):
types = {}
@abstractmethod
def validate(self):
pass
@classmethod
def get_types(cls):
return cls.types
@classmethod
def add_type(cls, name, klass):
if not name:
raise ValidatorException('Validator must have a name!')
if not issubclass(klass, Validator):
raise ValidatorException('Class "{}" is not Validator!'.format(klass))
cls.types[name] = klass
@classmethod
def get_instance(cls, name):
klass = cls.types.get(name)
if klass is None:
raise ValidatorException('Validator with name "{}" not found'.format(name))
return klass()
class EMailValidator(Validator):
def validate(self, value):
#проверка на наличие @ в email
if '@' not in value:
return False
#проверка на наличие . в email
if '.' not in value:
return False
sig1 = value.find('@')
#проверка на вхождение второй @
if value.rfind('@') != sig1:
return False
sig2 = value[::-1].find('.')
sig3 = abs(sig1 - value.find('.') + 1)
if sig1 != 0 and sig2 != 0 and sig3 != 0:
return True
return False
"""
--------------
ext = value.split('@')
ext1 = ext[1].split('.')
if len(ext[0]) !=0 and len(ext1[0]) !=0 and len(ext1[1]) !=0:
return True
"""
class DateTimeValidator(Validator):
def validate(self, value):
#row = value.split()
date_format = ['%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',
'%Y-%m-%j %H:%M:%S',
'%Y-%m-%j %H:%M',
'%Y-%m-%j',
'%Y-%n-%j %H:%M:%S',
'%Y-%n-%j %H:%M',
'%Y-%n-%j',
'%j.%n.%Y %H:%M:%S',
'%j.%n.%Y %H:%M',
'%j.%n.%Y',
'%j.%m.%Y %H:%M:%S',
'%j.%m.%Y %H:%M',
'%j.%m.%Y',
'%d.%m.%Y %H:%M:%S',
'%d.%m.%Y %H:%M',
'%d.%m.%Y',
'%j/%n/%Y %H:%M:%S',
'%j/%n/%Y %H:%M',
'%j/%n/%Y',
'%j/%m/%Y %H:%M:%S',
'%j/%m/%Y %H:%M',
'%j/%m/%Y',
'%d/%m/%Y %H:%M:%S',
'%d/%m/%Y %H:%M',
'%d/%m/%Y'
]
for form in date_format:
try:
datetime.datetime.strptime(value, form)
return True
except:
continue
return False
Validator.add_type('email', EMailValidator)
Validator.add_type('datetime', DateTimeValidator)
validator = Validator.get_instance('email')
validator1 = Validator.get_instance('datetime')
|
04a60107cce644cd3d87322b2173b8d4c1c190d2 | Global19/pm4ngs | /src/pm4ngs/jupyterngsplugin/utils/load_content_dict.py | 2,410 | 3.9375 | 4 |
def load_content_dict(file, delimiter, strip_line=True,
replace_old=None, replace_new=None, comment=None,
startswith=None):
"""
This function load file content in a dictionary spliting the line in two (key-value)
:param file: File to parse
:param delimiter: Delimiter to split line
:param strip_line: Strip line before splitting
:param replace_old: Replace substring replace_old with replace_new before splitting
:param replace_new: Replace substring replace_old with replace_new before splitting
:param comment: Comment str to exclude line
:param startswith: Parse line if start with startswith
:return: Dict with file content
"""
result = {}
with open(file) as fin:
for line in fin:
if (not comment or (comment and not line.startswith(comment))) or \
(startswith and line.startswith(startswith)):
if strip_line:
line = line.strip()
if replace_old:
line = line.replace(replace_old, replace_new)
fields = line.split(delimiter)
if len(fields) == 2:
result[fields[0].strip()] = fields[1].strip()
return result
def load_content_dict_line(file, delimiter, startswith, sec_delimiter, strip_line=True,
replace_old=None, replace_new=None):
"""
This function load file content in a dictionary spliting the line in two (key-value)
:param file: File to parse
:param delimiter: Delimiter to split line
:param strip_line: Strip line before splitting
:param replace_old: Replace substring replace_old with replace_new before splitting
:param replace_new: Replace substring replace_old with replace_new before splitting
:param startswith: Parse line if start with startswith
:return: Dict with file content
"""
result = {}
with open(file) as fin:
for line in fin:
if line.startswith(startswith):
if strip_line:
line = line.strip()
if replace_old:
line = line.replace(replace_old, replace_new)
fields = line.split(delimiter)
if len(fields) == 2:
result[fields[0].strip()] = fields[1].strip().split(sec_delimiter)[0]
return result
|
a3ef74ac052606a13361d8531ead5dce148162f1 | rastgeleo/python_algorithms | /sorting/quick_sort.py | 540 | 3.859375 | 4 | import random
def quick_sort(items):
if len(items) <= 1:
return items
pivot = items[0]
lt = quick_sort([item for item in items[1:] if item < pivot])
gte = quick_sort([item for item in items[1:] if item >= pivot])
return lt + [pivot] + gte
def test_quick_sort():
my_list = random.sample(range(-100, 100), 10)
assert quick_sort(my_list) == sorted(my_list)
print('sorting: {}'.format(my_list))
print('sorted :{}'.format(quick_sort(my_list)))
if __name__ == "__main__":
test_quick_sort() |
8f2b65e954502dedf32b7c907284987509746681 | xatlasm/python-crash-course | /chap3/3-10.py | 461 | 3.828125 | 4 | # Every function
categories = ['country', 'city', 'plant', 'animal', 'object', 'boy name',
'girl name', 'famous person']
print(categories[-7].title())
categories.append('foo')
categories.pop()
categories.insert(0,"bar")
del categories[0]
categories.remove('famous person')
categories.sort()
print(categories)
categories.sort(reverse=True)
print(categories)
print(sorted(categories))
categories.reverse()
print(categories)
print(len(categories)) |
4f5a3e0627337098314a736f8f160c4a779526bb | HTMLProgrammer2001/pyGame | /Arcanoid/Classes/Ball.py | 2,311 | 3.53125 | 4 | import pygame
from random import random
from globals import *
class Ball(pygame.sprite.Sprite):
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.size = BALL_SIZE
self.power = 1
self.color = BALL_COLOR
# move
self.isInit = False
# ball direction
self.dir = {
'x': -1,
'y': -1
}
self.speed = {
'x': BALL_INITIAL_SPEED,
'y': BALL_INITIAL_SPEED
}
# draw
self.surface = pygame.Surface((self.size * 2, self.size * 2))
self.rect = self.surface.get_rect(
bottom=pos[1] - 5,
centerx=pos[0]
)
def update(self):
if not self.isInit:
return
# move ball
self.rect.move_ip(self.dir['x'] * self.speed['x'], self.dir['y'] * self.speed['y'])
# check collision
if self.rect.left < 0 or self.rect.right > W:
self.dir['x'] *= -1
if self.rect.top < 0 or self.rect.bottom > H:
self.dir['y'] *= -1
def draw(self, sc):
# clear
self.surface.fill(BOARD_COLOR)
pygame.draw.circle(self.surface, self.color, (self.size, self.size), self.size)
# draw on screen
sc.blit(self.surface, self.rect)
def checkCollisionWith(self, rect):
return self.rect.colliderect(rect)
def changeDir(self, x=False, y=False):
# change direction of ball
if x:
self.dir['x'] *= -1
if y:
self.dir['y'] *= -1
def changeSpeedX(self, faster=True):
if faster:
self.speed['x'] *= 1.2
if self.speed['x'] > BALL_MAX_SPEED:
self.speed['x'] = BALL_MAX_SPEED
else:
self.speed['x'] /= 1.2
if self.speed['x'] < BALL_MIN_SPEED:
self.speed['x'] = BALL_MIN_SPEED
def changeSpeedY(self, faster=True):
if faster:
self.speed['y'] += .1
if self.speed['y'] > BALL_MAX_SPEED:
self.speed['y'] = BALL_MAX_SPEED
else:
self.speed['y'] -= .1
if self.speed['y'] < BALL_MIN_SPEED:
self.speed['y'] = BALL_MIN_SPEED
def move(self):
self.isInit = True
|
9537234e130166034003d3a6fedd1c33e3c0ffc5 | ushitora/bwt | /bwt/lyndon/lyndon.py | 1,070 | 4.1875 | 4 | def longest_lyndon_prefix(w):
"""
Returns the tuple of the longest lyndon prefix length and the number of repitition for the string w.
Examples:
abbaa -> Returns (3, 1)
abbabb -> Returns (3, 2)
"""
i = 0
j = 1
while j < len(w) and w[i] <= w[j]:
if w[i] == w[j]:
i += 1
j += 1
else:
i = 0
j += 1
return j - i, j // (j - i)
def is_lyndon(w):
"""Returns true iff the string w is the lyndon word"""
return longest_lyndon_prefix(w)[0] == len(w)
def lyndon_break_points(w):
"""Returns lyndon breakpoints sequence of the string w"""
start = 0
while start < len(w):
pref, rep = longest_lyndon_prefix(w[start:])
for _ in range(rep):
start += pref
yield start
def lyndon_factorize(w):
"""
Returns lyndon factorization sequence of the string w
Examples:
abbaba -> abb, ab, a
"""
start = 0
for bp in lyndon_break_points(w):
yield w[start: bp]
start = bp
|
f32bbf84d7b3a7887eab331d062288b7541f9dc1 | dojorio/dojo_niteroi | /2010/20101021_pybr_fizzbuzz/fizzbuzz.py | 202 | 3.625 | 4 | DIV3 = 'Arveres'
DIV5 = 'somo nozes'
def fizzbuzz(numero):
valor = ''
if numero % 3 == 0:
valor += DIV3
if numero % 5 == 0:
valor += DIV5
return valor or str(numero)
|
f91e1e233e9dff8fbd4b2937c9494135ecb8a03f | Alcatraz714/HacktoberFest-1 | /Python Graphics/Projection.py | 480 | 3.578125 | 4 | import math
from graphics import *
win = GraphWin("PolygonClipping", 500, 500)
def main():
print("Enter number of points")
n = int(input())
arr=[]
for i in range(n):
print("Enter x co-ordinate of point")
x = int(input())
print("Enter y co-ordinate of point")
y = int(input())
print("Enter z co-ordinate of point")
z = int(input())
arr.append([x, y, z])
print(arr)
main()
|
e13af7754459c150351937f14df5a7fbe96f3ea1 | ParthG-Gulati/Python-day-5 | /employee.py | 625 | 4.21875 | 4 | #Consider an employee class, which contains fields such as name and designation.
#And a subclass, which contains a field salary.# Write a program for inheriting this relation.
class employee:
name = ""
designation = ""
def NAME(self):
self.name = input("Enter the name of the Employee:")
def DESIGNATION(self):
self.designation = input("Enter the designation of the Employee:")
class salary(employee):
salary=0.0
def SALARY(self):
self.salary = int(input("Enter the salary of the Employee:"))
sal=salary()
sal.NAME()
sal.DESIGNATION()
sal.SALARY() |
47ab767d1e174c8b3445c7b7a0d5e853727d8ef3 | RotemHalbreich/Ariel_OOP_2020 | /Classes/week_09/TA/simon_group/2-variables.py | 2,115 | 4.59375 | 5 | # Creating Variables
x = 5
y = "John"
print(x)
print(y)
# Variable Names
#
# A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
# (case sensitive and don't start with a number)
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
# Ouput Variables
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = 5
y = 10
print(x + y)
#################################################### Wont Work
# x = 5
# y = "John"
# print(x + y)
####################################################
# Assignment Operators
"""
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
"""
# Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# Multiple Value for same variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
# global and local variables
"""
If you create a variable with the same name inside a function, this variable will be local,
and can only be used inside the function. The global variable with the same name will remain as it was,
global and with the original value.
"""
# Example
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc() # the output will be the local one (fantastic)
print("Python is " + x) # the output will be the global one (awesome)
# If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print(
"Python is " + x) # print the var x assigned globally by the latter function, try it without global to better understanding.
# ----------------------------------------------#
# Also, use the global keyword if you want to change a global variable inside a function.
|
c0c28116a09cd42749f749ccab53c374bb0896b2 | darlasunitha/python | /62.py | 161 | 3.671875 | 4 | p=raw_input()
"""if all(a in '01' for a in q):
print "yes"
else:
print "no"
"""
if not(p.translate(None,'01')):
print "yes"
else:
print "no"
|
222e5d4b9fe694b7081b80b120e4197f23e8ea12 | MichaelKSoh/Euler_Project | /Problem 006/sumSquareDifference.py | 363 | 3.546875 | 4 | targetNum = 100
def sumOfSquares(num):
counter=0
for i in range(1,num+1):
counter += i**2
return counter
print(sumOfSquares(targetNum))
def SquareOfSum(num):
counter = 0
for i in range(1,num+1):
counter += i
return (counter**2)
print(SquareOfSum(targetNum))
print((SquareOfSum(targetNum)) - (sumOfSquares(targetNum))) |
e4291c39bed110adbed214dfb4c5b8481bf97c8b | emerette/python-challenge | /PyBank/main.py | 1,935 | 3.5 | 4 | import os
import csv
from statistics import mean
csvpath = os.path.join( 'Resources', 'budget_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter =",")
print (csvreader)
csv_header = next(csvreader)
print(f"Financial Analysis: ")
print("--------------------------")
count = 0
total = 0
# Count = number of rows there are
# Total = total amt of profit/loss
diffs = []
prev = 0
biggest = []
smallest = []
for row in csvreader:
count += 1
current = int(row[1])
total += current
if count > 1:
diffs.append(current - prev)
if int(biggest[1]) < current:
biggest = [row[0], (current-prev)]
if int(smallest[1]) > current:
smallest = [row[0], (current-prev)]
if count == 1:
biggest = row
smallest = row
prev = current
averagechange = sum(diffs)/len(diffs)
print(averagechange)
print(" Total Months: " + str(count))
print(" Total: $" + str(total))
print(" Average Change: $" + str(averagechange))
print(" Greatest Increase in Profits: " + biggest[0] + " ($" + str(biggest[1]) + ") ")
print(" Greatest Decrease in Profits: " + smallest[0] + " ($" + str(smallest[1]) + ") ")
outputpath = os.path.join("Analysis", "analysis.txt")
with open(outputpath, "w") as output:
output.write(" Financial Analysis\n")
output.write("--------------------------\n")
output.write(" Total Months: " + str(count) + "\n")
output.write(" Total: $" + str(total) + "\n")
output.write(" Average Change: $" + str(averagechange) + "\n")
output.write(" Greatest Increase in Profits: " + biggest[0] + " ($" + str(biggest[1]) + ") \n")
output.write(" Greatest Decrease in Profits: " + smallest[0] + " ($" + str(smallest[1]) + ") \n")
|
9a4958ed9db568218992a52a989aa7302a2f227c | WdxzzZ/Grab-AzureHackthon | /utils.py | 525 | 3.75 | 4 | # Great circle distance computes the shortest path distance of two projections on the surface of earth.
from math import radians, degrees, sin, cos, asin, acos, sqrt
def haversine(lat1, lat2, long1, long2):
r = 6371 #km
long1, lat1, long2, lat2 = map(radians, [long1, lat1, long2, lat2])
dist_longtitude = long2-long1
dist_latitude = lat2 - lat1
a = sin(dist_latitude/2)**2 + cos(lat1)*cos(lat2)*sin(dist_longtitude/2)**2
return 2*r*asin(sqrt(a))
print(haversine(37.72,41.8781, -89.2167,-86.6297)) |
b685f8d36f8299819c4dca1a70eb6b18493fb006 | longhao54/leetcode | /easy/476.py | 407 | 3.53125 | 4 | class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return int(''.join(['0' if x == '1' else '1' for x in bin(num)[2:]]),2)
def fast(self, num):
res = ''
if num == 0:
return 1
while num!=0:
res = str((num%2)^1)+res
num = num//2
return int(res,2)
|
29745ca840d4cc825005cd43842e2122c8347704 | jmg5219/First-Excercises-in-Python- | /celsius_to_farenheit.py | 377 | 4.375 | 4 | #Defining a function to convert temperature in Centigrade to Fahrenheit
def convert_F(temp_c):
temp_f = (temp_c*(9/5))+32
return temp_f
#Prompting User Input fo rTemperature in Centigrade
temp_c = int(input("Temperature in C?"))
#Using string interpolation to print the units
print("%.1f F" % (convert_F(temp_c)))#Calling the function to perform the conversion
|
4004eff7ca1538adb79219b2075d5631286987ac | ghufransyed/udacity_cs101 | /restaurant.py | 1,055 | 4.25 | 4 | class Restaurant(object):
"""
Represents a place that serves food.
"""
def __init__(self, p_name, p_owner, p_chef):
self.name = p_name
self.owner = p_owner
self.chef = p_chef
def display(self):
"""Display the restaurant."""
print self.name
def is_yummy(self):
"""
returns true if yummy, otherwise false
"""
return False
# define a method is_yummy
# that returns a boolean value of yummyness
# for now it should always return False
def __str__(self):
return (str(self.name) + ' (Owner: ' + str(self.owner)
+ ', Chef: ' + str(self.chef) + ')')
# class Restaurant(object):
# """
# Represents a place that serves food.
# """
# def __init__(self, name):
# self.name = name
#
# def display(self):
# """Display the restaurant."""
# print self.name
#
# def is_yummy(self):
# """
# returns true if yummy, otherwise false
# """
# return False
|
a5a55dc61623b21474c1f46536df5d3c8406ae2a | eze2017/Air-traffic-projection | /predictions/fuel_consumption.py | 13,362 | 4.3125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def compute_distances_vector_in_miles(iata_to_fuel):
"""
This function converts distance from nautical miles to miles.
:param iata_to_fuel: Data mapping fuel consumption to aircraft IATA codes
:return x_miles: Array containing distances in miles
"""
# From the data mapping fuel consumption to aircraft IATA codes we get distances in nautical miles.
x_nautical_miles = np.array(iata_to_fuel.keys()[1:]).astype(float)
# We convert these distances in nautical miles to distances in miles.
x_miles = x_nautical_miles * 1.15078 # 1 nautical mile = 1.15078 mile
return x_miles
def compute_polynomial_coefficients(x, y, degree):
"""
This function computes the coefficients of a polynomial regression model.
:param x: Array representing the input values.
:param y: Array representing the output values.
:param degree: Integer representing the degree of the polynomial model.
:return coefficients: Array containing the coefficients of the polynomial model.
"""
coefficients = np.polyfit(x, y, degree)
return coefficients
def get_flight_distance(origin, dest, year, data_by_year):
"""
#his function computes flight distance between an origin and a destination.
:param origin: String representing the three-letter code of the origin airport.
:param dest: String representing the three-letter code of the destination airport.
:param year: Year of the data that we wish to work with.
:param data_by_year: Data corresponding to yearly air trafic.
:return distance_in_miles: Float representing the flight distance in miles between the origin and the destination.
"""
distance_in_miles = np.array(data_by_year[str(year)].iloc[np.where(
(data_by_year[str(year)]['ORIGIN'] == origin) & (data_by_year[str(year)]['DEST'] == dest))]['DISTANCE'])[0]
return distance_in_miles
def compute_definitive_coefficients(data_by_year, dot_to_iata, iata_to_fuel, degree=4):
"""
This function returns the coefficients of polynomial models used to compute the fuel consumption of all the different
aircrafts.
The fuel consumption depends a lot on the type of aircrafts. The iata_to_fuel data maps fuel consumption to aircraft
IATA codes in an undirect manner. For each aircraft it returns its fuel consumption for some given distances.
We thus approximate the fuel consumption model of each aircraft using these values.
:param data_by_year: Data corresponding to yearly air trafic.
:param dot_to_iata: Data mapping aicraft DOT codes to aircraft IATA codes. Also provides the number of seats of
each aircraft.
:param iata_to_fuel: Data mapping fuel consumption to aircraft IATA codes.
:param degree: Degree of the polynomial model
:return coefs_of_dot_codes: Dictionary containing the polynomial fuel consumption model of different aircrafts.
"""
coefs_of_dot_codes = {} # Initialization of the dictionary containing the polynomial model of different aircrafts.
x_miles = compute_distances_vector_in_miles(iata_to_fuel) # Distances present in the iata_to_fuel data
dot_codes_used = []
# We look at all the aircrafts that were used between the years 2015 and 2019. We only list the aircrafts thave have
# been used during these years and not between the years 2005 to 2019 for instance because we had to map by hand
# the dot codes of the aircraft present in the data_by_year data to the iata codes of the aircraft present in the
# iata_to_fuel. Since it was time consuming we decided to only list aircrafts used between 2015 and 2019 and assumed
# that they were representative of the aircrafts used between 2005 and 2019.
years = ['2015', '2016', '2017', '2018', '2019']
for yr_str in years:
dot_codes_used += list(data_by_year[yr_str]['AIRCRAFT_TYPE'])
# We get a list of the dot codes of all the aircrafts used between 2015 and 2019
dot_codes = np.unique(dot_codes_used)
for k in range(len(dot_codes)):
# For each aircraft (represented by a dot code) we get its corresponding iata code
iata_code = np.array(dot_to_iata.iloc[np.where(dot_to_iata['DOT'] == dot_codes[k])]['IATA'])[0]
# We also get the number of seats associated to this aircraft
seats_nb = np.array(dot_to_iata.iloc[np.where(dot_to_iata['DOT'] == dot_codes[k])]['Seats'])[0]
coefs_of_dot_codes[dot_codes[k]] = {"seats": seats_nb, "coefs": None}
# If this iata code is associated to its fuel consumption in the iata_to_fuel data:
if len(iata_to_fuel.iloc[np.where(iata_to_fuel['IATA'] == iata_code)]) != 0:
# We get the fuel consumption values of this particular aircraft for the distances present in x_miles
y = np.array(iata_to_fuel.iloc[np.where(iata_to_fuel['IATA'] == iata_code)])[0][1:]
y = np.array(y, dtype=float)
y = y[~np.isnan(y)] # We get rid of the values associated to nan values
# We use the distances present in x_miles and the associated fuel consumption of this aircraft to compute
# a polynomial model for the fuel consumption of this aircraft.
coefs = compute_polynomial_coefficients(x_miles[:len(y)], y, degree)
# We store the parameters of this model for this particular aircraft in the final dictionary
coefs_of_dot_codes[dot_codes[k]]["coefs"] = coefs
# We gather all the parameters of the different models associated to the fuel consumption of the different aircrafts
# into one list called all_coefs
all_coefs = []
for sub in coefs_of_dot_codes:
if ((coefs_of_dot_codes[sub]["coefs"]) is not None):
all_coefs.append(coefs_of_dot_codes[sub]["coefs"])
# We add a special key/value pair to the final dictionary which will be used if we later have to deal with an aircraft
# code for which we do not have any fuel consumption model or which was not listed in the original list of the
# aircrafts used during years 2015-2019.
# The model associated to this special key is made of coefficients which are an average of the coefficients of all
# the other models.
# The number of seat associated to this special key are an average of the number of seats of all the other aircrafts.
coefs_of_dot_codes[0] = {"coefs": np.mean(all_coefs, axis=0),
"seats": np.mean([coefs_of_dot_codes[sub]["seats"] for sub in coefs_of_dot_codes], axis=0)}
return coefs_of_dot_codes
def compute_CO2_emissions(origin, dest, year, data_by_year, coefs_of_dot_codes):
"""
This function computes the CO2 emission by calculating the fuel consumption, and using a standard conversion from kg of fuel to kg of CO2 produced.
:param origin: String representing the three-letter code of the origin airport.
:param dest: String representing the three-letter code of the destination airport.
:param year: Year of the data that we wish to work with.
:param data_by_year: Data corresponding to yearly air trafic.
:param coefs_of_dot_codes: Dictionary containing the polynomial fuel consumption model of different aircrafts.
:return CO2_kg: Float representing the carbon emission produced by all the flights that flew between a particular
origin and a particular destination during a particular year.
"""
# We get the distance in miles between the origin airport and the destination airport
flight_distance = get_flight_distance(origin, dest, year, data_by_year)
# We get the dot codes of all the aircrafts that have been flying between this origin and this destination during this
# particular year
dot_codes = np.array(data_by_year[str(year)].iloc[np.where(
(data_by_year[str(year)]['ORIGIN'] == origin) & (data_by_year[str(year)]['DEST'] == dest))]['AIRCRAFT_TYPE'])
# We get the number of seats of all the aircrafts that have been flying between this origin and this destination during
# this particular year
seats_nb = np.array(data_by_year[str(year)].iloc[np.where(
(data_by_year[str(year)]['ORIGIN'] == origin) & (data_by_year[str(year)]['DEST'] == dest))]['PASSENGERS'])
fuel_total_consumption_kg = 0 # Initialization of the fuel consumption
# We go through all the flights which took place between this origin and this destination during this particular
# year
for k in range(len(dot_codes)):
# If the type of aircraft is not part of types of aircrafts which have been used between 2015 and 2019
if dot_codes[k] not in coefs_of_dot_codes:
# We use parameters which are an average of the parameters of all the other aircrafts for the model of this
# aircraft
coefs = coefs_of_dot_codes[0]["coefs"]
# We use the number of seats which is an average of the number of seats of all the other aircrafts.
# We estimate the number of flights which took place between this origin and this destination for this year.
# Indeed each row of the data_by_year data corresponds to monthly statistics. Therefore to compute the exact
# number of flights which took place during a year we divide the number of seats present in this row by the
# number of seats of this type of aircraft.
estimated_number_of_flights = int(round((seats_nb[k]) / (coefs_of_dot_codes[0]["seats"])))
# If the type of aircraft is part of the types of aircrafts which have been used between 2015 and 2019 but its
# code is not associated to any fuel consumption values
elif coefs_of_dot_codes[dot_codes[k]]["coefs"] is None:
# We use parameters which are an average of the parameters of all the other aircrafts for the model of this
# aircraft
coefs = coefs_of_dot_codes[0]["coefs"]
# We use the number of seats of this particular aircraft.
estimated_number_of_flights = int(round((seats_nb[k]) / (coefs_of_dot_codes[dot_codes[k]]["seats"])))
else:
# We use the fuel consumption model of this specific type of aircraft
coefs = coefs_of_dot_codes[dot_codes[k]]["coefs"]
# We use the number of seats of this specific type of aircraft
estimated_number_of_flights = int(round((seats_nb[k]) / (coefs_of_dot_codes[dot_codes[k]]["seats"])))
# We use the fuel consumption model and apply it on the distance to compute the fuel consumed by this type of
# aircraft on this distance.
fuel_consumed_for_distance = np.polyval(coefs, flight_distance)
# We multiply the fuel consumed by this type of aircraft on this distance with the number of flights of this kind
# which flew between this origin and this destination at this particular year.
fuel_total_consumption_kg += fuel_consumed_for_distance * estimated_number_of_flights
# We convert the fuel consumption in kg to CO2 consumption in kg
CO2_kg = round(fuel_total_consumption_kg * 3.15)
return CO2_kg
def plot_aircraft_codes_histogram(data_by_year):
"""
This is an accessory function to obtain the most commonly used aircraft for flights, and plot a histogram of aircraft
types used for all flights.
:param data_by_year: Data corresponding to yearly air trafic.
:return: A graph displaying a histogram of the types of aircraft used for all flights for the years present in data_by_year
"""
years_str = list(data_by_year.keys())
# We get a list of all the types of aircrafts that flew during the years present in data_by_year
dot_codes_used = []
for yr_str in years_str:
dot_codes_used += list(data_by_year[yr_str]['AIRCRAFT_TYPE'])
dot_codes_used = np.array(dot_codes_used)
# We get a list containing all these different types of aircrafts only once
dot_codes = np.unique(dot_codes_used)
plt.title("Types of aircrafts used between 2015 and 2019")
plt.xlabel("DOT Aircraft code")
plt.ylabel("Number of flights done")
plt.hist(dot_codes_used, dot_codes)
plt.show()
def other_transport(dist):
"""
This function returns the average CO2 emitted per person on a certain distance for different types of cars and for
trains.
Uses average mileage for all cars classified by category (according to EPA classification). Estimates mileage from
distance between cities.
Train fuel economy on a passenger-miles per gallon basis on a national average AMTRAK load factor of 54.6%.
:param dist: Float representing a distance in miles
:return car_fuel_emissions, train_avg: Two dictionaries with CO2 emission per person for each type of car and train.
"""
car_fuel_emissions = {'Two-seater': 22, 'Subcompact': 24, 'Compact': 26, 'Midsize Sedan': 26, 'Large Sedan': 21,
'Hatchback': 27, 'Pickup truck': 18, 'Minivan': 20, 'Small SUV': 24, 'Standard SUV': 18}
car_fuel_emissions.update({i: 9.07185 * (dist / car_fuel_emissions[i]) for i in car_fuel_emissions.keys()})
car_fuel_emissions = [{"type": key, "emissions": value} for key, value in car_fuel_emissions.items()]
train_avg = [{"type": "Train", "emissions": 10.1514 * (dist / 71.6)}]
return (car_fuel_emissions, train_avg)
|
188865e4e7c96c0b6b2ddbd847ce6f16bc1ffdaf | ypyao77/python-startup | /python-cookbook/03.digit-date-time/13-last-friday.py | 2,302 | 4.15625 | 4 | #!/usr/bin/env python3
# 3.13 计算最后一个周五的日期
# 你需要查找星期中某一天最后出现的日期,比如星期五。你需要查找星期中某一天最后出现的日期,比如星期五。
"""
Topic: 最后的周五
Desc :
"""
from datetime import datetime, timedelta
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# 上面的算法原理是这样的:先将开始日期和目标日期映射到星期数组的位置上 (星期一索引为 0),
# 然后通过模运算计算出目标日期要经过多少天才能到达开始日期。然后用开始日期减去那个时间差即得到结果日期。
def get_previous_byday(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(dayname)
days_ago = (7 + day_num - day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days=days_ago)
return target_date
if __name__ == "__main__":
# Python 的 datetime 模块中有工具函数和类可以帮助你执行这样的计算。下面是对类似这样的问题的一个通用解决方案
print("datetime.today(): ", datetime.today())
print("get_previous_byday('Monday'): ", get_previous_byday('Monday'))
print("get_previous_byday('Tuesday'): ", get_previous_byday('Tuesday'))
print("get_previous_byday('Friday'): ", get_previous_byday('Friday'))
# 可选的 start_date 参数可以由另外一个 datetime 实例来提供。
print("get_previous_byday('Sunday', datetime(2019, 5, 18)): ", get_previous_byday('Sunday', datetime(2019, 5, 18)))
# 如果你要像这样执行大量的日期计算的话,你最好安装第三方包 python-dateutil来代替。
# 比如,下面是是使用 dateutil 模块中的 relativedelta() 函数执行同样的计算:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
d = datetime.now()
print("d: ", d)
# Next Friday
print("d + relativedelta(weekday=FR): ", d + relativedelta(weekday=FR))
# Last Friday
print("d + relativedelta(weekday=FR(-1)): ", d + relativedelta(weekday=FR(-1)))
|
21657edaf9b632a2233a9e6c46cf76db6b2116c2 | toolshc/euler | /001-multiples-3-5/multiple-3-5.py | 263 | 4.1875 | 4 | def is_multiple_of_3_or_5(x):
if ( x%3 == 0 ) or ( x%5 == 0 ) :
return True
else:
return False
def sum(top):
total = 0
for i in range(3,top):
if is_multiple_of_3_or_5(i):
total += i
return total
print sum(10)
print sum(1000) #233168 |
4a9e41c920d9c3a95cad8901bf6b8f9810df6a92 | bilakos26/Python-Test-Projects | /Class_Information.py | 1,373 | 4.125 | 4 | class Information:
def __init__(self, name, address, age, phone_number):
self.__name = name
self.__address = address
self.__age = age
self.__phone_number = phone_number
def set_name(self, name):
self.__name = name
def set_address(self, address):
self.__address = address
def set_age(self, age):
self.__age = age
def set_phone_number(self, phone_number):
self.__phone_numer = phone_number
def get_name(self):
return self.__name
def get_address(self):
return self.__address
def get_age(self):
return self.__age
def get_phone_number(self):
return self.__phone_number
def __str__(self):
return f"Name: {self.__name}\nAddress: {self.__address}\nAge: {self.__age}" +\
f"Phone Number: {self.__phone_number}"
def main():
info = []
for i in range(3):
name = input('Give name: ')
address = input('Give address: ')
age = input('Give age: ')
phone_number = input('Give phone number: ')
print()
person = Information(name, address, age, phone_number)
info.append(person)
for i in info:
print(f"Name: {i.get_name()}\nAddress: {i.get_address()}\nAge: {i.get_age()}" +\
f"Phone Number: {i.get_phone_number()}")
main() |
cab4ab98c760f3f97c671166dec90fde0030bb53 | Aviv-Cyber/Library_VOL1 | /University/yesno.py | 921 | 3.953125 | 4 | names_list = []
answers_list = []
name = input("Full name: ")
names_list.append(name)
right_answers = []
wrong_answers = []
not_a_yn_answer = []
num_of_question = []
class one:
answer = input("האם חדשנות טובה לכלכלה? : ")
num_of_question.append(1)
if answer == "yes":
right_answers.append(1)
elif answer == "no":
wrong_answers.append('class one')
else:
not_a_yn_answer.append('class one')
answers_list.append(answer)
class two:
answer = input("האם וודגווד היה בעל מפעל לכלי חרס? : ")
num_of_question.append(1)
if answer == "yes":
right_answers.append(1)
elif answer == "no":
wrong_answers.append('class two')
else:
not_a_yn_answer.append('class two')
answers_list.append(answer)
print(name + " you were right on", str(sum(right_answers)) + "/" + str(sum(num_of_question)))
|
e11554d1761aac74cdafa4f5401d524eb6e88c2b | frosyastepanovna/5sem | /lab1.py | 2,140 | 3.96875 | 4 | import math, cmath
print("ИУ5-52б Дума Эмилия Михайловна Лаб1\nПрограмма для решения (би)квадратных уравнений.\nВведите тип уравнения, которое хотите решить\n1. Квадратное\n2. Биквадратнрое")
q = int(input())
if q == 1:
args = []
i = 0
while i < 3:
try:
print("Введите коэффициент:")
args.append(float(input()))
i = i + 1
except ValueError:
print("Введите число, а не string или char")
a, b, c = args
print("Вы ввели уравнение: ",a,"x^2 +",b,"x +",c,"= 0")
D = b*b - 4*a*c
print("Дискриминант:", D)
if D > 0: print("Дискриминант положительный\nВсего 2 корня: ", "%.5f" % ((-b + math.sqrt(D))/2*a), "%.5f" % ((-b - math.sqrt(D))/2*a))
elif D == 0: print("Дискриминант равне нулю\nВсего 1 корень: ", "%.5f" % ((-b)/2*a))
elif D < 0:
print("Дискриминант меньше нуля\nВсего 2 комплексных корня: ", "%.5f" % ((-b + math.sqrt(D*-1))/2*a),"* i,", "%.5f" % ((-b - math.sqrt(D*-1))/2*a),"* i")
elif q == 2:
args = []
i = 0
while i < 3:
try:
print("Введите коэффициент:")
args.append(float(input()))
i = i + 1
except ValueError:
print("Введите число, а не string или char")
a, b, c = args
print("Вы ввели уравнение: ", a, "x^4 +", b, "x^2 +", c, "= 0")
D = b * b - 4 * a * c
print("Дискриминант:", D)
print("Всего 4 корня: \n", "%.5f" % (math.sqrt(((-b+math.sqrt((b*b-4*a*c)))/(2*a)))), "%.5f" % (math.sqrt(((-b-math.sqrt((b*b-4*a*c)))/(2*a)))))
print( "%.5f" % (-math.sqrt(((-b+math.sqrt((b*b-4*a*c)))/(2*a)))),"%.5f" % (-math.sqrt(((-b-math.sqrt((b*b-4*a*c)))/(2*a)))))
else: print("Такого типа уравнения нет, кажется, вы ошиблись :(") |
51d5356fbf82adbe3afca3889fa693ed062bd624 | jithendra2002/LabTest_01-09-2020 | /L3-copyingarrayelements.py | 312 | 3.765625 | 4 | print("Jithendra-121910313053")
a=[]
n=int(input("enter number of elements to be entered into array"))
b=[]
for i in range(0,n):
x=int(input("enter the element:"))
a.append(x)
print("original array is:",a)
l=len(a)
for c in range(0,l):
x=a[c]
b.append(x)
print("new array is:",b)
|
1c6f3192708f3e3685d0c5d79cd5a81fc3e2a453 | sakurasakura1996/Leetcode | /leetcode_weekly_competition/199weekly_competition/5472_重新排列字符串.py | 961 | 3.65625 | 4 | """
5472. 重新排列字符串 显示英文描述
通过的用户数 0
尝试过的用户数 0
用户总通过次数 0
用户总提交次数 0
题目难度 Easy
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
"""
from typing import List
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
a = list(s)
n = len(indices)
ans = []
cter = {}
for i in range(n):
cter[indices[i]] = i
for i in range(n):
ans.append(a[cter[i]])
return ''.join(ans)
solu = Solution()
s = "aiohn"
indices = [3,1,4,2,0]
ans = solu.restoreString(s,indices)
print(ans)
|
846075147226775dd91404436e08323972c456d1 | b-ark/lesson_5 | /Task2.py | 590 | 4.21875 | 4 | # Generate 2 lists with the length of 10 with random integers from 1 to 10, and make a third list containing the common
# integers between the 2 initial lists without any duplicates.
# Constraints: use only while loop and random module to generate numbers
from random import randint
random_list_1 = []
random_list_2 = []
counter = 0
while counter != 10:
random_list_1 += [randint(0, 10)]
random_list_2 += [randint(0, 10)]
counter += 1
final_list = list(set(random_list_1) & set(random_list_2))
print(f'Common between {random_list_1} and {random_list_2} ---> {final_list}')
|
fb0df889474d9eed15423d0c28dd08e98e0e5607 | imjaya/Leetcode_solved | /k_closest_point_to_oorigin.py | 658 | 3.65625 | 4 | from typing import List, Tuple
def k_closest_points(points: List[Tuple[int, int]], k: int) -> List[Tuple[int, int]]:
# WRITE YOUR BRILLIANT CODE HERE
import heapq, math
heap = []
for pt in points:
heapq.heappush(heap, (math.sqrt(pt[0] ** 2 + pt[1] ** 2), pt))
res = []
for _ in range(k):
_, pt = heapq.heappop(heap)
res.append(pt)
return res
if __name__ == '__main__':
points = []
n = int(input())
for _ in range(n):
points.append(tuple(int(x) for x in input().strip().split()))
k = int(input())
res = k_closest_points(points, k)
print('\n'.join(f'{x} {y}' for x, y in res)) |
b3e0c42ddf7f32306e93fadc244f6d55f9ed5667 | vritser/leetcode | /python/239.sliding_window_maximum.py | 631 | 3.640625 | 4 | from collections import deque
from typing import List
# https://leetcode.com/problems/sliding-window-maximum/
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = deque() # Store max k elements
ans = []
for i, v in enumerate(nums):
# Clear all elements less than v
while q and v > nums[q[-1]]:
q.pop()
q.append(i)
# Outside of the window size k
if q[0] == i - k:
q.popleft()
if i >= k - 1:
ans.append(nums[q[0]])
return ans
|
364379316c552e721da54a7354a9a63a9b31f933 | Nikitoz78/Codewars | /Shift Left/Shift Left.py | 312 | 3.75 | 4 | def shift_left(a, b):
n = 0
for i in range(len(a) + len(b)):
if len(a) >= len(b) and str(a) != str(b):
a = a[1:len(a)]
n += 1
elif len(a) < len(b) and str(a) != str(b):
b = b[1:len(b)]
n += 1
else:
continue
return n
|
fa503f3cb5b484d5c769583b3f8f09c7ed19b5bc | ndneighbor/python-the-hard-way | /exercise3/ex3sd.py | 418 | 3.9375 | 4 | # Finding out what each operator does
print 2 + 4
print 4 - 8
print 64 / 8
print 8 * 8
print 4 % 2
print 3 < 2
print 7 > 2
print 3 <= 1
print 9 >= 2
# The number excersize now in floating point
print "I will now count my imaginary chickens:"
print "Hens", 25.7 + 38.1 / 6.66
print "Roosters", 100 - 25.09 * 3.12 % 4
print "Now I count the eggs:"
print 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 + 6.00
|
c2b030b41c73b2e61b96b79aecfec929f681d68d | charusat09/LPTHW | /ex33.py | 107 | 4.03125 | 4 | print("How long you want to print?")
num = int(input("> "))
i = 1
while i <= num:
print(i)
i += 1
|
68baa25b717852c632036aaeb381f45a678a3c37 | Nicolas669/projet_logique | /dames.py | 2,152 | 3.90625 | 4 | #!/usr/bin/env python
# python script to generate SAT encoding of N-queens problem
#
# Jeremy Johnson and Mark Boady
import sys
#Helper Functions
#cnf formula for exactly one of the variables in list A to be true
def exactly_one(A):
temp=""
temp=temp+atleast_one(A)
temp=temp+atmost_one(A)
return temp
#cnf formula for atleast one of the variables in list A to be true
def atleast_one(A):
temp=""
for x in A:
temp = temp +" " +str(x)
temp=temp+" 0\n"
return temp
#cnf formula for atmost one of the variables in list A to be true
def atmost_one(A):
temp=""
for x in A:
for y in A[A.index(x):]:
temp = temp +" -"+str(x)+" -"+str(y)+" 0\n"
return temp
#function to map position (r,c) 0 <= r,c < N, in an NxN grid to the integer
# position when the grid is stored linearly by rows.
def varmap(r,c,N):
return r*N+c+1
#Read Input
if len(sys.argv)>1:
N=int(sys.argv[1])
else:
N=2
#Check for Sane Input
if N<1:
print("Error N<1")
sys.exit(0)
#Start Solver
print("c SAT Expression for N="+str(N))
spots = N*N
print("c Board has "+str(spots)+" positions")
#Exactly 1 queen per row
temp=""
for row in range(0,N):
A=[]
for column in range(0,N):
position = varmap(row,column,N)
A.append(position)
temp = temp+exactly_one(A)
#Exactly 1 queen per column
for column in range(0,N):
A=[]
for row in range(0,N):
position = varmap(row,column,N)
A.append(position)
temp = temp+exactly_one(A)
#Atmost 1 queen per negative diagonal from left
for row in range(N-1,-1,-1):
A=[]
for x in range(0,N-row):
A.append(varmap(row+x,x,N))
temp=temp+atmost_one(A)
#Atmost 1 queen per negative diagonal from top
for column in range(1,N):
A=[]
for x in range(0,N-column):
A.append(varmap(x,column+x,N))
temp=temp+atmost_one(A)
#Atmost 1 queen per positive diagonal from right
for row in range(N-1,-1,-1):
A=[]
for x in range(0,N-row):
A.append(varmap(row+x,N-1-x,N))
temp=temp+atmost_one(A)
#Atmost 1 queen per positive diagonal from top
for column in range(N-2,-1,-1):
A=[]
for x in range(0,column+1):
A.append(varmap(x,column-x,N))
temp=temp+atmost_one(A)
print ('p cnf ' + str(N*N) + ' ' + str(temp.count('\n')) + '\n')
print(temp)
|
d8718b4da18ec6915297f92350bd18c69ebb17c9 | xxNB/sword-offer | /leetcode/链表/环形链表.py | 238 | 3.609375 | 4 |
class Solution:
def hasCycle(self,head):
fast=slow=head
while fast:
fast = fast.next.next
slow = slow.next
if fast.val == slow.val:
return True
return False |
1b99447ff3477b9fb5a304b11ba1a44ee9f116c4 | LeonardoBerlatto/URI | /2427.py | 78 | 3.671875 | 4 | x = int(input())
soma = 4
while(x/2 >= 2):
x = x/2
soma = soma*4
print(soma) |
03cfd0c9336a9a35320a0c99407b4c5a994d9370 | Sushantghorpade72/100-days-of-coding-with-python | /Day-02/Day2_Tip_Calculator.py | 651 | 4.03125 | 4 | '''
Project Name: Tip calculator
Author: Sushant
Tasks:
1. Greeting for program
2. What is the total bill? 124.54
3. How many people to split the bill? 5
4. What percentage tip would you like to give?10,12 or 15?
5. Each person should pay?
'''
print("Welcome to tip calculator")
bill = float(input("What was the total bill? $"))
tip = int(input("How much tip you would like to give? 10, 12 or 15? "))
people = int(input("How many people to split the bill?"))
bill_with_tip = round(bill*(1 + tip/100),2)
split = round(bill_with_tip/people,2)
print(f"Total bill is ${bill_with_tip} and split for each person will be ${split}")
|
2d40a0de4917815fc18c1b653ea9c0cc0f5040ce | atastet/Python_openclassroom | /Chap01/variables/test_list_deref.py | 305 | 3.9375 | 4 | #!/usr/bin/python3.4
# -*-coding:Utf-8
liste = [1, 2, 3]
liste2 = list(liste)
liste2.append(4)
print("liste = {}, liste2 = {}".format(liste, liste2))
print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2)))
liste2 = liste
print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2)))
|
acb4597b9c9eb159548b45015f2cda19a64a81d3 | deebika1/guvi | /codeketa/basis/find_the_exponent_of_the_given_two_number.py | 292 | 4.125 | 4 | # program which is used to calculate the exponent of the given number
def no(num1,num2):
c=(num1**num2)
return c
# get the value of num1 and num2 from the user
num1,num2=list(map(int,input("").split()))
res1=no(num1,num2)
# print the result of the exponential of the two number
print(res1)
|
42d3fb18196e12816af55ec1c8fccc6889108c47 | Shibaram404/Example | /003_python_List_operation/in_list.py | 593 | 4.375 | 4 | myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList)
# Python offers two very powerful operators,
# able to look through the list in order to check whether a specific
# value is stored inside the list or not.
## The first of them (in) checks if a given element (its left argument)
## is currently stored somewhere inside the list (the right argument)
### - the operator returns 'True' in this case.
## The second (not in) checks if a given element (its left argument)
## is absent in a list - the operator returns 'True' in this case.
|
d53de8531cf8603bdd66ad0d16880f7381dd5f16 | thiagonantunes/Estudos | /aulas/dictionary.py | 1,370 | 4.25 | 4 | """
DICIONÁRIO
"""
d1 = {'chave1':'item 1', 'chave2': 'item2'}
d2 = dict(chave1='item 1', chave2 ='item 2') #outra maneira de criar dicionário
d2['nova_chave'] = 'novo item' # adicionando novo item no dicionário
d1['chave'] = 'item'
#para saber se uma key está no dicionário, caso não exista a chave, imprimi valor None
print(d1.get('chave', 'Not found'))
#outra maneira de mostrar o valor
print (d2['chave2'])
print(d2)
# dicionário aceita string, int e tuple como chave
d3 ={'str': 'valor', 123: 'segundo valor', (1,2): 'terceiro valor'}
#deletar chave
del d3[123]
print('segundo valor' in d3.values())
print(d3)
clientes = {'cliente1':{'nome': 'Thiago', 'sobrenome': 'Antunes'}, 'cliente2':{'nome': 'Simone','sobrenome': 'Rodrigues'}}
# for clientes_k, clientes_v in clientes.items():
# print (clientes_k)
# for dados_k, dados_v in clientes_v.items():
# print(f'\t{dados_k}: {dados_v}')
students = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
students.update({'phone': '5633-5000', 'name': 'Mary'})
print(students.get('phone', 'not found'))
del students['phone']
print(students)
age = students.pop('age')
print(students)
print(age)
"""
DICITONARY COMPREHENSION
"""
lista = [
('chave1', 'valor1'),
('chave2', 'valor 2')
]
d1 = {x: y for x, y in lista}
d2 = {f'Chave: {x}': x*3 for x in range(3,8)}
# print(d1, d2) |
8fd470ea556df326c07be86f69e36c332b89f6cf | rosezaf/rose_Challenge | /validate_creditcard.py | 441 | 3.953125 | 4 | import re
t=input()
def check(string):
for i in range(0,len(string)-3):
if string[i]==string[i+1]==string[i+2]==string[i+3]:
return False
return True
for i in range(0,t):
string=raw_input()
if check(string.replace("-",""))==False:
print"Invalid"
elif bool(re.match(r"^[4-6][0-9]{3}(-)?[0-9]{4}(-)?[0-9]{4}(-)?[0-9]{4}$",string)):
print "Valid"
else:
print"Invalid" |
3db38ce8d5677eb6a16fbc4d214d513d2ca22d28 | lord12-droidd/Colokvium-AP | /Coloc 7.py | 827 | 3.75 | 4 | """Створіть масив А [1..12] за допомогою генератора випадкових чисел з
елементами від -20 до 10 і виведіть його на екран. Замініть всі від’ємні елементи
масиву числом 0.
Мельник Д.В.
"""
import random
massive = [random.randint(-20, 10) for i in range(12)] # Генератор списку для ініцалізації масиву та його елементів
print(massive)
for i in range(len(massive)): # К-сть ітерації = довжині масиву
if massive[i] < 0: # Звертаємось по індексу,щоб отримати елемент масиву
massive[i] = 0 # Якщо він менше 0 то заміняємо його на 0
print(massive)
|
bf6324743c584d2d7f972ead4bc6a00e8ff4d1be | Fenster7/How-many-coins-1-3-5 | /How manys coins 1-3-5.py | 264 | 4.09375 | 4 | total = int(input("What is the total worth of your coins?"))
five = int(total/5)
three = int((total - (five * 5)) / 3)
one = int(total - ((five * 5) + (three * 3)))
print("You have these coins:", five, "5 coin(s)", three, "3 coin(s)", one, "1 coin(s)")
|
9499392e0ff11cec3ec148b59d8585bfcb6b862d | armelite/python-learning | /hello.py | 3,275 | 4.0625 | 4 | #i/usr/bin/env/ python3
#-*- coding:utf-8 -*-
import math
'''
print('中文测试正常')
t = (['apple','huawei','xiaomi'],[1000,2000,500],['hongkong','shanghai',
'guangzhou'])
print(t)
name = input('please enter your name:')
print('hello,',name)
age = int(input('please enter your age:'))
#print(age)
if age >= 18:
print('hello,%s,your age is %d,so you are a adult!'%(name,age))
elif age>=12:
print('hello,%s,your age is %d,so you are a teenager'%(name,age))
elif age>=6:
print('hello,%s,your age is %d,so you are a kid'%(name,age))
else:
print('hello,%s,your age is %d,so you are a baby'%(name,age))
'''
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('bad type')
if x>=0:
return x
else:
return -x
#a = int(input('please enter a number:'))
#print(my_abs(a))
def power(x,n=2):
s =1
while n >0:
n = n -1
s = s*x
return s
def product(*numbers):
sum = 1
for n in numbers:
sum =sum*n
return sum
'''
# 测试
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
# print('here')
# a = bool(product())
# print(a)
product()
print('测试成功!')
except TypeError:
print('测试失败!')
'''
# 利用递归函数移动汉诺塔:
def move(n, a, b, c):
if n == 1:
print('move', a, '-->', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
'''
#测试
move(4, 'A', 'B', 'C')
'''
#利用切片操作,实现一个trim()函数,去除字符串首尾空格
def trim(s):
for i in range(len(s)):
if s[:1]==' ':
s=s[1:]
elif s[-1:]==' ':
s=s[:-1]
return s
'''
# 测试:
if trim('hello ') != 'hello':
print('01测试失败!')
elif trim(' hello') != 'hello':
print('02测试失败!')
elif trim(' hello ') != 'hello':
print('03测试失败!')
elif trim(' hello world ') != 'hello world':
print('04测试失败!')
elif trim('') != '':
print('05测试失败!')
elif trim(' ') != '':
print('06测试失败!')
else:
print('测试成功!')
'''
#使用迭代查找一个list中最小和最大值,并返回一个tuple:
def findMinAndMax(L):
if L==[]:
return(None,None)
else:
min = L[0]
max = L[0]
for x in L:
if x <= min:
min = x
elif x > max:
max = x
return(min,max)
'''
# 测试
if findMinAndMax([]) != (None, None):
print('01测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('02测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('03测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('04测试失败!')
else:
print('测试成功!')
'''
#菲波那切数列(fibonacci)
def fib(max):
n,a,b = 0,0,1
s = [b]
while n<max:
yield b #generator 执行到yield就中断,进入下一次运算
a,b = b,a+b
n = n+1
s.append(b)
return s |
4ffe1ca99b1c12e9239d6d7bd63335b09382b023 | daniel-reich/ubiquitous-fiesta | /gdzS7pXsPexY8j4A3_22.py | 283 | 3.84375 | 4 |
def count_digits(lst, t):
result = []
for element in lst:
count = 0
for digit in str(element):
if t == "even" and int(digit)%2 == 0:
count += 1
if t == "odd" and int(digit)%2 != 0:
count += 1
result.append(count)
return result
|
28db64ea2f6e4fe76681413c8e57a729a1e66b59 | kishorebolt03/learn-python-the-hard-way | /ITVAC/problem_solving/dict_problem.py | 1,502 | 3.734375 | 4 | #sorting (NESTED DICTionary)
dict=
{
'AB':{'eng':40,'sci':50},
'RA':{'eng':10,'sci':40},
'JE':{'eng':30,'sci':60}
}
#using predefined func
l=[]
for k ,v in dict.items():
l.append(v['eng'],k)
print(sorted(l))
#using userdefined func
def sortdict(b,rev):
a=b
cnt=[i+1 for i in range(len(a))]
for j in range(1,len(a)):
if rev==True:
if a[j-1]<a[j]:
a[j-1],a[j]=a[j],a[j-1]
cnt[j-1],cnt[j]=cnt[j],cnt[j-1]
else:
if a[j-1]>a[j]:
a[j-1],a[j]=a[j],a[j-1]
cnt[j-1],cnt[j]=cnt[j],cnt[j-1]
return a
#using lambda func
print([[x[0],x[1]['eng']] for x in sorted(dict.items(),key=lambda kv: kv[1]['eng'] ,reverse=True)])
#HIGHEST of values in a class
def highest():
'''
l=[]
for k,v in d.items():
l.append([v['Eng'],k])
print(max(l))
'''
#using lambda func
sub=input("Enter subject to get highest scored student based on it\n")
print(sorted(d.items(), key=lambda x:x[1][sub],reverse=True)[0][0])
#AVERAGE of values of specific subjects in a class
def average():
avg=0
for i in d.values():
avg+=i['Eng']
print(avg//len(d))
#using lambda func
print((functools.reduce(lambda a,b:a+b,[y['eng'] for x,y in dict.items()]))//len(dict),"average")
#using sum func
print("average ------",
sum([k['eng'] for k in [d[v] for v in d.keys()]])//len(d))
|
309c2fe9731868a03834fa73f954ec9a877f0e7c | darioabadie/bairesdev | /main.py | 4,228 | 3.5625 | 4 |
# Librerías
import pandas as pd
import os
import sys
def main():
# Lectura del archivo people.in
data = []
with open (os.path.join(os.path.dirname(sys.argv[0]), "people.in"), "r") as myfile:
data.append(myfile.read())
# Parseo de los datos y ordenamiento en un dataframe
data = data[0].splitlines()
df = pd.DataFrame(data)
df[["PersonId", "Name", "LastName", "CurrentRole", "Country", "Industry", "NumberOfRecommendations",
"NumberOfConnections"]] = df[0].str.split("|",expand=True,)
df = df[["PersonId", "Name", "LastName", "CurrentRole", "Country", "Industry", "NumberOfRecommendations",
"NumberOfConnections"]]
# Ponderación de las características de los individuos
role_weight = 30 # Peso asignado al puesto
country_weigth = 20 # Peso asignado al país
industry_weight = 15 # Peso asignado a la industria
connections_factor = 1/50 # Factor asignado al número de conexiones
recommendations_factor = 1/5 # Peso asignado número de recomendaciones
# Listas utilizadas para filtrar y ponderar datos
# Lista de paises latinoamericanos
countries = ["Argentina","Bolivia","Brazil","Chile","Colombia","Ecuador","French Guiana", "Guyana","Paraguay","Peru","Suriname","Uruguay","Venezuela","Belize","Costa Rica", "El Salvador", "Guatemala", "Honduras","Mexico","Nicaragua","Panama"]
# Lista de industrias en las que BairesDev ha desarrollado soluciones
industries = ["Banking","Business Services", "Financial Services","Capital Markets","Computer Games","Consumer Goods","Design","Electrical Manufacturing","Electronics", "Electronic Manufacturing","Energy", "Resources", "Utilities","Entertainment", "Sports","Government",
"Healthcare","High Tech","Human Resources","Information Technology","Insurance","Manufacturing","Media & Information Services", "Pharmaceuticals", "Biotech",
"Publishing", "Real Estate", "Retail", "Consumer Products","Staffing", "Recruiting", "Telecommunications", "Textiles", "Tolling", "Automation", "Travel", "Transportation", "Hospitality"]
# Puestos que ocupan los clientes de BairesDev
roles = ["product manager", "VP of engineering", "SVP", "managing director", "program manager", "CTO", "business development", "director of architecture", "VP technology services", "CEO", "founder","owner", "chief executive officer",
"vice president","president","project manager","director", "supervisor"]
# Filtrado de datos
df2 = df[df["CurrentRole"] != ""] # Se eliminan los individuos que no tienen una posición definida
# Asignación de puntaje a cada individuo
df2["Score"] = df2["CurrentRole"] # Creación de la característica Score (Puntaje)
df2 = df2.reset_index()
for ind in range(0,len(df2["CurrentRole"])): # Proceso de ponderación
F_country = country_weigth if df2["Country"][ind] in countries else 0 # Ponderación por país
flag_role = 0
for role in roles: # Ponderación por puesto
if df2["CurrentRole"][ind] in role:
flag_role = 1
F_role = role_weight if flag_role == 1 else 0
F_indistry = industry_weight if df2["Industry"][ind] in industries else 0 # Ponderación por industria
F_connections = int(df2["NumberOfConnections"][ind])* connections_factor # Ponderación por número de conexiones
F_recommendations = int(df2["NumberOfRecommendations"][ind])* recommendations_factor # Ponderación por número de recomendaciones
df2["Score"][ind] = F_country + F_role + F_indistry + F_connections + F_recommendations # Puntaje final
# Selección de los 100 individuos con mayor puntaje (Posibles clientes)
df3 = df2.sort_values(by=["Score"], ascending=False)
df4 = df3[:100]
# Almacenamiento de la lista de IDs de los clientes en un archivo
with open(os.path.join(os.path.dirname(sys.argv[0]), "people.out"), 'w') as f:
for item in df4["PersonId"]:
f.write("%s\n" % item)
if __name__=='__main__':
main()
|
a89f7e79fe282bbaddd808029c7dd91c4346245d | OhOverLord/loft-Python | /алгоритмы 1 курс/(2.2.2)last_fibonacci_number.py | 835 | 3.96875 | 4 | """
Выполнил: Филиппов Л. П2-17
Задача:
Дано число 1≤n≤107, необходимо найти последнюю цифру n-го числа Фибоначчи.
"""
def fib_digit(n):
"""
Функция для нахождения последней
цифры n-го числа Фибоначчи
:param n: n-ое число Фибоначчи
:return: последняя цифра n-го числа
"""
if n < 2:
return n
else:
fib1, fib2 = 0, 1 # два первых числа фибоначчи
for i in range(1, n):
fib1, fib2 = fib2, (fib1 + fib2) % 10
return fib2
def main():
n = int(input())
print(fib_digit(n)) # вывод последней цифры n-го числа
if __name__ == "__main__":
main()
|
2dde63440235667ef0101da51c9c33fa0c10e952 | Werkov/Completion | /src/python/learning/stripTex.py | 5,641 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import argparse
import re
from string import ascii_letters
def stripTex(file):
"""Strip mathematics, content of chosen sequences, sequences and braces from TeX source."""
S_TEXT = 0
S_INLINE = 1
S_DISPLAY = 2
S_DOLLAR_IN = 3
S_DOLLAR_OUT = 4
S_SEQUENCE = 5
S_EXPECT_ARG = 6
S_OPTIONAL = 7
# sequences whose 1st argument content is not desired text
forbidden = {
'begin', 'end', 'ref', 'eqref', 'usepackage', 'documentclass',
'probbatch', 'probno', 'probpoints', 'probsolauthors', 'probsolvers', 'probavg',
'illfig', 'fullfig', 'plotfig',
'eq'
}
# -- strip comments --
lines = []
for line in file.readlines():
line += '%'
lines.append(line[:line.index('%')]) # TODO \%
# -- strip mathematics and chosen sequence's arguments --
# finite state machine with depth counter
state = S_TEXT
mode = S_TEXT
depth = 0
sequence = ''
bracketStack = [] # contains either None or index in out where sequence argument starts
out = []
for c in ''.join(lines):
#print(c, state)
if state == S_TEXT:
if c == '\\':
state = S_SEQUENCE
out.append(c)
elif c == '$':
state = S_DOLLAR_IN
elif c == '{':
out.append(c)
bracketStack.append((len(out), None))
elif c == '}':
try:
out.append(c)
i, seq = bracketStack.pop() # not to shadow "global" sequence
if seq != None and seq in forbidden:
out = out[:i]
except IndexError:
print('Unmatched right bracket.')
break
else:
out.append(c)
elif state == S_INLINE:
if c == '\\':
state = S_SEQUENCE
mode = S_INLINE
elif c == '$':
state = S_TEXT
mode = S_TEXT
elif c == '{':
bracketStack.append((len(out), None))
elif c == '}':
try:
bracketStack.pop()
except IndexError:
print('Unmatched right bracket.')
break
elif state == S_DISPLAY:
if c == '\\':
state = S_SEQUENCE
mode = S_DISPLAY
elif c == '$':
state = S_DOLLAR_OUT
elif c == '{':
bracketStack.append((len(out), None))
elif c == '}':
try:
bracketStack.pop()
except IndexError:
print('Unmatched right bracket.')
break
elif state == S_DOLLAR_OUT:
if c == '$':
state = S_TEXT
mode = S_TEXT
else:
pass # stay in display mode
elif state == S_DOLLAR_IN:
if c == '$':
state = S_DISPLAY
mode = state
else:
state = S_INLINE
mode = state
elif state == S_SEQUENCE:
if c in ascii_letters:
if mode == S_TEXT: out.append(c)
sequence += c
elif c == '[':
if mode == S_TEXT: out.append(c)
state = S_OPTIONAL
elif c == '{':
state = mode
if out[-1] == '\\': # backslashed brace
out.append(c)
else:
bracketStack.append((len(out), sequence))
sequence = ''
if mode == S_TEXT: out.append(c)
elif c == '}':
try:
out.append(c)
i, seq = bracketStack.pop() # not to shadow "global" sequence
if seq != None and seq in forbidden:
out = out[:i]
except IndexError:
print('Unmatched right bracket.')
break
else:
if mode == S_TEXT: out.append(c)
state = mode
sequence = ''
elif state == S_OPTIONAL: # here we suppose no nested [, ]
if c == ']':
if mode == S_TEXT: out.append(c)
state = S_EXPECT_ARG
else:
if mode == S_TEXT: out.append(c)
elif state == S_EXPECT_ARG:
if c == '{':
bracketStack.append((len(out), sequence))
sequence = ''
if mode == S_TEXT: out.append(c)
else:
state = mode
if mode == S_TEXT: out.append(c)
else:
print('Invalid state')
break
# end for
noMath = ''.join(out)
# -- finally simple regexp substitution --
noMath = re.sub('~', ' ', noMath)
noMath = re.sub(r'\\[a-zA-Z]+(\[[^\]]*\])?', '', noMath)
noMath = re.sub(r'[{}]', '', noMath)
print(noMath)
def main():
parser = argparse.ArgumentParser(description="Strip (La)TeX sequences from input files and concatenate them to output.")
parser.add_argument("file", help="(La)TeX file", type=argparse.FileType('r'), nargs='+')
args = parser.parse_args()
for f in args.file:
stripTex(f)
f.close()
if __name__ == '__main__':
main()
|
b4f2b525801f4a0a5467b45a1983da960594e619 | Kvazar78/Skillbox | /24_classes/dz/task_9.py | 1,112 | 3.625 | 4 | from random import choice
class Pole:
lst = [i for i in range(1, 10)]
def input(self, player, coord):
self.lst[coord - 1] = player.symbol
def print_pole(self):
count_elem = 0
print("-" * 13)
for i_elem in self.lst:
count_elem += 1
print(f'| {i_elem}', end=' ')
if count_elem % 3 == 0:
print('|')
print("-" * 13)
# def test(self):
class Player:
def __init__(self, name, sym):
self.name = name
self.symbol = sym
player1 = Player('Vasya', 'X')
player2 = Player('Roma', '0')
pole1 = Pole()
pole1.print_pole()
print(first_player)
# for _ in range(4):
# znak = input('введи координаты через пробел: ').split()
# pole1.input(znak)
# print(pole1.pole)
# count = 0
# for i_elem in pole1.pole:
# count += i_elem.count('x')
# print(count)
#
#
# field = range(1, 10)
# print("-" * 12)
# for i in range(3):
# print("|", field[0 + i * 3],
# "|", field[1 + i * 3],
# "|", field[2 + i * 3], "|")
# print("-" * 12) |
596e4aa351bc033a616d3bce885c599985ff586d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2546/60586/261559.py | 206 | 3.59375 | 4 | def exam6():
t=int(input())
for i in range(t):
p=[1,1,1]
n=int(input())
for j in range(3,n+1):
x=p[j-2]+p[j-3]
p.append(x)
print(p[n])
exam6() |
f247f7259f4550d53e797fc2657f78664f249793 | Thiagomrfs/Desafios-Python | /aula 13/desafio052.py | 338 | 3.859375 | 4 | num = int(input("Digite um número: "))
resp = 0
for c in range(1, num+1):
if num % c == 0:
print("\033[34m", end=" ")
resp += 1
else:
print("\033[31m", end=" ")
print(f"{c}", end=" ")
if resp == 2:
print(f"\n\033[34mseu número É primo")
else:
print("\n\033[31mseu número NÃO é primo!")
|
6f958d764f281796334cec6201670421ed91d759 | poojavarshneya/algorithms | /generate_pallindromic_compositions.py | 738 | 3.84375 | 4 | def generate_pallindromes(s, result, midpoint):
print ("entering: midpoint =", midpoint)
if (midpoint < 0 or midpoint == len(s)):
print(result)
return
start = midpoint
end = midpoint
while s[start] == s[end]:
start = start - 1
end = end + 1
if start < 0:
break
if end >= len(s):
break
result = result + "|" + s[start+1 : end]
print("===",result)
generate_pallindromes(s, result, midpoint - 1)
generate_pallindromes(s, result, midpoint + 1)
def generate_palindromic_decompositions(s):
results = ""
midpoint = int(len(s)/2)
generate_pallindromes(s, results, midpoint )
generate_palindromic_decompositions("abba") |
2da54b928558d794aa84797431598c75684e8076 | Imperiopolis/ccmakers-python | /Day 1/04 variables.py | 414 | 3.5 | 4 | my_name = 'Nora Autumn Trapp'
my_age = 24 # years
my_height = 71 # inches
my_eyes = 'Hazel'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "She's %d years old." % my_age
print "She's %d inches tall." % my_height
print "She's got %s eyes and %s hair." % (my_eyes, my_hair)
# this line is tricky, try to get it exactly right
print "If I add %d and %d I get %d." % (
my_age, my_height, my_age + my_height)
|
56a7bbf5fa825d0654ecd45a037cce79f5c6ddd3 | hugechuanqi/Algorithms-and-Data-Structures | /Interview/pratical_interview/hw_0002、矩阵相邻搜索.py | 5,807 | 3.9375 | 4 | ## 题目:矩阵相邻搜索
## 类型:矩阵,回溯法
## 应用:涉及到机器人行走路径
## 题目描述:给定一个矩阵,然后给你一个路径,matrix=[[1,2,3,4,5],[11,12,13,14,15],[21,22,23,24,25],[31,32,33,34,35],[41,42,43,44,45]],path=[1,2,3,4,5,11],并且矩阵中的路径可以超出限制,判断是否存在所给定路径
## 核心:1、如何找到第一个路径点;2、如何沿着这条路径依次行走,包括向上、向下、向左、向右,每次都得判断是否超出边界;3此题似乎可以超出边界。
## 思路:首先输入一个矩阵和路径,首先???
# python知识扩展:对于if j+1<cols and matrix[i][j+1] == path[0]:,首先判断第一个条件j+1<cols是否满足,如果不满足则第二个条件不会执行,满足才会执行。
class Solution:
def hasPath(self, matrix, rows, cols, path):
""" 找到起点,并开始行走
"""
for i in range(rows):
for j in range(cols):
if matrix[i][j] == path[0]:
if self.find2(matrix, rows, cols, path[1:], i, j):
return True
return False
def find(self, matrix, rows, cols, path, i, j):
""" 开始递归判断上下左右哪个路径符合行走路径
"""
if not path:
return True
matrix[i][ j] = '0' # 将找过的值赋值为0
# print(i, j, path, rows, matrix[i+1][j])
if j+1<cols and matrix[i][j+1] == path[0]:
print(matrix[i][j+1], matrix)
return self.find(matrix, rows, cols, path[1:], i, j+1) # 向右寻找
elif j-1>=0 and matrix[i][j-1] == path[0]:
print(matrix[i][j-1], matrix)
return self.find(matrix, rows, cols, path[1:], i, j-1) # 向左寻找
elif i+1<rows and matrix[i+1][j] == path[0]:
print(matrix[i+1][j], matrix)
return self.find(matrix, rows, cols, path[1:], i+1, j) # 向下寻找
elif i-1>=0 and matrix[i-1][j] == path[0]:
print(matrix[i-1][j], matrix)
return self.find(matrix, rows, cols, path[1:], i-1, j) # 向上寻找
else:
return False
def find2(self, matrix, rows, cols, path, i, j):
if not path:
return True
matrix[i][ j] = '0' # 将找过的值赋值为0
print(i, j, path, rows, cols, matrix[i+1][j], j+1==cols)
if j+1<cols and matrix[i][j+1] == path[0]:
print(matrix[i][j+1], matrix)
return self.find2(matrix, rows, cols, path[1:], i, j+1) # 向右寻找
elif j-1>=0 and matrix[i][j-1] == path[0]:
print(matrix[i][j-1], matrix)
return self.find2(matrix, rows, cols, path[1:], i, j-1) # 向左寻找
elif i+1<rows and matrix[i+1][j] == path[0]:
print(matrix[i+1][j], matrix)
return self.find2(matrix, rows, cols, path[1:], i+1, j) # 向下寻找
elif i-1>=0 and matrix[i-1][j] == path[0]:
print(matrix[i-1][j], matrix)
return self.find2(matrix, rows, cols, path[1:], i-1, j) # 向上寻找
elif i-1 == -1 and 0<=j<=cols-1: # 超出上边边界
print("ok")
i = rows-1
if j+1<cols and matrix[i][(cols+ j+1)//cols] == path[0]:
print(matrix[i][j+1], matrix)
return self.find2(matrix, rows, cols, path[1:], i,(cols+ j+1)//cols) # 向右寻找
elif j-1>=0 and matrix[i][(cols+j-1)//cols] == path[0]:
print(matrix[i][j-1], matrix)
return self.find2(matrix, rows, cols, path[1:], i, (cols+j-1)//cols) # 向左寻找
elif i+1 == rows and 0<=j<=cols-1: # 超出下边边界
i = 0
if matrix[i][(cols+j+1)//cols] == path[0]:
print(matrix[i][(cols+j+1)//cols], matrix)
return self.find2(matrix, rows, cols, path[1:], i, (cols+ j+1)//cols) # 向右寻找
elif matrix[i][(cols+j-1)//cols] == path[0]:
print(matrix[i][(cols+j-1)//cols], matrix)
return self.find2(matrix, rows, cols, path[1:], i, (cols+j-1)//cols) # 向左寻找
elif j-1 == -1 and 0<=i<=rows-1: # 超出左边边界
j = cols-1
if i+1<rows and matrix[(rows+i+1)][j] == path[0]:
print(matrix[(rows+i+1)][j], matrix)
return self.find2(matrix, rows, cols, path[1:], (rows+i+1)//rows, j) # 向下寻找
elif i-1>=0 and matrix[(rows+i-1)//rows][j] == path[0]:
print(matrix[(rows+i-1)//rows][j], matrix)
return self.find2(matrix, rows, cols, path[1:], (rows+i-1)//rows, j) # 向上寻找
elif j+1 == cols and 0<=i<=rows-1: # 超出右边边界
print("ok")
j = 0
print(i,j, matrix[ (rows+i+1)//rows][j])
if i+1<rows and matrix[ (rows+i+1)//rows][j] == path[0]:
print(matrix[i+1][j], matrix)
return self.find2(matrix, rows, cols, path[1:], (rows+i+1)//rows, tmp) # 向下寻找
elif i-1>=0 and matrix[ (rows+i+1)//rows][j] == path[0]:
print(matrix[i-1][j], matrix)
return self.find2(matrix, rows, cols, path[1:], (rows+i-1)//rows, j) # 向上寻找
else:
return False
import sys
if __name__ == "__main__":
matrix = [[1,2,3,4,5],[11,12,13,14,15],[21,22,23,24,25],[31,32,33,34,35],[41,42,43,44,45]]
rows, cols = 5,5
# for line in sys.stdin:
# path = line.split()
path = [1,2,3,4,5,11]
a = Solution()
if a.hasPath(matrix, rows, cols, path):
print('1')
else:
print('0')
## 测试用例:
# [5,15,25,35,45,1]
# [1,2,3,4,5,11]
|
1b20d13f321d69e85a70108902b7e11d9e5e3f09 | kc4v/CSE | /Trenten Williams - World Map OOF.py | 5,427 | 3.609375 | 4 | class Room(object):
def __init__(self, name, north, south, east, west, description):
self.name = name
self.east = east
self.north = north
self.south = south
self.west = west
self.description = description
def move(self, direction):
global current_node
current_node = globals()[getattr(self, direction)]
# Initialize Rooms
door = Room("Door", None, None, "hallway", None, "Just ran inside after being chased from some zombies, \n"
"*check pockets for keys*, are"
" you serious, now I have to search the house for the keys to the \n"
"shed since I forgot to take them, but \n"
"I got to be ready for anything, \n"
"I still don't know if there inside, \n"
"I need to find a weapon and close all the windows so this place can\n"
"be safe again, for now I have to is go unarmed.")
hallway = Room("Hallway", None, "kitchen", "closet", "door", "I can go to the closet to the West or go to the \n"
"Kitchen to the South, or just go back to the door."
"We need to go upstairs to get the key to the \n"
"shed but we can get a weapon before we go, \n"
"there's a Den to the East.")
closet = Room("Closet", None, "living_room", None, "hallway", "I'm at the closet, there might be something inside, \n"
"if not I can go to the living room to the south.")
living_room = Room("Living Room", "closet", None, None, "stairs", "There are 2 windows in here, I better close \n"
"them before zombies crawl through.")
stairs = Room("Stairs", None, "hallway2", "living_Room", "den", "We need to go upstairs to get the key to the \n"
"shed(South) but we can get a weapon before \n"
"we go, there's a Den to the East.")
den = Room("Den", "kitchen", None, "stairs", None, "Another window, need to close it.")
kitchen = Room("Kitchen", "hallway", "den", None, None, "Nice, there is still a knife here.")
hallway2 = Room("Hallway2", "stairs", "master_Bedroom", "bathroom", "hallway3", "I can go to the bathroom to the \n"
"east but I hear sound in there, or \n"
"just go to the master bedroom to \n"
"the south, there is another \n"
"hallway to the East.")
hallway3 = Room("Hallway3", "room1", "room3", "hallway2", "room2", "I can go back to the second hallway to the \n"
"West, or go to room3 to the North, \n"
"room2 to the South or room1 to the east.")
bathroom = Room("Bathroom", None, None, None, "hallway2", None)
room1 = Room("Room1", None, "hallway3", None, None, "The key is not in here, but there is a window \n"
"so I better close it.")
room2 = Room("Room2", None, None, "hallway3", None, "The key is not in here, but there is a window \n"
"so I better close it.")
room3 = Room("Room3", "hallway3", None, None, None, "The key is not in here, but there is a window \n"
"so I better close it.")
master_bedroom = Room("Master_Bedroom", "hallway2", None, None, None, "The key is not in here also, \n"
"but there is a window so I better close it.")
shed_door = Room("Shed_Door", None, None, None, "hallway4", "I finally got in the shed, now I have to grab a gun.")
hallway4 = Room("Hallway4", "sniper Room", "assault Room", "shed_door", None, "There is snipers to the North \n"
"and some assault rifles to the South.")
assault_room = Room("Assault_Room", "hallway", None, None, None, "ok, seems like going with the assault rifles.")
sniper_room = Room("Sniper_Room", None, "hallway4", None, None, "ok, seems like going with the snipers rifles.")
directions = ['north', 'south', 'east', 'west']
current_node = door
while True:
print(current_node.name)
print(current_node.description)
command = input('>_')
if command == 'quit':
quit(0)
if command in directions:
try:
current_node.move(command)
except KeyError:
print("You cannot go this way.")
else:
print("Command not recognized")
print()
|
762b5c437a735f329e31508dd3aa3abb248179bc | soraoo/python_study | /basic/09_class/exercise.py | 958 | 4.09375 | 4 | class Dog:
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗收到命令时蹲下"""
print(f'{self.name} is now sitting')
def roll_over(self):
"""模拟小狗收到命令时打滚"""
print(f'{self.name} rolled over!')
my_dog = Dog('Willie', 6)
print(my_dog.name)
print(my_dog.age)
my_dog.sit()
my_dog.roll_over()
# 9-1
class Restaurant:
"""餐馆"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f'{self.restaurant_name} - {self.cuisine_type}')
def open_restaurant(self):
print('opening')
my_restaurant = Restaurant('牛肉', '烧饼')
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
|
57085bda8fcc493bbce9dad20a617648250866a2 | ksrntheja/08-Python-Core | /venv/modules/31RandRangeFunction.py | 333 | 3.734375 | 4 | from random import *
for i in range(5):
print(randrange(5))
print()
for i in range(10):
print(randrange(1, 11))
print()
for i in range(10):
print(randrange(1, 11, 2))
print()
print(randrange(0, 101, 10))
# 3
# 4
# 4
# 3
# 2
#
# 8
# 5
# 8
# 2
# 6
# 7
# 4
# 2
# 5
# 4
#
# 7
# 3
# 5
# 9
# 3
# 5
# 9
# 1
# 9
# 3
#
# 0
|
8abcb5e660edb1c52d1bac697ae7dffeb3aaad99 | Kenterbery/Discrete_labs | /lab5/main.py | 2,220 | 3.5625 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter.font import Font
import combinatorics
class MainWindow(Tk):
def __init__(self):
super().__init__()
self.initFonts()
self.initUI()
def initFonts(self):
"""Ініціалізація шрифтів, кольорів"""
self.color = "#8bb2d3"
self.font_H1 = Font(self, name="font_H1", family="Verdana", size=18)
self.font_p = Font(self, name="font_p", family="Verdana", size=14)
self.font_button = Font(self, name="font_button", family="Verdana", size=10)
def initUI(self):
self.title("Комбінаторика")
self.center()
self["bg"] = self.color
# Фрейм з імʼям
self.frame_name = Frame(self, bg="#8bb2d3", bd=5)
self.lbl_name = Label(self.frame_name, text="Бабко Дмитро, ІО-63", bg="#8bb2d3", font="font_H1")
self.lbl_var = Label(self.frame_name, text="Варіант: 5", bg="#8bb2d3", font="font_p")
self.btn_start = Button(self, text="Розпочати роботу", command=self.nextwin, underline="0", bg="silver",
font="font_button")
# grid
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.frame_name.grid(sticky="nwes")
self.lbl_name.grid(row=0, column=0, sticky="nwe")
self.lbl_var.grid(row=1, column=0, sticky="swe")
self.btn_start.grid(row=2, column=0, sticky="nswe")
self.protocol("WM_DELETE_WINDOW", self.messagequit)
def nextwin(self):
second = combinatorics.Combinatorics()
self.destroy()
def messagequit(self):
"""Метод визову messagebox для виходу з програми"""
if messagebox.askyesno("Quit", "Завершити роботу?"):
sys.exit()
def center(self):
"""Метод центрування вікна"""
x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
self.wm_geometry("+%d+%d" % (x, y))
if __name__ == "__main__":
root = MainWindow()
root.mainloop()
|
f4aaccfedc50219552853a8e681c934af8205ca9 | krish-bajaj123/Miscellaneous-Python | /greatest numer.py | 171 | 3.96875 | 4 | a,b=int(input("enter 2 numbers")),int(input())
if(a>b):
print("a is the greatest")
elif(a==b):
print("both are equal")
else:
print("b is the greatest")
|
e0a0f1495c0c36d6565ba2febd6fdf0cd6038e35 | minhduc9699/PhamMinhDuc-fundamental-c4e16 | /S2/BMI.py | 599 | 4.40625 | 4 | height = float(input('what is your height? (cm) '))
weight = float(input('what is your weight? (kg)'))
#convert unit from cm to m
height_cm = height / 100
#BMI calculate
BMI = weight / (height_cm * height_cm)
print('your height is: %.f (cm) = %.2f (m)' % (height, height_cm))
print('your weight is: %.f (kg)' % (weight))
print('your BMI is: %.2f' % (BMI))
#BMI check:
if BMI < 16:
print('your are severely underweigh')
elif BMI < 18.5:
print('you are underweigh')
elif BMI < 25:
print('you are normal')
elif BMI < 30:
print('you are overweight')
else:
print('you are obese')
|
8dffd3321dd26680435d9111b1c42e96db866ac0 | diegolinkk/exercicios-python-brasil | /exercicios-com-listas/exercicio11.py | 516 | 4.25 | 4 | #Altere o programa anterior, intercalando 3 vetores de 10 elementos cada.
vetor_1 = []
vetor_2 = []
vetor_3 = []
for i in range(10):
vetor_1.append(int(input("Digite um número inteiro: ")))
vetor_2.append(int(input("Digite outro número inteiro: ")))
vetor_3.append(int(input("Digite outro número inteiro: ")))
vetor_mesclado = []
for i in range(len(vetor_1)):
vetor_mesclado.append(vetor_1[i])
vetor_mesclado.append(vetor_2[i])
vetor_mesclado.append(vetor_3[i])
print(vetor_mesclado) |
e6f003175605dc8f6adc845dbe1ac054b1a740fa | developyoun/AlgorithmSolve | /solved/2475.py | 110 | 3.515625 | 4 | numbers = list(map(int, input().split()))
total = 0
for num in numbers:
total += num**2
print(total % 10) |
c42a4d6e361de3e4d9675f2ee7b9ad8565ad0955 | reed-qu/leetcode-cn | /RemoveNthNodeFromEndOfList.py | 1,628 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/19 下午12:06
# @Title : 19. 删除链表的倒数第N个节点
# @Link : https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
QUESTION = """
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
"""
THINKING = """
问题在于如何遍历一遍之后回头找到倒数n内个位置,然后倒数n+1.next = 倒数n-1就可以
思路是从头往后遍历,用列表记录每一次的节点,然后回头用n来索引就可以了
但是列表的两头,第一位和最后一位需要特殊处理,还有链表只有1个节点的时候
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
nodes = []
size = 0
while head:
size += 1
nodes.append(head)
head = head.next
if n == 1:
if size == 1:
return None
else:
nodes[-2].next = None
elif n == size:
return nodes[1]
else:
nodes[-n-1].next = nodes[-n+1]
return nodes[0]
if __name__ == '__main__':
s = Solution()
head = ListNode(1)
x = 1
print(s.removeNthFromEnd(head, x))
|
4067a4a09fa24ff2468fcb79b0d342246730ea97 | DolanDark/Data-Science-projects | /BioInfomatics/DNA count.py | 1,976 | 3.546875 | 4 | import pandas
import streamlit
import altair
from PIL import Image
dna_image = Image.open("gettyimage.jpg")
streamlit.image(dna_image, use_column_width=True)
streamlit.write("""
# DNA Count Neucleotide
This app counts the neucleotide composition of query DNA
***
""")
streamlit.header("Enter the DNA sequence - ")
seq_input = "> DNA Query\nATCGGCATAAAGCTAGCTGGCGTACGCTATGTCGATCGTCGAT\nCGTATCGATCATCGATGTACATGACGATGCATCTAGCGCATGTA\nCATGCTTCGAAGCTGATAGTGAGCATGTAGCATAGAGCTAATC"
seq = streamlit.text_area("Input Sequence - ", seq_input, height = 250)
seq = seq.splitlines()
seq = seq[1:]
seq = "".join(seq)
streamlit.write('''
***
''')
streamlit.header("Inputed DNA query")
streamlit.write(seq)
streamlit.header("Output DNA Neucleotide count")
streamlit.subheader("1 - Print Dictionary")
def dna_nucleotide_count(sequen):
d = dict([
("A", sequen.count("A")),
("T", sequen.count("T")),
("G", sequen.count("G")),
("C", sequen.count("C"))
])
return d
X = dna_nucleotide_count(seq)
streamlit.write(X)
streamlit.subheader("2 - Print text")
streamlit.write("There are " + str(X["A"]) + " Adenaine (A)")
streamlit.write("There are " + str(X["T"]) + " Thymine (T)")
streamlit.write("There are " + str(X["G"]) + " Guanine (G)")
streamlit.write("There are " + str(X["C"]) + " Cytocinine (G)")
streamlit.subheader("3 - Display Dataframe")
DF = pandas.DataFrame.from_dict(X, orient="index") #take val from dictionary to plot
DF = DF.rename({0:"count"}, axis="columns") #renaming the column
DF.reset_index(inplace=True)
DF = DF.rename(columns = {"index": "nucleotide"})
streamlit.write(DF)
streamlit.subheader("4 - Display Bar Chart")
BAR = altair.Chart(DF).mark_bar().encode(x = 'nucleotide', y = 'count')
BAR = BAR.properties(
width=altair.Step(50) #controls width of bar
)
streamlit.write(BAR)
|
30588ec75a6c20bffa7b3d1397184270c5705c34 | MichelFeng/leetcode | /27.py | 592 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
"""description"""
def removeElement(self, nums, val):
"""TODO: Docstring for removeElement.
:returns: TODO
"""
if not nums:
return 0
n = len(nums)
l = 0
while l < n:
if nums[l] != val:
l += 1
else:
nums[l] = nums[n-1]
n -= 1
return n
if __name__ == "__main__":
s = Solution()
nums = [0,1,2,2,3,0,4,2]
val = 2
print(s.removeElement(nums, val))
|
96b9b0a0f5a530fda756f8669e5e35f3f7603856 | ChristianBalazs/DFESW3 | /printend.py | 667 | 3.890625 | 4 |
listVar = ['violin', 'viola', 'cello','traingle', 'harp', 'flute']
print('')
print(listVar[-3])
print('')
# to print item at position -3
listLen=len(listVar)
print(listVar[-listLen])
# to print item at position -lenght o the list = first on the list
print(' ')
# For loop
for tempVar in listVar:
print(tempVar)
# While loop
inputNum = int(input("Type in whole num: "))
answerVar = 1
while inputNum > 0:
answerVar = answerVar * inputNum
inputNum = inputNum - 1
print(answerVar)
# Modulus
print(7 // 4) #how many times 4 gets into 7 = 1
print(7 % 4) #whole no remainder after division = 3
print(7 / 4) #normal division with decimals = 1.75
|
82ce44a2e82d6bb4446ec99f70a5ce50b42e664a | emrekardaslar/HackerRank-Questions | /Problems Solving Questions/dayOfProgrammer.py | 571 | 3.875 | 4 | def checkLeap(year):
if ( (year <= 1917) and (year%4 == 0) or (( year%400 == 0) or (( year%4 == 0 ) and ( year%100 != 0)))):
return True
elif (year == 1918):
return True
else:
return False
def dayOfProgrammer(year):
check=checkLeap(year)
if check == True and year == 1918:
print("26.09.1918")
elif check == True:
print("12.09." + str(year))
elif check == False:
print("13.09." + str(year))
if __name__ == '__main__':
year = int(input())
dayOfProgrammer(year)
|
631e47868021d1bce89292c230803398fd53ffc7 | Mihyar-30614/Backtracking_Algorithm | /KnightTour.py | 1,589 | 3.765625 | 4 | # Cheesboard size
size = 8
# Helper Function to print Solution
def printSolution(board):
for i in range(size):
for j in range(size):
print(str(board[i][j]).zfill(2), end=' ')
print()
# Helper function to check if i,j are in n*n board
def isSafe(board, new_x, new_y):
if (new_x >= 0 and new_y >= 0 and new_x < size and new_y < size and board[new_x][new_y] == -1):
return True
return False
# Solver function to solve the issue
def solver(board, current_x, current_y, move_x, move_y, counter):
# If all visited, we're done
if counter == size**2:
return True
# Try all the possible solutions for current position
for i in range(8):
new_x = current_x + move_x[i]
new_y = current_y + move_y[i]
if isSafe(board, new_x, new_y):
board[new_x][new_y] = counter
if solver(board, new_x, new_y, move_x, move_y, counter+1):
return True
else:
# Backtracking solution
board[new_x][new_y] = -1
return False
# Driver Function
if __name__ == "__main__":
# Initialize Board with -1, Knight start at first position
board = [[-1 for i in range(size)] for i in range(size)]
board[0][0] = 0
# Possible moves for a Knight
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
# Counter for the Knight's move
counter = 1
if not solver(board, 0, 0, move_x, move_y, counter):
print("Solution could not be found.")
else:
printSolution(board) |
0e6fad420262eb7a9911666280508603df5dc146 | jakesant/dsa-assignment | /q12.py | 547 | 4.21875 | 4 | #Write a function that returns the sum of the first n numbers of the
#Fibonacci sequence. The first 2 numbers in the sequence
#are 1,1, …
def sum_fib(nterms):
x = nterms
sum = 0
while nterms != 0:
sum += fib(nterms)
nterms -= 1
print("The sum of the first", x, "values is", sum)
def fib(n): #Recursive Fibonacci program
if(n<0):
print("The number entered cannot be negtive")
elif(n==1):
return 1
elif(n==2):
return 1
else:
return fib(n-1) + fib(n-2)
sum_fib(5) |
3e3321a59f23adbf1be87c8f74d6e30063a9326b | abueesp/mathstuffinc | /bitscalc.py | 773 | 4.3125 | 4 | ## Bits Calc ##
## Author: Abueesp ##
## Date: Tue, May 23 2015 ##
## License: CC NC-BY-SA ##
scriptname = 'Bits Calc'
prompt = '> '
print "Hello, I'm the", scriptname, "a pretty dumb code for calculating bits"
print "Introduce the number of bits: "
bits = int(raw_input(prompt))
bytes= bits/8
print "You have", bits, "bits, which are", bytes, "words of 8-bits also known as bytes."
print "\n"
print "Which represent the following bit positions"
if (bits % 2 == 0):
for i in range(bits/2):
print 1,
elif(bits % 2 == 1):
for i in range((bits-1)/2):
print 1,
print 0
else:
print 'Was that a number?'
print "\n"
possibilities=2**bits
dualities=possibilities/2
print "Which represent", possibilities, "possibilities, or", dualities, "dualities."
print "\n"
|
48f6447b7442ebadcd362e6cff7d3d719d61143f | kailash-manasarovar/A-Level-CS-code | /functional_programming/lambda.py | 1,188 | 4.21875 | 4 | ## writing lambda functions in Python
# ## simple addition and multiplication
# function = lambda a : a + 15
# print(function(10))
# function = lambda x, y : x * y
# print(function(12, 4))
#
#
# ## sort a list of tuples
# # https://docs.python.org/3/howto/sorting.html - lots of sorting options
# subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
# print("Original list of tuples:")
# print(subject_marks)
# subject_marks.sort(key = lambda x: x[1])
# print("\nSorting the List of Tuples:")
# print(subject_marks)
## fibonacci
from functools import reduce
fib_series = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]],
range(n - 2), [0, 1])
print("Fibonacci series upto 2:")
print(fib_series(2))
print("\nFibonacci series upto 3:")
print(fib_series(3))
print("\nFibonacci series upto 4:")
print(fib_series(4))
print("\nFibonacci series upto 9:")
print(fib_series(9))
# ## palindromes
# texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"]
# print("Orginal list of strings:")
# print(texts)
# result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
# print("\nList of palindromes:")
# print(result) |
d269f0fd67b790c90dec731ef68b5fa6f32b9c32 | damv00/da-academy-pycharm | /Repaso/Matrix_programs/Tic_tac_toe1.py | 1,107 | 4.4375 | 4 | '''
Draw A Game Board
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more).
Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s print statement.
'''
def lineas(n):
lista1 = []
for i in range(n):
lista1.append(" ")
for j in range(3):
lista1.append("-")
lista1 = "".join(lista1)
print(lista1)
def columna(n):
lista2 = []
for i in range(n):
lista2.append("|")
for j in range(3):
lista2.append(" ")
if i + 1 == n:
lista2.append("|")
lista2 = "".join(lista2)
print(lista2)
size=input("What size game board do you want me to draw: ")
size=int(size)
for i in range(size):
lineas(size)
columna(size)
if i+1==size:
lineas(size)
game = [[1, 2, 0],
[2, 1, 0],
[2, 1, 1]]
|
c3208e83d10e9e4a13eb668bb92ab74e49fb0d8a | prathy16/LeetCode | /word_ladder.py | 1,507 | 3.8125 | 4 | '''
Problem: https://leetcode.com/problems/word-ladder/
'''
from collections import deque
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
def dict_words(wordList):
d = {}
for word in wordList:
for i in range(len(word)):
s = word[:i] + "_" + word[i+1:]
d[s] = d.get(s, []) + [word]
return d
def steps_queue(beginWord, endWord, d):
queue, visited = deque([(beginWord, 1)]), set()
while(queue):
word, steps = queue.popleft()
if word == endWord:
return steps
if word not in visited:
visited.add(word)
for i in range(len(word)):
s = word[:i] + "_" + word[i+1:]
for each_word in d.get(s, []):
if each_word not in visited:
queue.append((each_word, steps+1))
if(each_word == endWord):
return (steps + 1)
return 0
d = dict_words(wordList)
return steps_queue(beginWord, endWord, d)
|
013eae7b31590b2671a35ace62d2906d31b50483 | himraj123456789/competitive-programming- | /breaking_the_records.py | 1,665 | 3.5 | 4 | import os
import sys
import random
import math
def binary_find(t,r):
l1=0
r1=len(r)-1
while(l1<=r1):
mid=int((l1+r1)/2)
if(r[mid]==t):
return mid+1
break
if(r[mid]<t):
if(r[mid-1]>t):
return(mid+1)
break
else:
r1=mid-1
l1=l1
if(r[mid]>t):
if(r[mid+1]<t):
return mid+2
break
else:
l1=mid+1
r1=r1
def climbingLeaderboard(x12,t12):
l=[]
i=0
j=1
while True:
if(x12[i]>x12[j]):
l.append(x12[i])
j=j+1
i=j-1
if(j==len(x12)):
break
if(x12[i]==x12[j]):
j=j+1
p=j
if(j==len(x12)):
break
l.append(x12[len(x12)-1])
n=0
while(n!=len(t12)):
select=t12[n]
if(select>=l[0]):
print(1)
elif(select<l[len(l)-1]):
print(len(l)+1)
elif(select==l[len(l)-1]):
print(len(l))
else:
result=binary_find(select,l)
print(result)
n=n+1
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
scores_count = int(input())
x11 = list(map(int, input().rstrip().split()))
alice_count = int(input())
t11= list(map(int, input().rstrip().split()))
#x11=[100,90,90,80,75,60]
#t11=[50,65,77,90,102]
climbingLeaderboard(x11,t11)
#fptr.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.