blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
206de95ed94e47b3e7acc0adaf20fd8ebb29462a | BristolTopGroup/DailyPythonScripts | /dps/legacy/tools/Table.py | 407 | 3.59375 | 4 |
#Class to represent a table and manipulate the string representation
class Table():
#create a table with a header (first row) and a footer (last row)
def __init__(self, header = True, footer = False):
self.rows = []
def addrow(self, row):
self.rows.append(row)
def convertToTwikiEntry(self):
pass
def convertToLatex(self):
pass |
372c97891bd42376a5a6b85714c63222117709e7 | tofritz/example-work | /py4e/Ch10/ex_10_01.py | 462 | 3.8125 | 4 | fname = input('Enter a filename:')
try:
fhand = open(fname, 'r')
except:
print('Invalid filename:', fname)
quit()
emails = dict()
for line in fhand:
words = line.split()
if len(words) >= 2 and words[0] == 'From':
emails[words[1]] = emails.get(words[1], 0) + 1
lst = list()
for address, count in list(emails.items()):
lst.append((count, address))
mostcommon = sorted(lst, reverse=True)[0]
print(mostcommon[1], mostcommon[0])
|
e138469afc2da8d9df1085e028a7b101db8c567e | Success2014/Leetcode | /implementStrStr.py | 1,084 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 18:32:18 2015
Implement strStr().
Returns the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
@author: Neo
"""
class Solution:
# @param {string} haystack
# @param {string} needle
# @return {integer}
"""brute force, two pointers"""
def strStr(self, haystack, needle):
lenH = len(haystack)
lenN = len(needle)
if lenH < lenN:
return -1
for i in xrange(lenH - lenN + 1): # first pointer i, for haystack
j = 0 # second pointer j, for needle
k = i # temporary pointer, to loop in haystack
while j < lenN:
if needle[j] == haystack[k]:
j += 1
k += 1
else:
break
if j == lenN:
return i
return -1
sol = Solution()
print sol.strStr("abcdef","ef")
|
7c2a0890e57c867a441ad2cfd318c8240d1a7554 | JohnGoure/leetcode-solutions | /addLinkedList.py | 815 | 3.65625 | 4 | from singlyLinkedList import LinkedList as ListNode
def addTwoNumbers(L1, L2):
arr1 = []
arr2 = []
while(L1.val != None):
arr1.append(L1.val.data)
L1.val = L1.val.next
while(L2.val != None):
arr2.append(L2.val.data)
L2.val = L2.val.next
# no reverse if numbers are entered forward
arr1.reverse()
arr2.reverse()
num1 = ''.join(str(x) for x in arr1)
num2 = ''.join(str(x) for x in arr2)
sum = [int(i) for i in str(int(num2) + int(num1))]
sum.reverse()
sumList = ListNode(sum[0])
for i in range(sum):
temp = sumList.val
return sumList
newList = ListNode(7)
newList.push(1)
newList.push(6)
secondNewList = ListNode(5)
secondNewList.push(9)
secondNewList.push(2)
print(addTwoNumbers(newList, secondNewList)) |
44815240466575dd95ddf8149c7b222d96acb083 | IzumiHoshi/My-Python-Code | /test_code/erciyuan.py | 196 | 3.609375 | 4 | import math
def quadratic(a, b, c):
temp = math.sqrt((b * b - 4 * a * c) / 4 * a * a)
x1 = -(b / 2 * a) - temp
x2 = -(b / 2 * a) + temp
return x1, x2
print(quadratic(1, 2, 1))
|
501d44a42e9482d1177051b5d0733a8575b21922 | cah835/Data-Structures | /Homework 7/#9 sql.py | 488 | 3.84375 | 4 | # Open the database
import sqlite3
connection = sqlite3.connect('mcu.db')
# Display the all customers
cursor = connection.cursor()
cursor.execute("SELECT distinct characters.name from characters, teamUps where characters.name = 'Howard Stark' and member1 = characters.id or member2 = characters.id intersect SELECT distinct characters.name from characters, teamUps where characters.name = 'Peggy Carter' and member1 = characters.id or member2 = characters.id ")
for row in cursor:
print(row)
|
0d680536267450fedcf13d6eff6f7c07caa28d1d | augustedupin123/python_practice | /p54_without_using_pow.py | 333 | 4.25 | 4 | #If a number is power of another no. without using pow
def function1(a,b):
prod = 1
while(prod<b):
prod *=a
if(prod == b):
print('the no. is a power')
else:
print('the no. is not a power')
m = int(input('enter a'))
n = int(input('enter b'))
print (function1(m,n))
|
b010fe28626c6cfcd354329d0517cc688ea9e852 | wtrnash/LeetCode | /python/047全排列II/047全排列II.py | 1,121 | 3.609375 | 4 | """
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
"""
# 解答:类似046题,主要需要去重,所以每次交换,对于同样的数字,只交换一次,所以需要判断前面有没有相同的,有则不做交换
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
self.dfs(result, nums, 0)
return result
def dfs(self, result, nums, start):
if start >= len(nums) - 1:
result.append(nums[:])
return
for i in range(start, len(nums)):
if self.needSwap(nums, start, i):
nums[start], nums[i] = nums[i], nums[start]
self.dfs(result, nums, start + 1)
nums[start], nums[i] = nums[i], nums[start]
def needSwap(self, nums, start, end):
for i in range(start, end):
if nums[i] == nums[end]:
return False
return True |
cf3fd09a7531ff09326b58d4a6c1d40ebaad86c0 | juncid/RWProyects-Python-3x | /Working with Email/3_2-working_with_external_files.py | 445 | 3.53125 | 4 |
f = open("contacts.txt", 'w')
f.write("Mickey Mouse|[email protected]|Y\n")
f.close()
f = open("contacts.txt", 'a')
f.write("Donald Duck|[email protected]|Y\n")
f.close()
f = open("contacts.txt", 'r')
contacts = f.read()
print(contacts)
def read_contacts(file_name):
f = open("contacts.txt", 'r')
data = f.read().split('|')
contacts = []
for contact in data:
if len(contact)> 0:
contacts.append(contact.split('|'))
return contacts
|
6046370ac8bc486d0473a0d8b4b533f7dc42b7d9 | zywangzy/fun_with_flags | /source/funwithflags/gateways/db_gateway_abc.py | 464 | 3.5 | 4 | """Module for the DbGateway abstract base class."""
from abc import ABC, abstractmethod
from typing import Any
class DbGateway(ABC):
"""Abstract base class for DbGateway defining the interfaces to interact with
a database, including read / write / update / delete database table entries.
"""
@abstractmethod
def query(self, command: str) -> Any:
"""Given a `command` string, do the query and return result of type `Any`.
"""
|
ac0637e7df2f0f05c8abb73e72c21467e67a0cf7 | ysjin0715/python-practice | /chapter9/supermarket.py | 673 | 3.625 | 4 | #편의점 재고 관리
import sys
item={'종이컵':2,'우유':1}
item['커피음료']=7
item['펜']=3
item['책']=5
item['콜라']=4
print('재고관리시스템을 실행합니다')
key=input('물건의 이름을 입력하시오: ')
print(item[key])
s= input('변경하고자 하는 재고를 입력하시오: ')
print('선택된 물품:',s)
v= int(input('재고의 증가/감소량을 적어주세요: '))
if item[s]+v<0:
print('재고의 양은 0미만으로 설정될 수 없습니다.')
print('재고관리시스템을 강제종료합니다.')
sys.exit()
else:
item[s]=item[s]+v
print('재고의 값이',item[s],'로 변경되었습니다.')
|
042b4a70bfc566523636678d7a511ae70c10c70a | WhaleGirl/practice | /Shizhan.py | 1,025 | 3.8125 | 4 | #moc_tn = "百年孤独是什么样的一种孤独"
#print(moc_tn)
#a = input()
#b = input()
#if a>b:max=a
#print(max)
#num=5
#if num == 5:
# print("ok")
#a = 10
#b=20
#r=a if a>b else b
#print(r)
#str="百年孤独"
#for s in str:
# print(s)
# 九九乘法表
#for i in range(1, 9):
# for j in range(1, 9):
# print(str(i) + "*"+ str(j)+"="+str(i*j) +"\t", end=' ')
# print('')
#逢七拍腿
# num=1
# # total=0
# # for num in range(100):
# # if num%7==0:
# # continue
# # else:
# # string=str(num)
# # if string.endswith('7'):
# # continue
# # total+=1
# # print(total)
#模拟10086
# num = input()
# while num!=0:
# if num == '1':
# print("你还剩余99元话费")
# elif num==2:
# print("你还剩余5G流量")
# elif num==3:
# print("操作无效")
# else:
# print("exit")
# break
# num=input()
#索引的下标
verse=["heheda","hsdkf","jeflelw"]
print(verse[-1])
print(verse[0:1])
|
85fb9b8bdc062def2974608ca45d25fee411e3f0 | CalvinNeo/LeetCode | /python/leetcode.230.py | 1,301 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from utils import *
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
ans = None
def index(cur):
cntl = 0
cntr = 0
if cur.left:
cntl = index(cur.left)
if cur.right:
cntr = index(cur.right)
return cntl + 1 + cntr
def dfs(cur, kk):
# print "find {}-th at {}".format(kk, cur.val)
cntl = 0
if cur.left:
cntl = index(cur.left)
if kk <= cntl:
return dfs(cur.left, kk)
if kk == cntl + 1:
return cur.val
return dfs(cur.right, kk - cntl - 1)
return dfs(root, k)
sln = Solution()
print sln.kthSmallest(make_tree([1, null, 2]), 2)
print sln.kthSmallest(make_tree([2,1]), 1)
print sln.kthSmallest(make_tree([3,1,4,null,2]), 4)
print sln.kthSmallest(make_tree([3,1,4,null,2]), 2)
print sln.kthSmallest(make_tree([3,1,4,null,2]), 3)
print sln.kthSmallest(make_tree([3,1,4,null,2]), 1) |
6beb653a6248cd84eb0e91e33710c29c989202fb | daniel-reich/turbo-robot | /tftN3EdkSPfXxzWpi_5.py | 1,033 | 3.796875 | 4 | """
Create a function that returns the sentence that contains the word at index
`n`. Remember to include the full stop at the end.
### Worked Example
txt = "I have a dog. I have a log. There is no stopping me now."
sentence_searcher(txt, 7) ➞ "I have a log."
# The word at index 7 is "log".
# The full sentence that contains the word at index 7 is "I have a log."
# Return the sentence.
### Examples
sentence_searcher(txt, 2) ➞ "I have a dog."
sentence_searcher(txt, 4) ➞ "I have a log."
sentence_searcher(txt, -1) ➞ "There is no stopping me now."
# The index at -1 is the last word.
# The last word is "now".
### Notes
* All sentences will end with a full stop.
* You need to also account for negative indexes.
"""
def sentence_searcher(txt, n):
s=txt[:-1]
t=s.split('. ')
A=[0]+[len(x.split()) for x in t]
B=[sum(A[:i]) for i in range(1,len(A)+1)]
n=(n+sum(A))%sum(A)
for i in range(len(B)-1):
if B[i]<=n<B[i+1]:
return t[i]+'.'
|
546d6c35b8d0a8f63d1507ff9521ab64fd3d9495 | irving2/leetcode | /leetcode/1009. Complement of Base 10 Integer.py | 770 | 3.609375 | 4 | #!/usr/bin/env python
# coding=utf-8
# Project: leetcode
# Author : [email protected]
# Date : 2019/5/11
class Solution(object):
def bitwiseComplement(self, N):
"""
:type N: int
:rtype: int
"""
def binary( x):
if x < 2:
return str(x)
return binary(x//2) + str(x % 2)
def int_10(s):
ret = 0
for i in range(len(s)):
ret += pow(2, i) * int(s.pop())
return ret
bin_N = binary(N)
s = ['1' if e=='0' else '0' for e in bin_N]
return int_10(s)
if __name__ == '__main__':
def binary(x):
if x < 2:
return str(x)
return binary(x // 2) + str(x % 2)
print(binary(4))
|
b020ed42daecf995c3ebbcb4e6048c4650c4d71e | nikhil1699/cracking-the-coding-interview | /python_solutions/chapter_02_linked_lists/SinglyLinkedNode.py | 445 | 3.578125 | 4 | class SinglyLinkedNode:
def __init__(self, value, next_node):
self.value = value
self.next_node = next_node
def stringify_linked_list(head):
display_str = ''
while head is not None:
display_str += str(head.value) + ","
head = head.next_node
return display_str
def list_length(node):
length = 0
while node is not None:
length += 1
node = node.next_node
return length |
8ba3e7a0119e55080aef1ee02ed67fe7945f0cc4 | SandraAlcaraz/FundamentosProgramacion | /parcial3problema3.py | 496 | 3.9375 | 4 | def Factorial (x):
v=x
m=1
if x==0:
return 1
while v>1:
m=v*m
v=v-1
return m
tr=True
while tr==True:
x=int(input("Dame el valor de x"))
v=0
f=0
r=0
while f<101:
v=v+1
y=Factorial(f)
w=(x**f)/y
r=w+r
f=f+1
print (r)
y=str(input("Deseas calcular otro exponente x S/N"))
if y=="s" or y=="S":
tr=True
else:
tr=False
|
02df84da527f122ac6a32c835b5c8dc8082cdaae | utkarshbhardwaj22/TRAINING1 | /venv/Practice46.py | 490 | 3.703125 | 4 | """
Misc concepts in python
"""
class Point:
def __init__(self,x,y):
self._x = x # _x means protected in python -> x must not be accessed directly [warning]
self.__y = y # __y means private in pyhton -> cannot be accessed [error]
def show(self):
print("Points is {} | {}".format(self._x,self.__y))
def main():
ob1 = Point(10,20)
ob1.show()
print("X is: ",ob1._x)
print("Y is: ",ob1._Point__y)
if __name__ == '__main__':
main() |
4b373a77fcc381d3f00f6eba2bac5e4b5bfb7930 | jim0409/PythonLearning-DataStructureLearning | /StatisticProblem/StatisticalInference/probabilityDistGen/poisson.py | 517 | 3.671875 | 4 | import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
rate = 2
n = np.arange(0, 10)
y = stats.poisson.pmf(n, rate)
print(y)
plt.plot(n, y)
plt.show()
# # 使用rvs作圖
# data = stats.poisson.rvs(mu=2, loc=0, size=1000)
# print("Mean: %g" % np.mean(data))
# print("SD: %g" % np.std(data, ddof=1))
#
# # 製作空圖
# plt.figure()
#
# plt.hist(data, bins=9, normed=True)
# plt.xlim(0,10)
# plt.xlabel("Number of accidents")
# plt.title("Simulating Poisson Random Variables")
# plt.show()
|
f5baca5b809b5da2dca2f542fb3f2103783ee46c | danxie1999/python_test | /absolute_v3.py | 280 | 4.40625 | 4 | #!/usr/bin/env python 3
num=input('Please input a number:\n')
try:
num=float(num)
except ValueError:
print('Your input is not a number.')
exit()
if num > 0:
print('The absolute value of',num,'is:',num)
else:
print('The absolute value of',num,'is:',-num) |
1270e19c41319f54e4c2c85723f5fda2a4fc7204 | Mustafasavran/Machine-learning | /LinearRegressionWithGradientDescentandvectorization.py | 1,191 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 22:17:59 2018
@author: mustafa
"""
##Linear regression with one variable and vectorization
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot(theta,filename):#theta is matris
x,y=get_attribütes_from_file(filename)
a=np.arange(150)
plt.scatter(x,y)
plt.scatter(a,theta.item(0)*a+theta.item(1))
plt.show()
def get_attribütes_from_file(filename):#get attribütes using pandas
file=pd.read_csv(filename)
x=file[file.columns.values[0]]
y=file[file.columns.values[1]]
return x,y
def gradientDescentWithvectorization(x,y):#calculate thetas using numpy
x=np.vstack([x,np.ones(99)])
theta=np.matrix('1,1')
for i in range(1000):
theta=theta-1/(len(y))*0.0001*(theta*x-np.matrix(y))*x.T#learning rate is 0.0001
print("ERROR: ",getErrorWithVectorization(theta,x,len(y),y))
return theta
def getErrorWithVectorization(theta,x,m,y):# get error using numpy
return 1/(2*m)*np.sum(*np.square(theta*x-np.matrix(y)))
x,y=get_attribütes_from_file("linear.csv")
theta=gradientDescentWithvectorization(x,y)
plot(theta,"linear.csv")
|
f869280cafd9caf9ac0ae294030bd2c93ed5a0b0 | ahtif/Bioinformatics-Algorithms | /nwa.py | 4,132 | 3.5 | 4 | import sys
from collections import OrderedDict
from termcolor import colored
symbols = set(["A", "C", "G", "T"])
MATCH_SCORE = 1
MISMATCH_SCORE = -0.5
"""
The scoring matrix provided in the assignment sheet as a function.
"""
def score(x, y):
if x == y:
return MATCH_SCORE
if x == "-" or y == "-":
return MISMATCH_SCORE
return 0
"""
Generate a NW table as an ordered dictionary given two sequences. The alignment score
of the two sequences is just the last item added to the dictionary
"""
def NWTable(s1, s2):
table = OrderedDict()
for i in range(0,len(s1)+1):
table[(i,0)] = i*MISMATCH_SCORE
for j in range(0,len(s2)+1):
table[(0,j)] = j*MISMATCH_SCORE
for i in range(1,len(s1)+1):
for j in range(1,len(s2)+1):
match = table[(i-1, j-1)] + score(s1[i-1], s2[j-1])
delete = table[(i-1, j)] + MISMATCH_SCORE
insert = table[(i, j-1)] + MISMATCH_SCORE
table[(i,j)] = max(match, insert, delete)
return table
"""
Given two sequences and their NW table, calculate an optimal aligment and the path
in the table corresponding to the alignment
"""
def alignment(s1, s2, table):
align1 = ""
align2 = ""
i = len(s1)
j = len(s2)
path = []
while (i > 0 or j > 0):
if i > 0 and j > 0 and table[(i,j)] == table[(i-1,j-1)] + score(s1[i-1], s2[j-1]):
align1 = s1[i-1] + align1
align2 = s2[j-1] + align2
path.append((i,j))
i -= 1
j -= 1
elif i > 0 and table[(i,j)] == table[(i-1, j)] + score(s1[i-1], "-"):
align1 = s1[i-1] + align1
align2 = "-" + align2
path.append((i,j))
i -= 1
else:
align1 = "-" + align1
align2 = s2[j-1] + align2
path.append((i,j))
j -= 1
return align1, align2, path
"""
Pretty print a representation of the NW table and highlight the path that corresponds
to the optimal alignment.
If a file handle is passed in as the fname parameter, it will instead print to the
given file in a csv type format.
"""
def printTable(s1, s2, table, path, fname=None):
x, y = list(table.keys())[-1]
s1 = "E"+s1
s2 = "E"+s2
if fname:
row = [c for c in s1]
print (" ", *row, sep=",", file=fname)
else:
row = [c.ljust(5) for c in s1]
print (" ", *row, sep="|", end="|\n")
j = 0
while j <= y:
row = [s2[j]]
i = 0
while i <= x:
if fname:
i
v = str(table[(i,j)])
else:
v = str(table[(i,j)]).ljust(5)
if (i,j) in path:
if fname:
v = "("+v+")"
else:
v = colored(v, "green")
row.append(v)
else:
row.append(v)
i+=1
if fname:
print (*row, sep=",", file=fname)
else:
print (*row, sep="|", end="|\n")
j+=1
"""
Calculate the alignment score of the two defined sequences, and print their NW, with
the optimal alignment highlighted.
"""
def task1(fname=None):
s1 = "CATGAG"
s2 = "CAGAGG"
#s1 = "CAAAGATCTGAAGAGCCAGTGGACTCCACCCCACTTTCTGGTCTGACCAATT"
#s2 = "ACCACACTCTCTGGGCTGACCAATTACAGCGCTTCTACAGAACTGAACACTCC"
table = NWTable(s1, s2)
print ("Alignment score for {} and {}: {}".format(s1, s2, list(table.items())[-1][1]))
align1, align2, path = alignment(s1, s2, table)
print("Optimal alignment:\n{}\n{}".format(align1, align2))
if fname:
outfile = open(fname, "w")
printTable(s1,s2,table,path, outfile)
print ("\nOptimal Path:\n", path, file=outfile)
outfile.close()
else:
print("NW table: ")
printTable(s1,s2,table,path)
print("Optimal path:\n",path)
#If a filename is passed to the program, pass it in as a parameter to task1()
if __name__ == "__main__":
fname = None
if len(sys.argv) > 1:
fname = sys.argv[1]
task1(fname)
|
318c075c7f5fcfc51a3056bc6358760d2f62e992 | k0syan/Kattis | /82.py | 267 | 3.546875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def deleteDuplicates(self, head: ListNode) -> ListNode:
c = head
p = head
n = head.next
print(c, p, n)
while n is not None:
c = n
n = c.next |
55d58e7eac0137841de2e7660c5c053f5e4e08c0 | dao-keer/python2.7_study | /6-3.py | 443 | 3.640625 | 4 | personInfo = {
'name': 'dao-keer',
'age': 20,
'sex': 'male',
'city': 'wuhan',
'firstName': 'dao',
'lastName': 'keer'
}
for i, v in personInfo.items():
print i + ': ' + str(v)
for i in personInfo.keys():
print i
for v in personInfo.values():
print v
keys = ['name', 'age', 'weight']
for i in personInfo.keys():
if i not in keys:
print 'please tell us your ' + i
else:
print 'now, we get your ' + i
|
34a838271bfebb4949302b8bd759cf6e359251f3 | keithoma/GdP | /Praktikum-Aufgabe-4/prime_sums.py | 1,153 | 3.828125 | 4 | #! /usr/bin/env python3
from math import factorial
class PrimeSums:
@staticmethod
def is_prime(p):
return p >= 2 and factorial(p - 1) % p - p == -1 # TODO: maybe sieve me
@staticmethod
def next_prime(p):
p += 1
while PrimeSums.is_prime(p) is False: # TODO Sieve me
p += 1
return p
@staticmethod
def decompose_all(n, smallestPrime = 2, callDepth = 1):
if n == smallestPrime:
return [[n]]
results = []
p = smallestPrime
while p <= n:
a = PrimeSums.decompose_all(n - p, p, callDepth + 1)
for a_k in a:
a_k.append(p)
a_k.sort()
if results.count(a_k) == 0:
results.append(a_k)
p = PrimeSums.next_prime(p)
if PrimeSums.is_prime(n) and callDepth != 1:
print("add@{}: {}: {}".format(callDepth, n, results))
results.append([n])
results.sort()
return results
def test_n(n):
all_sums = PrimeSums.decompose_all(n)
for sums in all_sums:
print("{}: {}".format(n, sums))
test_n(8)
|
d8efdfea7e4a8ee7d2029c733999b7ec1d79d423 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter6-Lists/P6.3.py | 1,062 | 4.1875 | 4 | # Write a program that adds all numbers from 2 to 10,000 to a list.
# Then remove the multiples of 2 (but not 2), multiples of 3 (but not 3),
# and so on, up to the multiples of 100. Print the remaining values.
# FUNCTIONS
def fillList(list):
for i in range(2, 10001):
list.append(i)
return list
def removeMultiples(list):
# for i in range(len(list) - 1, -1, -1):
# number = list[i]
# pop = False
# for j in range(100, 1, -1):
# if number != j:
# pop = True
# break
#
# if pop == True:
# list.remove(number)
for i in range(10000, 1, -1):
remove = False
for j in range(100, 1, -1):
if i != j and i % j == 0:
remove = True
if remove == True:
list.remove(i)
return list
# main
def main():
exampleList = []
exampleList = fillList(exampleList)
print("Before")
print(exampleList)
print("After")
print(removeMultiples(exampleList))
# PROGRAM RUN
main() |
3c18947f075257b17d0c660a1ca41d28c9eccf87 | antoinealb/master-thesis | /scripts/bib_sorter.py | 4,085 | 3.5625 | 4 | #!/usr/bin/env python3
"""
Sorts a tex bibliography according to the order they are cited.
"""
import argparse
import re
import logging
def parse_cite(line):
"""
Parses a line, returning a list of citation keys.
>>> parse_cite("Paxos\cite{kernelpaxos} is an \cite{attempt} to.")
['kernelpaxos', 'attempt']
>>> parse_cite("Paxos\cite{kernel, paxos} is an \cite{attempt} to.")
['kernel', 'paxos', 'attempt']
>>> parse_cite("Paxos\cite[p 10.]{kernelpaxos} is an \cite{attempt} to.")
['kernelpaxos', 'attempt']
>>> parse_cite("Foobar is hello")
[]
"""
pattern = r'\\cite(\[.*?\])?\{(.+?)\}'
matches = re.findall(pattern, line)
result = []
for cite_all in [m[1] for m in matches]:
result += [s.strip() for s in cite_all.split(",")]
return result
def parse_include(line):
"""
Returns the name of the file to include, if there is something to include.
If the line is not an incude line, return None.
>>> parse_include('\include{introduction}')
'introduction.tex'
>>> parse_include('\section{Foobar}')
"""
pattern = r'\\include\{(.+?)\}'
match = re.match(pattern, line)
if match:
return match.groups(1)[0] + ".tex"
def extract_citations(input_file):
"""
Reads all citations from the given file, yielding keys.
Recursively go into includes.
"""
logging.debug('Parsing %s', input_file.name)
total_keys = 0
for l in input_file:
total_keys += len(list(parse_cite(l)))
# Recursively go down in the include
if parse_include(l):
with open(parse_include(l)) as f:
yield from extract_citations(f)
# Yields all citation keys
yield from iter(parse_cite(l))
logging.debug('Found %d keys in %s', total_keys, input_file.name)
def keep_only_first_occurence(seq):
"""
Keeps only the first occurence of any item in the first given sequence.
>>> keep_only_first_occurence([1,2,3,1,4])
[1, 2, 3, 4]
"""
result = []
seen_so_far = set()
for x in seq:
if x not in seen_so_far:
result.append(x)
seen_so_far.add(x)
return result
def parse_bib_entry(line):
"""
Parses a bibentry and returns the key if its a starting line.
Returns none if it is not the start of a bibtex entry.
>>> parse_bib_entry('@inproceedings{chubby')
'chubby'
>>> parse_bib_entry('title={The Chubby lock },')
"""
pattern = r"@[a-z]*{([^,]*)"
match = re.match(pattern, line)
if match:
return match.group(1)
def parse_bibliography(bibfile):
"""
Parses a bibfile and returns a dict with the citation key as key and the
entry lines as values
"""
result = {}
for l in bibfile:
if parse_bib_entry(l):
key = parse_bib_entry(l)
result[key] = []
result[key].append(l)
return result
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", "-i", type=argparse.FileType(), required=True)
parser.add_argument("--tex", "-t", type=argparse.FileType(), required=True)
parser.add_argument("--output", "-o", type=argparse.FileType('w'), required=True)
parser.add_argument("--verbose", "-v", action='store_true')
return parser.parse_args()
def main():
args = parse_args()
if args.verbose:
level = logging.DEBUG
else:
level = logging.INFO
logging.basicConfig(level=level)
citation_keys = list(extract_citations(args.tex))
citation_keys = keep_only_first_occurence(citation_keys)
print(citation_keys)
bibliography = parse_bibliography(args.input)
# We keep uncited keys sorted so that this program is a stable sort
uncited_keys = sorted(set(bibliography.keys()) - set(citation_keys))
logging.info("%d unused keys: %s", len(uncited_keys), ", ".join(uncited_keys))
for k in citation_keys + uncited_keys:
args.output.write("".join(bibliography[k]))
if __name__ == '__main__':
main()
|
622dd5adb3de1ce349951f67a2c0c62295dbd73e | kuldeepsinghshekhawat/CodeVita_preparation | /Europian_Iteration.py | 1,268 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 28 15:23:13 2020
@author: Kuldeep Singh Shekhawat
Topic: Europian Iteration
Based on the Roman Numbers
"""
def roman(number):
digits=[1,4,5,9,10,40,50,90,100,400,500,900,1000]
symbols=['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M']
ans=''
curr_base=len(digits)-1
while number>0 and curr_base>=0:
quotient=number//digits[curr_base]
number=number%digits[curr_base]
ans=ans+(quotient*symbols[curr_base])
curr_base=curr_base-1
return ans
def get_value(k):
value=ord(k)-ord('0')
if value > 9:
value=10+ord(k)-ord('A')
return value
def get_in_base_decimal_value(N,base):
value=0
N=str(N)
for index in range(len(N)):
power=len(N)-index-1
value=value+(get_value(N[index])*(base**(power)))
return value
inp=int(input("Test data"))
N=inp
while 1<=N and N<=3999:
roman_N=roman(N)
#print(N)
#print(roman_N)
max_digit='0'
for digit in roman_N:
if get_value(digit)>get_value(max_digit):
max_digit=digit
min_base=get_value(max_digit)+1
#print(min_base)
N=get_in_base_decimal_value(roman_N,min_base)
print(N)
"""
OUTPUT
Test data1
45338950"""
|
967a36660556f00f73899e63a4d993b70aa53225 | attard-andrew/automate-the-boring-stuff | /chapter_projects/11_feeling_lucky/lucky.py | 1,290 | 3.5625 | 4 | #! python3
# lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4
print('Googling...') # display text while downloading the Google page
# Defines a variable which will store the response from the Google search results
# page where the search term is sliced from the the argument provided
res = requests.get('http://google.com/search?q=' + ' '.join(sys.argv[1:]))
# Check that there are no issues with the request
res.raise_for_status()
# Retrieve top search result links (the results appearing on the first SERP)
soup = bs4.BeautifulSoup(res.text)
# Use soup.select to get a list of all elements that match the '.r a' selector
linkElems = soup.select('.r a')
# The number of tabs to open will be either 5 (the default for webbrowser)
# or the length of the linkElems list returned, whichever is smaller -
# thanks to the min() function (scenarios in which fewer than 5 results
# are returned)
numOpen = min(5, len(linkElems))
# For each iteration of the loop, use webbrowser.open() to open a new tab in the
# browser. Note that the href attribute's value in the returned <a> elements do
# not have the initial http://google.com part, so you have to concatenate
for i in range(numOpen):
webbrowser.open('http://google.com' + linkElems[i].get('href')) |
6479a0d515c51c9d48a681a3a26cd454dcd07b64 | rjmarshall17/miscellaneous | /reviews_keywords.py | 2,531 | 4.0625 | 4 | #!/usr/bin/env python3
from collections import defaultdict
"""
Given a list of reviews, a list of keywords and an integer k. Find the most popular
k keywords in order of most to least frequently mentioned. The comparison of strings
is case-insensitive.
Multiple occurrences of a keyword in a review should be considered as a single mention.
If keywords are mentioned an equal number of times in reviews, sort alphabetically.
"""
# Input
k = [
2,
2,
]
keywords = [
['anacell', 'cetracular', 'betacellular'],
['anacell', 'betacellular', 'cetracular', 'deltacellular', 'eurocell']
]
reviews = [
[
'Anacell provides the best services in the city',
'betacellular has awesome services',
'Best services provided by anacell, everyone should use anacell',
],
[
'I love anacell Best services; Best services provided by anacell',
'betacellular has great services',
'deltacellular provides much better services than betacellular',
'cetracular is worse than anacell',
'Betacellular is better than deltacellular.',
],
]
# Time complexity: O(k*r)
def get_keywords(number_of_keywords, keywords, reviews):
keyword_counts = defaultdict(int)
for review in reviews:
for keyword in keywords:
if keyword.lower() in review.lower():
keyword_counts[keyword] += 1
# Sorting the results and reversing it is most likely O(nlogn) at a minimum, but since I do both,
# it may be considered to be O(2*nlogn) which is still O(nlogn), however the overall time complexity
# is still O(k*r)
# print('keyword counts: %s' % keyword_counts)
counts = list(reversed(sorted(sorted([(v, k) for k,v in keyword_counts.items()],key=lambda v: v[1]))))
# print("counts: %s" % counts)
if len(counts) == number_of_keywords:
return [x[1] for x in counts]
return_counts = []
for index in range(len(counts) - 1):
if counts[index][0] > counts[index+1][0]:
return_counts.append(counts[index][1])
elif counts[index][0] == counts[index+1][0]:
return_counts.extend([x[1] for x in sorted([counts[index],counts[index+1]],key=lambda x: x[1])])
if len(return_counts) >= number_of_keywords:
break
return return_counts[:number_of_keywords]
if __name__ == '__main__':
for index in range(len(keywords)):
results = get_keywords(k[index], keywords[index], reviews[index])
print("For %d got results: %s" % (index,results))
|
4e583f24dd2e777e4a78b862b3aa048bc7e2c094 | magedu-python24/homework | /P24005-lmy/08-week/cat.py | 1,019 | 3.953125 | 4 | # 实现cat命令(支持查看内容和-n参数功能即可)
import argparse
parser = argparse.ArgumentParser(prog='cat',
description='concatenate file(s), or standard input, to standard output.',
add_help=False
)
parser.add_argument('file',
nargs='?',
help='files name'
)
parser.add_argument('-n', '--number',
action='store_true',
dest='num',
help='number all output lines'
)
args = parser.parse_args()
def show_cat(file:str, num=False):
if file:
with open(file, encoding='utf-8') as f:
for n, line in enumerate(f, 1):
if num:
print(n, line, end='')
else:
print(line, end='')
else:
print(input('<<<<'))
if __name__ == '__main__':
show_cat(args.file, args.num) |
9203bbac6cae6ce989c82e2a05b1d6c5413925be | rochafialvin/Python-Summarecon | /PYTHON/fundamental.py | 4,765 | 4.0625 | 4 | # Untuk menampilkan teks (komentar)
# print('My first code')
# Variable
# Untuk menyimpan sebuah data
# Tidak bisa diawali dengan angka
# string, tipe data yg menyimpan teks = 'Vinales'
# number , float : desimal (0.25, 3.14), integer : bulat (3, 5, 6)
# camelCase
firstName = 'Vinales'
lastName = 'John'
age = 32
# Function type digunakan untuk mengethaui tipe data
# dari sebuah variable
# result = type(age)
# print(result)
# print(type(age))
# function input digunakan untuk menerima inputan user
# name = input("Siapa Nama Anda : ")
# day = input("Hari apakah saat ini : ")
# print('Nama saya adalah ' + name)
# print('Hari ini adalah hari ' + day)
# Aritmatika
# numThree = "7"
# # function int akan mengubah string menjadi integer
# # hasil = numOne + int(numThree)
# # print(hasil)
# numOne = 10
# numTwo = 5
# result = numOne + numTwo # 15
# # numOne = 10 , numOneString = "10"
# numOneString = str(numOne)
# # numTwo = 5 , numTwoString = "5"
# numTwoString = str(numTwo)
# # result = 15 , resultString = "15"
# resultString = str(result)
# # 10 + 5 = 15
# result = numOne + numTwo
# print(numOneString + " + " + numTwoString + " = " + str(result))
# # 10 - 5 = 5
# result = numOne - numTwo
# print(numOneString + " - " + numTwoString + " = " + str(result))
# # 10 * 5 = 50
# result = numOne * numTwo
# print(numOneString + " * " + numTwoString + " = " + str(result))
# # 10 / 5 = 2
# result = numOne / numTwo
# print(numOneString + " / " + numTwoString + " = " + str(result))
# # 10 % 5 = 0
# result = numOne % numTwo
# print(numOneString + " % " + numTwoString + " = " + str(result))
# # 10 ** 5 = 100000
# result = numOne ** numTwo
# print(numOneString + " ** " + numTwoString + " = " + str(result))
ageJohn = 47
ageKobe = 41
ageJohn = ageJohn + 3
# ageJohn += 3
# ageKobe = ageKobe - 1
# ageKobe -= 1
# print(ageJohn)
# print(ageKobe)
# module math
# import math
# Mengabsolute sebuah nilai
# print(abs(-13))
# Mengabsolute sebuah nilai kemudian diubah menjadi float
# print(math.fabs(-4))
# Pangkat
# print(math.pow(8, 2))
# print(math.pow(8, 3))
# Akar dua
# print(math.sqrt(64))
# Membulatkan
# print(round(4.7))
# print(round(4.4))
# Floor (dibulatkan ke bawah)
# print(math.floor(4.7))
# Ceil (dibulatkan ke atas)
# print(math.ceil(4.4))
# STRING
word = 'Summarecon'
print(word[0]) # S
print(word[5]) # r
print(word[2:5]) # mma
print(word[2:]) # mmarecon
# print(len(x)) # Banyak karakter pada string
# index dimulai dari nol
# print(x.index('Dunia')) # Mengetahui letak suatu kata
# Memotong kalimat bedasarkan karakter tertentu, default = spasi " "
# print(x.split())
# print(x.split(" "))
# x = 'halo Dunia ku yang cerah'
# Mengubah menjadi huruf kecil
# print(x.lower())
# Mengubah menjadi huruf besar
# print(x.upper())
# Mengubah huruf besar untuk huruf pertama kalimat
# print(x.capitalize())
# print("hello, i'am ironman")
# print('hello, i\'am ironman')
# print('You are "crazy"')
# print("You are \"crazy\" ")
# \n untuk membuat baris baru, enter, new line
# print("Hello, i'am ironman" + "\n" +"and i'am \"crazy\"")
# print(
# "Hello, i'am ironman" + "\n" +
# "and i'am \"crazy\""
# )
# textInput = input('Masukkan sebuah kata : ')
# charInput = input('Karakter apa yang ingin diketahui jumlahnya : ')
# replacedText = textInput.replace(charInput, '')
# margin = len(textInput) - len(replacedText)
# print('Pada kata ' + textInput + ' terdapat ' + str(margin) + ' huruf ' + charInput)
# Hujan
# if hujan :
# pakai payung
# else :
# tidak pakai payung
# Umur
# if lebih dari 18:
# boleh masuk
# elif 15 - 17 :
# boleh masuk, tp dengan orang tua
# else :
# tidak boleh masuk
# Tipe Data : Boolean (TRUE, FALSE)
# 23 = 34
# == sama dengan
# > lebih besar
# < lebih kecil
# <= lebih kecil sama dengan
# >= lebih besar sama dengan
# print(4 > 5) # False
# print(7 > 5) # True
# print(8 > 8) # False
# print(8 >= 8) # True
# satu = "1"
# one = "1"
# Tipe data harus sama
# "1" == 1 -- > False
# 1 == 1 -- > True
# "1" == "1" -- > True
# print(satu == one)
# AND OR NOT
# and
# Jika kedua nilai bernilai TRUE akan menghasilkan TRUE
# or
# Jika kedua nilai bernilai FALSE akan menghasilkan FALSE
# not
# not TRUE = FALSE
# not FALSE = TRUE
# payday = False
# if payday :
# print('Ayo kita belanja')
# else :
# print('Mari berdiam dirumah')
# age = 16.5
# if age >= 18: # 18 +
# print('Silahkan masuk')
# elif (age >= 15) and (age <= 17): # 15 - 17
# print('Masuk dengan orang tua')
# else: # lainnya (14 tahun ke bawah)
# print('Tidak Boleh masuk')
# Duplicate code : SHIFT + ALT + DOWN ARROW
# Untuk membersihkan terminal : CTRL + L
# Membuat komentar : CTRL + /
# Membuka / Menutup terminal : CTRL + J |
05f372ce9bd2b7ee0e17b4c6ae7ba0d2121a1ee7 | MackleBJ/Learning-Python | /Words_Used_In_File.py | 677 | 4.15625 | 4 | #Open file, .split() lines into words, .append() to another list, then check for any duplicates.
file_name = input("Enter file name: ") #Requests what file to open
file_handle = open(file_name)
line_split = []
bank = []
for line in file_handle: #Splits each word, in the line, into individual indexies of a list
line_split = line_split + line.split()
for x in line_split: #Adds words to another list
if bank.count(x) == 0: #Check that no word is in the list more than once
bank.append(x)
bank.sort() #Permanently, alphabetically sorts the list
print(bank)
|
55e8b6432093549ae8b0c2d21974874f3ce2751c | vishwanathj/python_learning | /python_hackerrank/Collections/word_order.py | 1,282 | 4.21875 | 4 | '''
You are given n words. Some words may repeat. For each word, output its number of occurrences.
The output order should correspond with the input order of appearance of the word.
See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
Constraints:
1 <= n <= 100000
The sum of the lengths of all the words do not exceed 10 pow 6
All the words are composed of lowercase English letters only.
Input Format
The first line contains the integer, n.
The next n lines each contain a word.
Output Format
Output 2 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Sample Input
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
Explanation
There are 3 distinct words. Here, "bcdef" appears twice in the input at the first and last positions.
The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds
to the output.
'''
from collections import OrderedDict
D = OrderedDict()
N = int(raw_input())
for item in xrange(N):
key = raw_input()
D[key] = D.get(key, 0) + 1
print len(D.keys())
print ' '.join(map(str, D.values())) |
0e7f08dcf8b4126d096dc1bb964e39a85fb5cfe7 | devesh-bhushan/python-assignments | /tasks/task5.py | 4,330 | 3.859375 | 4 | """
this a menu driven python program to add ,display
search ,delete ,update a employee management system storing data in a database
"""
import pymysql
def create(): # function to create the table
cur = obj.cursor()
qry = """create table if not exists employees(
emp_id int primary key,
emp_name varchar(20),
email varchar(30),
contact varchar(10),
salary int,
hire_date date,
address varchar(50))
"""
cur.execute(qry)
cur.close()
def insert(n): # function to insert record
cur = obj.cursor()
for j in range(n):
lst = ["emp_id", "emp_name", "email", "contact", "salary", "hire_date", "address"]
val = []
for i in lst:
v = input("enter the "+i)
val.append(v)
qry = "insert into employees values({},'{}','{}','{}',{},'{}','{}')".format(*val)
cur.execute(qry)
obj.commit()
cur.close()
def display(): # function to display record
cur = obj.cursor()
qry = "select* from employees"
cur.execute(qry)
res = cur.fetchall()
print("employee_id\temployee_name\temail\tcontact\tsalary\thiredate\taddress".expandtabs(5))
for row in res:
for j in row:
print(j, end=" ")
print()
cur.close()
def delete(e_id): # function to delete record
cur = obj.cursor()
co = search(e_id)
if co == 1:
qry = "delete from employees where emp_id = %s"
cur.execute(qry, (e_id,))
obj.commit()
print("record successfully deleted")
else:
print("no such employee record found")
cur.close()
def update(): # function to update record
cur = obj.cursor()
emp = input("enter the employee id to be updated")
co = search(emp)
if co == 0:
print("no such record found ")
else:
name = input("enter the new name")
emai = input("enter the new email")
con = input("enter the contact")
sal = input("enter the new salary")
date = input("enter the hire date in yy-mm-dd format")
add = input("enter the address")
qry = f"""update employees
set emp_name = %s,email = %s,contact = %s, salary = %s, hire_date = %s, address = %s
where emp_id = %s"""
cur.execute(qry, (name, emai, con, sal, date, add, emp))
obj.commit()
print("record successfully updated")
cur.close()
def search(e_id): # function to search record
cur = obj.cursor()
qry = "select * from employees where emp_id = %s"
cur.execute(qry, (e_id,))
res = cur.fetchall()
counter = 0
for row in res:
for j in row:
print(j, end=" ")
print()
counter = 1
cur.close()
return counter
ch = 1
while ch == 1:
print("""
welcome to the portal
Press 1: insert record
Press 2: Display record
Press 3 : delete record
Press 4: Update record
Press 5: Search record """)
choice = int(input("please enter your choice"))
obj = pymysql.connect("localhost", "root", "", "ems")
if choice == 1:
num = int(input("enter the number of employees you want to add"))
insert(num)
obj.close()
elif choice == 2:
display()
obj.close()
elif choice == 3:
eid = input("enter eid to be deleted")
delete(eid)
obj.close()
elif choice == 4:
update()
obj.close()
elif choice == 5:
eid = input("enter the employee id to be searched")
flag = search(eid)
if flag == 1:
print("employee record exists")
else:
print("employee record does not exists")
obj.close()
else:
print("Invalid choice")
ch = int(input(""" \n Do You Want To Continue
Press 1: To Main Menu
Press 2: To Exit"""))
|
ca4e578a9c2ce5de05a7c7b712e03f91276fdeb9 | hubbm-bbm101/assignment-4-2018-b21726971 | /assignment4.py | 4,922 | 3.59375 | 4 | import sys
myFile = open(sys.argv[1], "r")
myFile = myFile.readlines()
myDict = {}
counter = 1
mylist = []
mylist2 = []
final_list = []
for poland in myFile:
another_one = []
for prussia in poland:
try:
another_one.append(int(prussia))
except ValueError:
pass
myDict[counter] = another_one
counter += 1
def printer(x):
global row
global column
deleter()
destroyer()
if x != 1:
for turkey in range(1, len(myDict)+1):
str1 = " ".join(str(e) for e in myDict[turkey])
print(str1)
if len(mylist) == 0 or len(mylist) == 1:
print("Your score is 0")
if len(mylist) > 1:
final = fibonacci(mylist[-1]-mylist[-2])*mylist2[-1]
final_list.append(final)
print("Your score is {}".format(sum(final_list)))
if endgame():
print("Game Over")
sys.exit()
answer = input("Please enter a row and column number : ")
answer = answer.split(" ")
row, column = int(answer[0]), (int(answer[1])-1)
if row > len(myDict) or column > len(myDict[1])-1:
print("Please enter a correct size")
printer(1)
elif myDict[row][column] == " ":
print("Please enter a correct size")
printer(1)
else:
mylist2.append(myDict[row][column])
first_checker(row, column)
calculator()
def checker(x, y):
global old_value
old_value = myDict[row][column]
a, b, c, d = 0, 0, 0, 0
if x <= len(myDict) and y <= len(myDict[1])-1:
if y+1 <= len(myDict[1])-1:
if myDict[x][y] == myDict[x][y+1] and myDict[x][y] != " ":
a += 1
if y-1 >= 0:
if myDict[x][y] == myDict[x][y-1] and myDict[x][y] != " ":
b += 1
if x+1 <= len(myDict):
if myDict[x][y] == myDict[x+1][y] and myDict[x][y] != " ":
c += 1
if x-1 >= 1:
if myDict[x][y] == myDict[x-1][y] and myDict[x][y] != " ":
d += 1
myDict[x][y] = " "
if a == 1:
checker(x, y+1)
if b == 1:
checker(x, y-1)
if c == 1:
checker(x+1, y)
if d == 1:
checker(x-1, y)
def calculator():
change = 0
for ulm in range(1, len(myDict)+1):
for bavaria in range(len(myDict[1])):
if myDict[ulm][bavaria] == " ":
change += 1
mylist.append(change)
printer(0)
def first_checker(x, y):
a, b, c, d = 0, 0, 0, 0
if x <= len(myDict) and y <= len(myDict[1])-1:
if y+1 <= len(myDict[1])-1:
if myDict[x][y] == myDict[x][y+1] and myDict[x][y] != " ":
a += 1
if y-1 >= 0:
if myDict[x][y] == myDict[x][y-1] and myDict[x][y] != " ":
b += 1
if x+1 <= len(myDict):
if myDict[x][y] == myDict[x+1][y] and myDict[x][y] != " ":
c += 1
if x-1 >= 1:
if myDict[x][y] == myDict[x-1][y] and myDict[x][y] != " ":
d += 1
if (a or b or c or d) == 0:
pass
else:
checker(x, y)
def deleter():
for patch in range(len(myDict)):
for york in range(len(myDict[1])):
for wessex in range(1, len(myDict)):
if myDict[wessex+1][york] == " ":
myDict[wessex+1][york] = myDict[wessex][york]
myDict[wessex][york] = " "
def destroyer():
for york in range(len(myDict[1])-1):
dest = 0
for wessex in range(1, len(myDict)+1):
if myDict[wessex][york] == " ":
dest += 1
if dest == len(myDict):
for wessex in range(1, len(myDict)+1):
myDict[wessex][york] = myDict[wessex][york+1]
myDict[wessex][york+1] = " "
gs = 0
for monster in range(len(myDict[1])):
if myDict[1][monster] == " ":
gs += 1
if gs == len(myDict[1]):
a = myDict[1]
for j in range(1, len(myDict)):
myDict[j] = myDict.pop(j+1)
myDict[len(myDict)+1] = a
def fibonacci(x):
x = int(x)
if x == 0:
return 0
elif x == 1:
return 1
else:
return fibonacci(x-1) + fibonacci(x-2)
def endgame():
crom = 0
for d in range(1, len(myDict)+1):
for f in range(len(myDict[1])-1):
if myDict[d][f] == myDict[d][f+1] and myDict[d][f] != " ":
crom += 1
for i in range(len(myDict[1])):
for r in range(1, len(myDict)):
if myDict[r][i] == myDict[r+1][i] and myDict[r][i] != " ":
crom += 1
if crom >= 1:
return False
else:
return True
calculator()
|
5d23ce0a48b30dfdbdfaf4956da4116ee6e7afd5 | chicocheco/automate_the_boring_stuff | /docx_reading.py | 344 | 3.59375 | 4 | #! python3
import docx
def get_text(filename):
doc = docx.Document(filename)
full_text = []
for para in doc.paragraphs:
full_text.append(para.text)
# Return one long string of joined separate paragraphs with '\n' so each paragraph starts on a new line.
return '\n'.join(full_text)
print(get_text('demo.docx'))
|
ce10d07b6fce7e49b991fdb9843b03a8d91cffc4 | developer22-university/pythonista | /bfs-search.py | 1,245 | 3.84375 | 4 | #bfs-search
import collections
import queue
from typing import Optional
import igraph
def depth_first_search(graph: igraph.Graph,
start: int,
val: int
) -> Optional[int]:
"""
Implementation of the Breadth First Search algorithm on a
non-directional, potentially cyclical graph.
Note that this implementation is NOT thread-safe. For that a
queue.Queue() needs to be used instead of a collections.deque().
:param graph: The igraph.Graph in which the algorithm searches.
:param start: The id of the vertex from which the search is started.
:param val: The id of the vertex which is searched for.
:return: Optional[int]. Returns val if vertex is found, None otherwise.
"""
if start < 0 or val < 0:
raise ValueError('Start and Search indices must not be negative.')
if start == val:
return val
q = collections.deque([start])
visited = set([start])
while len(q) != 0:
v = q.popleft()
for n in graph.neighbors(v):
if n not in visited:
if n == val:
return val
q.append(n)
visited.add(n)
return None
|
e315eb66eba1c0b3b0300f07fa681eae00b1ce17 | M1-2000-2020/ICTPRG-Python | /Week05-Arrays_and_Lists/Quiz.Q6.py | 361 | 4.125 | 4 | '''
Write a program that asks the user for a large number, and then sums all of the digits in that number: Example:
Enter a large number: 29834892
Sum of the digits: 2 + 9 + 8 + 3 + 4 + 8 + 9 + 2 = 45
'''
num1 = input("Please enter a large number, more than six digits long: ")
digits = [int(x) for x in str(num1)]
print(digits)
print(sum(digits)) |
002d6da83a394822bdf32c2808273bc520e045d4 | arjun289/eopi | /data_structures/linked_list/overlapping_list.py | 2,615 | 3.96875 | 4 | from list import ListNode, MyList
def iterate_and_find_overlap(bigger_list, smaller_list, skip_length):
large_iter, small_iter = bigger_list.head, smaller_list.head
for _ in range(skip_length):
large_iter = large_iter.next
while large_iter and small_iter:
if large_iter is small_iter:
return True
large_iter = large_iter.next
small_iter = small_iter.next
return False
def overlap_non_cycle(list1, list2):
len1 = list1.length()
len2 = list2.length()
if len1 > len2:
length = len1 - len2
return iterate_and_find_overlap(list1, list2, length)
else:
length = len2 - len1
return iterate_and_find_overlap(list2, list1, length)
def overlap_maybe_cycle(list1: MyList, list2: MyList):
root1, root2 = list1.has_cycle(), list2.has_cycle()
# they don't have cycle
if not root1 and not root2:
overlap_non_cycle(list1, list2)
# one of it does not have a cycle
elif (root1 and not root2) or (root2 and not root1):
return None
# both have cycle
temp = root2
while True:
temp = temp.next
if temp is root1 or temp is root2:
break
# If both cycles are disjoint
if temp is not root1:
return None
def distance(a, b):
dis = 0
while a is not b:
a = a.next
dis += 1
return dis
# L1 and L2 in same cycle, locate overlapping node if they
# first overlap before cycle starts.
stem1_length, stem2_length = distance(list1, root1), distance(list2, root2)
if stem1_length > stem2_length:
list2, list1 = list1, list2
for _ in range(abs(stem1_length - stem2_length)):
list2 = list2.next
while list1 is not list2 and list1 is not root1 and list2 is not root2:
list1, list2 = list1.next, list2.next
return list1 if list1 is list2 else root1
if __name__ == "__main__":
node1_1 = ListNode(1)
listing1 = MyList(node1_1)
node2_1 = ListNode(2)
node1_1.next = node2_1
node3_1 = ListNode(3)
node2_1.next = node3_1
print("lenght list 1: " + str(listing1.length()))
node1_2 = ListNode(5)
listing2 = MyList(node1_2)
node2_2 = ListNode(7)
node1_2.next = node2_2
node3_2 = ListNode(8)
node2_2.next = node3_2
node4_2 = ListNode(9)
node3_2.next = node4_2
# create overlap without loop
node3_1.next = node3_2
print("lenght list 2: " + str(listing2.length()))
print("list has overlap " + str(overlap_non_cycle(listing1, listing2)))
|
c785e50b43e0fd0d5b5f5eac0d1d8470dbab48ee | yangchi/LCPractice | /SearchInsertPosition.py | 579 | 3.78125 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
return self.binarySearchInsert(A, 0, len(A), target)
def binarySearchInsert(self, A, begin, end, target):
if begin >= end:
return end
mid = begin + (end - begin) / 2
if A[mid] == target:
return mid
if A[mid] > target:
return self.binarySearchInsert(A, begin, mid, target)
return self.binarySearchInsert(A, mid + 1, end, target) |
0df6cadbb9eaa946f804032bb91092aa8d80691d | arnjr1986/Curso-Python-3 | /aula08.py | 555 | 3.859375 | 4 | #Modulos / Biblioteca/ import
#import math (importa tudo: ceil(arredonda pra cima), floor(arredonda pra baixo
#trunc(trunca o numero para numero inteiro), pow(exponencial), sqrt, factorial
# from math import sqrt, ceil (vai importar somente sqrt e ceil da biblioteca Math) importação otimizada
import math
#from math import sqrt
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
#raiz = sqrt(num)
print('A raiz de {} é igual a {:.2f}'.format(num, raiz))
#print('A raiz de {} é igual a {}'.format(num, math.ceil(raiz))
|
35fe94e081db1e396fff8e7ea7af24739596a83b | JavaPhish/holbertonschool-interview | /0x1F-pascal_triangle/0-pascal_triangle.py | 282 | 3.71875 | 4 | #!/usr/bin/python3
"""
Basic pascal triangle algo
"""
def pascal_triangle(n):
""" Main function """
final = []
row = [1]
temp = [0]
for x in range(n):
final.append(row)
row = [l + r for l, r in zip(row + temp, temp + row)]
return final
|
addc6915f4f7dcb2daada6858c1e4f708749023b | gnorgol/Python_Exercice | /Exercice 43.py | 165 | 3.53125 | 4 | def InsertEtoile(s) :
resultat = ""
for each in s:
resultat = resultat + each + "*"
return resultat
s = "Python"
print(InsertEtoile(s))
|
6a6ec231d1b29335c8b5a05dfd24113544d2d5b4 | nicolasgasco/CodingNomads_Labs | /07_classes_objects_methods/CLIgame_characters.py | 1,196 | 4.03125 | 4 | import random
# create two classes for hero and opponent
class Hero:
"Class for the hero of the game"
def __init__(self, name, level, gender):
self.name = name
self.level = level
self.gender = gender
def attack(self, opponent):
print(f"{self.name} attacks {opponent.name}!\n")
hero_roll = random.randint(1, 12) * self.level
opp_roll = random.randint(1, 12) * opponent.level
print(f"Your roll is {hero_roll}.")
print(f"{opponent.name}'s roll is {opp_roll}.\n")
if hero_roll >= opp_roll:
print(f"{self.name} won over {opponent.name}!\n\n")
return True
else:
print(f"DEFEAT! {opponent.name} has defeated {self.name}!\n\n")
return False
def __repr__(self):
return f"{self.__class__.__name__}({self.name}, {self.level}, {self.gender})"
class Opponent():
"Class for the opponent of the game"
def __init__(self, name, level):
self.name = name
self.level = level
def __repr__(self):
return f"{self.__class__.__name__}({self.name}, {self.level})"
h1 = Hero("Luke Skywalker", 15, "male")
op1 = Opponent("Bounty hunter", 8)
|
ef1f0d090d91d6f78eb1e770ceb946e41a635f7f | devdesai-work/suduku_with_backtracking_visualization | /solve.py | 1,673 | 3.53125 | 4 | matrix = [[8, 1, 0, 0, 3, 0, 0, 2, 7],
[0, 6, 2, 0, 5, 0, 0, 9, 0],
[0, 7, 0, 0, 0, 0, 0, 0, 0],
[0, 9, 0, 6, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 2, 0, 0, 0, 4],
[0, 0, 8, 0, 0, 5, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 1, 0, 7, 5, 0],
[3, 8, 0, 0, 7, 0, 0, 4, 2]]
sector = {0:[0,1,2],1:[3,4,5],2:[6,7,8]}
def validate(val,i,j,grid):
for x in range(0,9):
if grid[x][j] == val and i!=x:
return False
for x in range(0,9):
if grid[i][x] == val and j!=x:
return False
p_i = (i//3)
p_j = (j//3)
for p in sector[p_i]:
for q in sector[p_j]:
if grid[p][q] == val and (i,j) != (p,q):
return False
return True
def construct(grid):
for i in range(0,9):
for j in range(0,9):
if grid[i][j] == 0:
for k in range(1,10):
if validate(k,i,j,grid):
grid[i][j] = k
if construct(grid):
return True
grid[i][j] = 0
return False
return True
def display(matrix):
for i in range(9):
if i%3 == 0 and i!=0:
print("- - - - - - - - - -")
for j in range(9):
if j%3 == 0 and j!=0:
print("|",end='')
if j == 8:
print(matrix[i][j])
else:
print(str(matrix[i][j]) + " ",end="")
if __name__ == "__main__":
construct(matrix)
display(matrix)
|
4fdae6d3749fbf4d6905905160426534ee3b489f | ani07/Starting_Out_with_Pythoni | /Rectangle_area_3_2.py | 374 | 4.03125 | 4 | L1 = float(input('Enter length of 1st rectangle'))
B1 = float(input('Enter the breadth of 1st rectangle'))
L2 = float(input('Enter length of 2nd rectangle'))
B2 = float(input('Enter breadth of 2nd rectangle'))
A1 = L1*B1
A2 = L2*B2
if A1 > A2:
print('First rectangle is bigger')
elif A2 > A1:
print('Second rectangle is greater')
else:
print('Both are equal') |
cd65c9a055b50bb2ad3964f447453bafce167d89 | dm36/interview-practice | /leetcode/majority_element.py | 3,957 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html
# - Know if a value is present in a list for more than half of the elements
# in that list
# Fault-tolerant computing- multiple redundant computations nad verify that
# a majority of results agree
# Sort the list- if there is a majority value it mut now be the middle
# run another pass through the list and count it's frequency
# O(1) extra space and O(n) time- 2 pases
# over the input list
# first pass- generate a single candidate value- majority value
# if there is a majority
# second pass counts the frequency of that value to confirm
# first pass- need candidate value- set to value, count set to 0
# each element examine count- if count is equal to 0- set candidate to value
# at the current element
# compare the element's value to current candidate value- same increment count
# by 1- different- decrement count by 1
# candidate = 0
# count = 0
# for value in input:
# if count == 0:
# candidate = value
# if candidate == value:
# count += 1
# else:
# count -= 1
# candidate will be majority if a majority value exists, O(n) pass
# to verify that the candidate is a majority element
# First, consider a list where the first element is not the majority value, for example this list with majority value 0:
#
# [5, 5, 0, 0, 0, 5, 0, 0, 5]
# processing the first element- aign 5 to candidate and 1
# to count
# 5 is not hte majority- at some point algorithm will find another
# value to pair with every 5 we've seen so far- count will drop to 0
# before the last element in the list- occurs at the 4th element
# [5, 5, 0, 0...]
# [1, 2, 1, 0...]
# count returns to 0- consumed same # of 5's as other elements
# if all elements were the majority element- consumed 2 majority and 2 non-majority
# largest # of majority elements consumed- majority
# must be a majority of the remainder of the input lit
# some of the other element were not majority elements this would be more true
# first element was a majority element and count drops to 0
# the majority element is still the majority of the remainder input list
# consumed equal # of majority and non majority elements
# demonstrates range of elements from time candidate is first assigned to when
# count drops to 0 can be discarded from the input without affecting the final
# result of the first pass
# repeat this over and over again discarding ranges that prefix our input until
# we find a range that is a suffix of our input where count never drops to 0
# input list suffix- count never drops to 0- must have more values than equal
# the first element than values that do no
# first element must be the majority of that list- only possible candidate
# for the majority of the full input list
# two
from collections import Counter
def majorityElement(arr):
my_counter = Counter(arr)
return [num for num, val in my_counter.items() if val > len(arr) / 3]
print majorityElement([1,1,1,3,3,2,2,2])
print majorityElement([3, 2, 3])
def majorityElement(self, nums, k):
ctr = collections.Counter()
for n in nums:
ctr[n] += 1
if len(ctr) == k:
ctr -= collections.Counter(set(ctr))
ctr = collections.Counter(n for n in nums if n in ctr)
return [n for n in ctr if ctr[n] > len(nums)/k]
# @param {integer[]} nums
# @return {integer[]}
# def majorityElement(self, nums):
# if not nums:
# return []
# count1, count2, candidate1, candidate2 = 0, 0, 0, 1
# for n in nums:
# if n == candidate1:
# count1 += 1
# elif n == candidate2:
# count2 += 1
# elif count1 == 0:
# candidate1, count1 = n, 1
# elif count2 == 0:
# candidate2, count2 = n, 1
# else:
# count1, count2 = count1 - 1, count2 - 1
# return [n for n in (candidate1, candidate2)
# if nums.count(n) > len(nums) // 3]
|
a7ef2f04b328fc4538359059520759cabbdbea1d | ender8848/the_fluent_python | /chapter_19/demo_19_15.py | 1,341 | 3.765625 | 4 | '''
假设有个销售散装有机食物的电商应用,客户可以按重量订购坚果、干果或杂粮。
在这个系统中,每个订单中都有一系列商品,而每个商品都可以使用示例 19-15 中的类表示。
示例 19-15 bulkfood_v1:最简单的 LineItem 类
'''
class LineItem:
def __init__(self, description, weight, price):
self.description = description
# 这里已经使用特性的设值方法了,确保所创建实例的 weight 属性不能为负值
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
# @property 装饰读值方法
@property
# 实现特性的方法,其名称都与公开属性的名称一样——weight
def weight(self):
# 真正的值存储在私有属性 __weight 中
return self.__weight
# 被装饰的读值方法有个 .setter 属性,这个属性也是装饰器;这个装饰器把读值方法和设值方法绑定在一起
@weight.setter
def weight(self, value):
# 如果值大于零,设置私有属性 __weight
if value > 0:
self.__weight = value
# 否则,抛出 ValueError 异常
else:
raise ValueError('value must be > 0')
if __name__ == '__main__':
raisins = LineItem('Golden raisins', -10, 6.95)
print(raisins.subtotal())
raisins.weight = -20
print(raisins.subtotal())
|
e0d6bf3d710e67607420d96d3a27865ea0d60f9f | rinAkhm/task_for_analytics | /task5.py | 2,143 | 3.8125 | 4 | from datetime import datetime
from datetime import timedelta
'''The Moscow Times - Wednesday, October 2, 2002
The Guardian - Friday, 11.10.13
Daily News - Thursday, 18 August 1977'''
format1 ='Wednesday, October 2, 2002'
day1 = datetime.strptime(format1, "%A, %B %d, %Y")
print(day1,type(day1))
format2 ='Friday, 11.10.13'
day2 = datetime.strptime(format2, "%A, %y.%m.%d")
print(day2,type(day2))
format3 ='Thursday, 18 August 1977'
day3 = datetime.strptime(format3, "%A, %d %B %Y")
print(day3, type(day3))
def check_dates(stream):
'''Напишите функцию, которая проверяет эти даты на корректность. Т. е. для каждой
даты возвращает True (дата корректна) или False (некорректная дата).'''
for date in stream:
try:
datetime.strptime(date, "%Y-%m-%d")
print(f'this date {date} is True')
except ValueError as e:
print(f'this date {date} is False')
def date_range(date_start:str, date_end:str):
'''
Напишите функцию date_range, которая возвращает список дат за период от start_date до end_date.
Даты должны вводиться в формате YYYY-MM-DD.
В случае неверного формата или при start_date > end_date должен возвращаться пустой список.'''
list_date = []
if date_start is None or date_end is None or date_end<date_start:
# list_date = None
print(list_date)
else:
try:
start = datetime.strptime(date_start, "%Y-%m-%d")
end = datetime.strptime(date_end, "%Y-%m-%d")
while start != end:
start += timedelta(days=1)
print(start.strftime("%Y-%m-%d"))
except ValueError as e:
print(e)
list_date = []
print(list_date)
if __name__ == "__main__":
stream = ["2018-04-02", "2018-02-29", "2018-19-02"]
check_dates(stream)
date_range('2018-03-10','2018-04-10')
|
746867a4b7ae573b5a8998bf77b3d7a145973747 | shenqidecaonima/python_tutorial | /Week1-2/1.11Python面向对象/2.py | 507 | 4.0625 | 4 | #构造函数:__init__()
'''
class A:
def __init__(self):
print("AAAAAAAA")
def fun(self):
print("class A...")
a = A()
'''
class Person:
name=""
age=0
def __init__(this,name,age):
this.name=name
this.age = age
def getInfo(self):
print(self.name,":",self.age)
# 构造方法可以实现,实例化对象的使用就可以初始化属性
p = Person("lisi",20)
#p.name="lisi"
p.age=30
p.getInfo()
|
bfdb50d8dcddf515f8f606ab1e1534bcb6a81c93 | ZachChuba/Tic-Tac-Toe-App | /models.py | 512 | 3.5 | 4 | '''
Model for DB
'''
def define_database_class(database_session):
'''
Returns class Player that is a model for the db
'''
class Player(database_session.Model):
'''
Database Player table format
'''
username = database_session.Column(database_session.String(80), primary_key=True)
score = database_session.Column(database_session.Integer, nullable=False)
def __repr__(self):
return '<Player {}>'.format(self.username)
return Player
|
b5a53e3308ff3a8950cbd1c9b70bf59fb7d9dc54 | YanjiaSun/leetcode-3 | /code/993_solution.py | 838 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
queue = collections.deque([root])
while queue:
parent = dict()
for _ in range(len(queue)):
node = queue.popleft()
for child in [node.left, node.right]:
if not child: continue
queue.append(child)
parent[child.val] = node
if (x in parent) ^ (y in parent): return False
if x in parent and y in parent:
if parent[x] == parent[y]: return False
else: return True
return False |
17a65e2160a8eb3bfa7d74cff44c51686ae69a50 | vicamu/test | /test.py | 84 | 3.609375 | 4 | a =[1,2,3,4]
for num in a:
print(num)
print("Línea nueva 2")
print("Hola hola") |
f358fdd80c85823c322ed71b846e629980d8fddc | annaxarkhipova/coursepy | /homework for 11 March/with_proccess.py | 1,312 | 3.890625 | 4 |
# Также запустите ее три раза с теми же аргументами, но каждую в отдельной потоке с помощью multiprocessing.Process.
# Не забудьте стартануть процессы и дождаться их окончания.
import multiprocessing
import time
v = time.time()
def odd_primes(end, start):
print('Старт вычислений, начиная с {}'.format(end))
primes = []
for a in range(end, start, -1):
if is_prime_number(a):
primes.append(a)
print('Конец вычислений c {}. Затрачено {} сек'.format(end, int(time.time() - v)))
def is_prime_number(x):
if x >= 2:
for y in range(2, x):
if not (x % y):
return False
else:
return False
process = []
pr = multiprocessing.Process(target=odd_primes, args=(10000, 3,))
pr1 = multiprocessing.Process(target=odd_primes, args=(20000, 10001,))
pr2 = multiprocessing.Process(target=odd_primes, args=(30000, 20001,))
pr.start()
pr1.start()
pr2.start()
process.append(pr)
process.append(pr1)
process.append(pr2)
pr.join()
pr1.join()
pr2.join()
print('Общее время вычислений в секундах: {}'.format(int(time.time() - v)))
|
34055a4fe950c03e9b14fbf71245f7018cd9a95f | quyixiao/python_lesson | /function1/function11.py | 803 | 3.578125 | 4 | def foo(xyz=None,u = 'abc',z = 123):
if xyz is None:
xyz = []
xyz.append(1)
print(xyz)
return xyz
foo()
print(1,foo.__defaults__)
foo()
print(2,foo.__defaults__)
foo([10])
print(3,foo.__defaults__)
foo([10,5])
print(4,foo.__defaults__)
lst = [5]
lst = foo(lst)
print(lst)
print(5,foo.__defaults__)
# 默认值的作用域
# 每一种方式
# 使用影子拷贝创建一个新的对象 ,永远不能改变传入的参数
# 第二种方式
# 通过值的判断就可以灵活的选择,
# 这种方法灵活,应用广泛
# 很多的函数的定义,都可以看到,如果传入的是非null,那么惯用的用法,
# 使用nonlocal关键字,将变量标记为在上级的局部的作用域中定义,但是不能是全局的作用域中定义,
# 属性_defaults_
|
53839d9c460d47315f4760fa1fd1fa0a4949d5e4 | evrenkaraarslan/LeetCode-Codewars | /BitCounting.py | 384 | 4.125 | 4 | ## Bit Counting ##
def countBits(n):
a="{0:b}".format(n).count("1")
return a
'''
Write a function that takes an integer as input, and returns the number of bits that are equal to one
in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in
this case
''' |
df2391c5d28acf81ce931ca77a3924df79ff0a3b | lorak127/University-Courses | /FP/Utils/Simulare_217_1/Domain/Medicine.py | 1,164 | 3.515625 | 4 | '''
Created on 11 dec. 2017
@author: USER
'''
import unittest
class Medicine():
def __init__(self,name,price):
"""
Initializeaza un obiect de tip Medicine
:param: name - string
:param: price - float
"""
self.__name=name
self.__price=price
def getName(self):
"""
Getter pentru numele medicamentului
:return: self.__name
"""
return self.__name
def getPrice(self):
"""
Getter pentru pretul medicamentului
:return: self.__price
"""
return self.__price
class TestCase(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.med=Medicine("Nurofen",17.50)
def tearDown(self):
unittest.TestCase.tearDown(self)
def testMedicineGetName(self):
self.assertEqual(self.med.getName(), "Nurofen", "Numele e incorect")
def testMedicineGetPrice(self):
self.assertEqual(self.med.getPrice(), 17.50, "Pretul e incorect")
if __name__ == '__main__':
unittest.main() |
30d6fab4a2b8d322350ffe09f6f830d1cc671f5d | theydonthaveit/python-training | /api_frameworks/hug_test.py | 811 | 3.53125 | 4 | """A basic (single function) API written using hug"""
import hug
@hug.get('/hug_test')
def happy_birthday(name, age:hug.types.number=1):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
@hug.get('/greet/{event}')
def greet(event: str):
"""Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) """
greetings = "Happy"
if event == "Christmas":
greetings = "Merry"
if event == "Kwanzaa":
greetings = "Joyous"
if event == "wishes":
greetings = "Warm"
return "{greetings} {event}!".format(**locals())
@hug.get('/echo', versions=1)
def echo(text):
return text
@hug.get('/echo', versions=range(2, 5))
def echo_new(text):
return "Echo: {text}".format(**locals())
|
65883fcadfd179420f6103b09df6de0962ce6f41 | Saber307/My-University-Life-Learning | /52 programming problems/problem 3.py | 107 | 3.5625 | 4 | for x in range (1000,0,-5):
for y in range(x,x-5,-1):
print(f"{y}\t",end='')
print("\n")
|
595df1012223cd8f440c3e4130dac31c4bf26b74 | IsseBisse/adventcode20 | /6/CustomCustoms.py | 625 | 3.53125 | 4 | def get_data(path):
with open(path) as file:
data = file.read().split("\n\n")
for i, entry in enumerate(data):
data[i] = entry.split("\n")
return data
def part_one():
data = get_data("input.txt")
total_sum = 0
for i, entry in enumerate(data):
temp = "".join(entry)
temp = set(temp)
total_sum += len(temp)
print(total_sum)
def part_two():
data = get_data("input.txt")
total_sum = 0
for i, group in enumerate(data):
intersect = set(group[0])
for entry in group:
intersect &= set(entry)
total_sum += len(intersect)
print(total_sum)
if __name__ == '__main__':
#part_one()
part_two() |
2648c617d019ec7e274c0f387430b1e1c4ed989a | chenshaoping2015/pygame | /python_pratice/game/game_round1.py | 894 | 3.671875 | 4 | # -*- coding:utf-8 -*-
# @Time :2020/11/18 17:04
# @Author: stevenchen
'''
一个回合制游戏,每个角色都有hp 和 power ,hp代表血量,power代表攻击力
hp的初始值为1000,power的初始值为200,
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
'''
#定义fight函数实现游戏逻辑
def fight():
#定义四个变量存放初始数据
my_hp = 1000
my_power = 200
enemy_hp = 1000
enemy_power = 200
#定义血量的最终计算方式
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
#判断输赢
# if my_final_hp > enemy_final_hp:
# print("WIN")
# else:
# print("GAME OVER")
#三目运算
print("WIN") if my_final_hp > enemy_final_hp else print("GAME OVER")
fight()
|
53a4ec70b346d1dc35d0299ec8ac2eef9ad385f5 | saadhasanuit/Assignment-2 | /pp 3.8.py | 305 | 4.15625 | 4 | print("MUHAMMAD SAAD HASAN 18B-117-CS SECTION:-A")
print("ASSIGNMENT # 3")
print("PRACTICE PROBLEM 3.8")
## A function perimeter() that takes, as input, the radius of a circle (a nonnegative number) and returns the perimeter of the circle
import math
def perimeter(r):
r = (2 * math.pi * r)
return r
|
b1479277d1367eddc76178534804291e254bd6b2 | RidgeHood/Mashupstacks-Projects | /python/python-lab-5/Project-3.py | 418 | 3.671875 | 4 | import csv
with open('projectcsv.csv','r') as car:
car_read=csv.reader(car)
csvlist=[]
header=[]
for x in car_read:
csvlist.append(x)
print('\nThird row is--\n',csvlist[2])
print('\n2nd column is---\n')
for i in range(len(csvlist)):
print(csvlist[i][1])
print('\nFirst 3 lines are----\n')
y=0
while y<3:
print(csvlist[y])
y=y+1 |
65a2b09ea57281e4a75f4de83efeaf7b5e027e44 | Alegruz/Game-AI-Track | /3_2/CSE304_ALGORITHM_ANALYSIS/Homeworks/hw1.py | 1,362 | 3.859375 | 4 | import time
def algorithm_recursive(n: int) -> int:
if n == 1 or n == 2:
return 1
else:
sum: int = 0
for i in range(1, n):
sum += algorithm_recursive(i)
return sum
def algorithm(n: int) -> int:
count: int = 0
data: list[int] = [0] * (n + 1)
data[1] = 1
data[2] = 1
for i in range(3, n + 1):
for j in range(1, i):
data[i] += data[j]
count += 1
# print(f"{i}: {data[i]}")
return data[n], count
def algorithm_best(n: int) -> int:
if n == 1:
return 1
return 1 << n - 2
if __name__ == "__main__":
input_list: list[int] = [1600, 3200, 6400, 12800, 25600]
# for i in range(24, 29):
# tic: float = time.time()
# result: int = algorithm_recursive(n=i)
# toc: float = time.time()
# print(f"RECURSIVE{i}-result: {result}, elapsed time: {toc - tic}")
#
# for item in input_list:
# tic: float = time.time()
# result: int = algorithm_best(n=item)
# toc: float = time.time()
# print(f"BEST[{item}]-elapsed time: {toc - tic}, result: {result}")
for item in input_list:
tic: float = time.time()
result, count = algorithm(n=item)
toc: float = time.time()
print(f"ARRAY[{item}]-count: {count}, elapsed time: {toc - tic}")
|
c936b1d86ddc4acfaeaacf0e276b19dd2a92408b | ethanrweber/ProjectEulerPython | /Problems/101-200/131-140/Problem135.py | 948 | 3.53125 | 4 | def method():
print("for values of a number n from 1 to 1 million, determine the number of solutions for n in which n can be "
"expressed as z^2-y^2-x^2 in exactly 10 unique ways, where x,y,z are terms in a series of "
"arithmetic progression")
print()
print(arithmetic_progression_sums(1000000, 10))
return
def arithmetic_progression_sums(n: int, w: int) -> int:
"""
General method for solving problem 135 with variable n and w
:param n: limit for a number n
:param w: number of unique ways n can be expressed as z^2 - y^2 - x^2 for x, y, z > 0
:return: the number of solutions for n in which n can be expressed in w ways as z^2 - y^2 - x^2 for x, y, z > 0
"""
slns = [0] * (n + 1)
for u in range(1, n + 1):
for v in range(n // u + 1):
if (u + v) % 4 == 0 and (3 * v) > u and (3 * v - u) % 4 == 0:
slns[u * v] += 1
return slns.count(w)
|
61be562379cfdbc84bb85d5eb3f4f294887714c3 | orlovska/python | /The_start/Divide.py | 878 | 4.0625 | 4 | # Given two positive integers, compute their quotient,
# using only the addition, subtraction, and shifting operators.
# Hint:Relate x/y to (x - y)/y.
def divide (x , y) :
# divide(9, 3) (1001, 11)
result, power = 0, 32
y_power = y << power
# y_power = 110000000000000000000000000000000...
while x >= y: # 1001 > 11, 11 = 11
while y_power > x: # 1 (1100000000...> 1001)
# 110 < 1001 with power = 1;
# 2 (110 > 11)
# 11 !< 11 with power = 0
y_power >>= 1
# y_power1 = 11...(31)
# y_power2 = 11
power -= 1
# power1 = 31
# power2 = 0
result += 1 << power
# result = 10, 11
x -= y_power
# x = 1001
# -0110
# 0011
return result
|
480c9bb1d75f5180c77139407444f3d70b37d41f | kbmulligan/cs545-a1 | /perceptron.py | 10,039 | 4.28125 | 4 | import numpy as np
from matplotlib import pyplot as plt
class Perceptron :
"""An implementation of the perceptron algorithm.
Note that this implementation does not include a bias term"""
def __init__(self, max_iterations=100, learning_rate=0.2) :
self.max_iterations = max_iterations
self.learning_rate = learning_rate
def fit(self, X, y) :
"""
Train a classifier using the perceptron training algorithm.
After training the attribute 'w' will contain the perceptron weight vector.
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
y : ndarray, shape (n_examples,)
Array of labels.
"""
self.w = np.zeros(len(X[0]))
converged = False
iterations = 0
while (not converged and iterations < self.max_iterations) :
converged = True
for i in range(len(X)) :
if y[i] * self.discriminant(X[i]) <= 0 :
#print 'y[i]', y[i]
#print 'learning_rate', self.learning_rate
#print 'w', self.w, len(self.w), np.shape(self.w)
#print 'X[i]', X[i], len(X[i]), np.shape(X[1])
self.w = self.w + y[i] * self.learning_rate * X[i]
converged = False
#plot_data(X, y, self.w)
iterations += 1
self.converged = converged
if converged :
print 'converged in %d iterations ' % iterations
def discriminant(self, x) :
return np.dot(self.w, x)
def predict(self, X) :
"""
make predictions using a trained linear classifier
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
"""
scores = np.dot(self.w, X)
return np.sign(scores)
def error(self, predictions, labels):
error_rate = 1
errors = 0
if (len(predictions) != len(labels)):
print 'Different number of labels and predictions...'
else:
for x in range(len(predictions)):
if predictions[x] != labels[x]:
errors += 1
error_rate = float(errors) / len(predictions)
return error_rate
def norm(self, x):
# return np.sqrt(np.sum(np.square(x)))
return np.sqrt(np.dot(x,x))
class PerceptronBias(Perceptron) :
"""An implementation of the perceptron algorithm with bias."""
def fit(self, Xinput, y) :
"""
Train a classifier using the perceptron training algorithm with bias.
After training the attribute 'w' will contain the perceptron weight vector of length equal to len(X) + 1.
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
y : ndarray, shape (n_examples,)
Array of labels.
"""
X = []
# Hide bias here in extra term, set to 1
for i in range(len(Xinput)):
X.append(np.insert(Xinput[i],0,1))
#print X[i]
self.w = np.zeros(len(X[0]))
converged = False
iterations = 0
while (not converged and iterations < self.max_iterations) :
converged = True
for i in range(len(X)) :
if y[i] * self.discriminant(X[i]) <= 0 :
self.w = self.w + y[i] * self.learning_rate * X[i]
converged = False
#plot_data(X, y, self.w)
iterations += 1
self.converged = converged
if converged :
print 'converged in %d iterations ' % iterations
def predict(self, X) :
"""
make predictions using a trained linear classifier
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
"""
bias = self.w[0]
w = self.w[1:]
scores = np.dot(w, X) + bias # IS THIS THE CORRECT THING TO DO WITH BIAS???
return np.sign(scores)
class PerceptronPocket(PerceptronBias) :
"""An implementation of the perceptron algorithm w/ bias which tracks
the weight vector which is 'best-so-far'. """
def fit(self, Xinput, y) :
"""
Train a classifier using the perceptron training algorithm with bias.
After training the attribute 'w' will contain the perceptron weight vector of length equal to len(X) + 1.
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
y : ndarray, shape (n_examples,)
Array of labels.
"""
Xlist = []
# Hide bias here in extra term, set to 1
for i in range(len(Xinput)):
Xlist.append(np.insert(Xinput[i],0,1))
# convert to np array
X = np.array(Xlist)
self.w = np.zeros(len(X[0]))
self.pocket = self.w # initialize the pcoket weight vector
self.pocket_error = 1
converged = False
iterations = 0
while (not converged and iterations < self.max_iterations) :
converged = True
for i in range(len(X)) :
if y[i] * self.discriminant(X[i]) <= 0 : # if misclassified or on the line
self.w = self.w + y[i] * self.learning_rate * X[i]
converged = False
predictions = [self.predict(i[1:], False) for i in X] # strip bias terms from features, then predict using self.w
error_now = self.error(predictions, y)
if error_now < self.pocket_error:
self.pocket = np.array(self.w)
self.pocket_error = error_now
iterations += 1
self.converged = converged
if converged :
print 'converged in %d iterations ' % iterations
def predict(self, X, use_pocket=True) :
"""
make predictions using a trained linear classifier
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
use_pocket : Boolean, set to True if using self.pocket, otherwise uses self.w
"""
if (use_pocket == True):
bias = self.pocket[0]
w = self.pocket[1:]
else:
bias = self.w[0]
w = self.w[1:]
score = np.dot(w, X) + bias # IS THIS THE CORRECT THING TO DO WITH BIAS???
return np.sign(score)
class PerceptronModified(Perceptron) :
"""An implementation of the perceptron algorithm. This modified version
updats the weight vector based on the data point that maximizes the given function lambda.
Note that this implementation does not include a bias term."""
def fit(self, X, y) :
"""
Train a classifier using the perceptron training algorithm.
After training the attribute 'w' will contain the perceptron weight vector.
Parameters
----------
X : ndarray, shape (num_examples, n_features)
Training data.
y : ndarray, shape (n_examples,)
Array of labels.
"""
maximum_initial_w_value = 1
c = 0.1 # init c and makes sure (0 < c < 1), not 0
while (c == 0):
c = np.random.uniform()
self.w = np.random.uniform(size=len(X[0])) * maximum_initial_w_value
converged = False
iterations = 0
while (not converged and iterations < self.max_iterations) :
converged = True
#evaluate lambda and put in tuple (i, lambda_value) in list 'lambdas'
lambdas = [(i, y[i] * np.dot(self.w, X[i])) for i in range(len(X))]
#filter for those i where lambda < c||w||
all_eligible = []
for lam in lambdas:
if (lam[1] < c * self.norm(self.w)):
all_eligible.append(lam)
# print all_eligible
# print len(all_eligible), 'less than c||w||'
# choose j (from all eligible i) for which lambda is maximized
j = ''
all_lambdas = [lam[1] for lam in all_eligible]
if (all_lambdas == []):
# none are eligible
converged = True
else:
for lam in all_eligible:
if (lam[1] == max(all_lambdas)):
j = lam[0]
break
if (j != ''):
#update w
self.w = self.w + y[j] * self.learning_rate * X[j]
converged = False
else:
converged = True
# stop if no more corrections are made
# if (False):
# converged = True
iterations += 1
self.converged = converged
if converged :
print 'PerceptronModified converged in %d iterations ' % iterations
else:
print 'PerceptronModified ran for %d iterations' % iterations
print 'C =', c
def generate_separable_data(N) :
w = np.random.uniform(-1, 1, 2)
print w,w.shape
X = np.random.uniform(-1, 1, [N, 2])
print X,X.shape
y = np.sign(np.dot(X, w))
return X,y,w
def plot_data(X, y, w) :
fig = plt.figure(figsize=(5,5))
plt.xlim(-1,1)
plt.ylim(-1,1)
a = -w[0]/w[1]
pts = np.linspace(-1,1)
plt.plot(pts, a*pts, 'k-')
cols = {1: 'r', -1: 'b'}
for i in range(len(X)):
plt.plot(X[i][0], X[i][1], cols[y[i]]+'o')
plt.show()
if __name__=='__main__' :
X,y,w = generate_separable_data(40)
p = Perceptron()
p.fit(X,y) |
6d4e1fbe3bd8329a5d7b3213261a960123cb8cbf | GustavMH29/Python | /Code/Math/Equations/Square.py | 450 | 3.96875 | 4 | # Written by RF
while True:
Q=float(input("What number would you like to square? "))
H=float(input("How many times would you like to square it? "))
S=((Q)**H)
print("The", H, "square is", S)
while True:
answer = str(input('Anything else? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Godspeed")
break
|
792a70d666f23881f20c1a77706696cedd724449 | csj561/python | /code/list/list.py | 1,060 | 3.59375 | 4 | #! /usr/bin/python
# -*- coding: UTF-8 -*-
import random
'''
序号 函数
1 cmp(list1, list2)
比较两个列表的元素
2 len(list)
列表元素个数
3 max(list)
返回列表元素最大值
4 min(list)
返回列表元素最小值
5 list(seq)
将元组转换为列表
序号 方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort([func])
对原列表进行排序
'''
i=100
ls=[]
while i>0:
i-=1
ls.append(random.randrange(100))
#print "ls: ",ls
ls.sort()
#print "ls: ",ls
ls.reverse()
#print "ls: ",ls |
c1e4afa7990b5a925d61eeaab1ac9a8dd290151f | Devu17/luminar | /venv/armstrong.py | 118 | 3.96875 | 4 | num=int(input("enter number"))
sum=0
while(num!=0):
digit=num%10
sum=sum+(digit**3)
num=num//10
print(sum) |
f08f4b0fb31e757b8328726fda198dddd2865ea8 | jell0720/Python27_Sublime_Dondon | /src/ClassContens/firstClass/Dictionary.py | 355 | 3.703125 | 4 | #coding=utf-8
dic = {'a':100, 'b':"yes", 'c':0.98, 'a':600}
print dic['c']
print dic.keys()
print dic.values()
print dic.get('c')
dic2 = dic
print dic2
dic['d'] = 811
print dic
dic.update({'e':'string'})
print dic
for key in dic:
print key,dic[key]
print dic2
def func(x):
return {'a': 1,'b': 2}.get(x)
func('b')
|
946968c7c03af1f1e363f62538061cba3e0b6b36 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Arrays/189_rotate_array.py | 1,496 | 4.3125 | 4 | # Given an array, rotate the array to the right by k steps, where k is non-negative.
#
# Example 1:
#
# Input: [1,2,3,4,5,6,7] and k = 3
# Output: [5,6,7,1,2,3,4]
# Explanation:
# rotate 1 steps to the right: [7,1,2,3,4,5,6]
# rotate 2 steps to the right: [6,7,1,2,3,4,5]
# rotate 3 steps to the right: [5,6,7,1,2,3,4]
# Example 2:
#
# Input: [-1,-100,3,99] and k = 2
# Output: [3,99,-1,-100]
# Explanation:
# rotate 1 steps to the right: [99,-1,-100,3]
# rotate 2 steps to the right: [3,99,-1,-100]
# Note:
#
# Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
# Could you do it in-place with O(1) extra space?
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
# Credits -> https://leetcode.com/problems/rotate-array/description/
# Idea -> First reverse the given array
# Then reverse the first k elements
# Then reverse the next n - k elements
k = k % len(nums)
reverse_helper(nums, 0, len(nums) - 1)
reverse_helper(nums, 0, k-1)
reverse_helper(nums, k, len(nums)-1)
return nums
def reverse_helper(nums, start, end):
"""
Helper function to reverse the elements of array
"""
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
# Examples
arr = [1, 2, 3, 4, 5, 6, 7]
n = 4
print(rotate(arr, n))
|
9dca59febb70dbeff743ba49cf108fb9faa1a803 | bsivavenu/Machine-Learning | /Advanced python 7 - 8/Exception/Demo4.py | 442 | 4.09375 | 4 | # WAP to Validate User Given AGE
# Age must be in B/W 23 to 40
def validate_age(given_age):
if((given_age>=23) and (given_age<=40)):
print("Valid Age")
else:
raise ValueError("Invalid Age")
#raise throw an Exception
age = int(input("Enter Age : "))
try:
validate_age(age)
except ValueError as ve:
print(ve)
else:
print("Thanks For Validating Age")
finally:
print("Thanks")
|
3fd57122f8c3933df471cfc70adeba612ce58945 | srinicoder035/Programming-Paradigms | /Assignment1/list.py | 1,286 | 3.921875 | 4 | class Node:
def __init__(self, val):
self.data = val
self.next = None
class List:
def __init__(self):
self.head = None
def addNode(self,val):
temp = Node(val)
if self.head == None:
self.head = temp
return
last = self.head
while(last.next):
last = last.next
last.next = temp
def deleteNode(self,val):
if self.head == None:
return False
if self.head.data == val:
self.head = self.head.next
return True
temp = self.head
while(temp):
if(temp.data == val):
break
temp = temp.next
if temp == None:
return False
temp1 = self.head
while(temp1.next!=temp):
temp1 = temp1.next
temp1.next = temp.next
return True
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
if __name__ == '__main__':
li = List()
li.addNode(1)
li.addNode(2)
li.addNode(3)
li.printList()
if li.deleteNode(5):
print("After deletion")
li.printList()
else:
print("Node doesn't exist") |
b18dc5583aeef8ad434ff6860fdc59a3348c5f41 | etscrivner/dse | /lib/integration.py | 4,648 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
lib.integration
~~~~~~~~~~~~~~~
Module for handling numerical integration.
Integrator: Interface that uses Simpson's Rule to numerically integrate a
function.
is_even(): Indicates whether or not the given integer value is even.
derivative(): Return a function that returns derivative of given function.
newton_raphson(): Uses the Newton-Raphson method to compute fixed point
of the given function.
approximate_inverse(): Approximate the inverse of a function at the given
point.
"""
class Integrator(object):
"""Interface that uses Simpson's Rule to numerically integrate a function.
"""
def __init__(self, number_of_segments, acceptable_error):
"""Initialize the integrator with tolerance values.
Arguments:
number_of_segments(int): Even number indicating the number of
segments to initially divide ranges into.
acceptable_error(float): The acceptable degree of error in the
result.
"""
if not is_even(number_of_segments):
raise ValueError(
"Simpson's rule requires an even number of segments")
self.number_of_segments = number_of_segments
self.acceptable_error = acceptable_error
def integrate(self, func, lower_limit, upper_limit):
"""Integrate the given function from lower limit to higher limit.
Arguments:
func(callable): The function to be integrated
lower_limit(float): The lower limit for the integration.
upper_limit(float): The upper limit for the integration.
Returns:
float: The approximation to the integral.
"""
previous_result = 0
num_segments = self.number_of_segments
while True:
segment_width = (upper_limit - lower_limit) / num_segments
result = func(lower_limit) + func(upper_limit)
for point in range(1, (num_segments / 2)):
result += 2 * func(lower_limit + (2 * point * segment_width))
for point in range(1, (num_segments / 2) + 1):
result += 4 * func(
lower_limit + ((2 * point - 1) * segment_width))
result *= (segment_width / 3)
if abs(result - previous_result) < self.acceptable_error:
return result
previous_result = result
num_segments = 2 * num_segments
def integrate_minus_infinity_to(self, func, upper_limit):
"""Integrate the given function from negative infinity to the
given upper limit.
Arguments:
func(callable): The function to be integrated
upper_limit(float): THe upper limit for the integration.
Returns:
float: The approximation to the integral.
"""
result = self.integrate(func, 0, abs(upper_limit))
if upper_limit < 0:
return 0.5 - result
return 0.5 + result
def is_even(x):
"""Indicates whether or not the given value is even.
Arguments:
x(int): An integer value
Returns:
bool: True if the value is even, False otherwise.
"""
return (x % 2 == 0)
def derivative(f, dx=10E-8):
"""Returns a function that will compute the value of the derivative of the
given function at any point x.
Arguments:
f(callable): A function
dx(float): Very small dx value
Returns:
callable: Derivative function
"""
def df(x):
return (f(x + dx) - f(x)) / dx
return df
def newton_raphson(f, guess, tolerance=1E-8):
"""Use the Newton-Raphson method to compute the fixed-point of the given
function.
Arguments:
f(callable): A function that takes a single variable x.
guess(float): The initial guess
tolerance(float): The acceptable tolerance for an answer.
Returns:
float: The approximate fixed point for the given function.
"""
df = derivative(f)
newton = lambda x: (x - (f(x) / df(x)))
current_guess = guess
next_guess = newton(guess)
while abs(next_guess - current_guess) > tolerance:
current_guess = next_guess
next_guess = newton(current_guess)
return next_guess
def approximate_inverse(f, point):
"""Approximate the inverse of the function for the given point.
Arguments:
f(callable): A function
point(float): The point to compute the inverse of
Returns:
float: The approximate inverse
"""
h = lambda x: f(x) - point
return newton_raphson(h, 0.5)
|
9328570129da614a62d08bb5467b1a7f1cb53bc0 | pko89403/Python-Study | /ProgrammingPattern/FactoryPattern/SimpleFactoryMethod-Job.py | 553 | 3.96875 | 4 | from abc import ABCMeta, abstractmethod
class Job(metaclass=ABCMeta):
@abstractmethod
def do_something(self):
pass
class Student(Job):
def do_something(self):
print("Let's do the study")
class Worker(Job):
def do_something(self):
print("Let's do the work")
class SimpleFactory(object):
def do_it(self, object_type):
return (eval(object_type.capitalize())().do_something())
if __name__ == "__main__":
job = input("What is your job? Student? Worker?")
f = SimpleFactory()
f.do_it(job) |
d1b735688abf2611abecb56fad87cbc045bf56b9 | Sultanggg/codeabbey | /q30.py | 435 | 3.671875 | 4 | #neumanns random generator
mylist = ['7735', '2754', '3453', '746', '3234', '4421' ,'3017' ,'2663', '9348', '6694']
def neumanns(mystr):
n = int(mystr)
first = n**2
pad = "%08d"%(first)
newstr = str(pad)
nextstr = pad[2:6]
return nextstr
for i in mylist:
emptylist = [i]
x = neumanns(i)
while x not in emptylist:
emptylist.append(x)
x = neumanns(x)
print(len(emptylist))
|
929e4781b38840be62cc7354067e346d2235a9a5 | Judahmeek/OldCode | /Python/Python 2/sum_power_max.py | 2,803 | 3.546875 | 4 | ''' https://www.hackerrank.com/contests/world-codesprint-april/challenges/little-alexey-and-sum-of-maximums
Alexey is playing with an array, AA, of nn integers. His friend, Ivan, asks him to calculate the sum of the maximum values for all subsegments of AA.
More formally, he wants Alexey to find F(A)=∑l=1n∑r=ln maxl≤x≤r A[x]F(A)=∑l=1n∑r=ln maxl≤x≤r A[x].
Alexey solved Ivan's challenge faster than expected, so Ivan decides to add another layer of difficulty by having Alexey answer mm queries. The ithith query contains subsegment [Li,Ri][Li,Ri], and he must calculate the sum of maximum values on all subsegments inside subsegment [Li,Ri][Li,Ri].
More formally, for each query ii, Alexey must calculate the following function:
F(A,Li,Ri)=∑l=LiRi∑r=lRimaxl≤x≤r A[x]F(A,Li,Ri)=∑l=LiRi∑r=lRimaxl≤x≤r A[x].
Can you help Alexey solve this problem?
Input Format:
The first line contains 22 space-separated positive integers, nn (the length of array AA) and mm (number of queries), respectively.
The second line contains nn space-separated integers, a0,a1,…,an−1a0,a1,…,an−1 describing each element ajaj (where 0≤j<n0≤j<n) in array AA.
Each of the mm subsequent lines contains 22 space-separated positive integers describing the respective values for LiLi and RiRi in query ii (where 0≤i<m0≤i<m).
Output Format:
For each query ii (where 0≤i<m0≤i<m), print its answer on a new line.
'''
class PowerSum:
def __init__(self, list):
self.level = [list]
def max(self, pos, distance):
#print "max", pos, distance
if distance == 0:
return self.level[0][pos]
while len(self.level) <= distance:
self.level.append({})
#print pos, "in or not in", self.level[distance]
if pos not in self.level[distance]:
self.level[distance][pos] = max(self.max(pos, distance - 1), self.max(pos + 1, distance - 1))
#print self.level[distance][pos], "= max(", self.max(pos, distance - 1), self.max(pos + 1, distance - 1)
return self.level[distance][pos]
def sum(self, pos, distance):
if distance == 0:
return self.level[0][pos]
acc = self.max(pos, distance)
#print "initial:", acc
#print self.level, pos, distance
for stop in xrange(1, distance):
level = distance - stop
for i in xrange(0, stop + 1):
#print level, i
acc += self.level[level][i]
acc += sum(self.level[0][pos: pos + distance + 1])
return acc
size, queries = map(int, raw_input().split())
calc = PowerSum(map(int, raw_input().split()))
for i in xrange(queries):
query = map(int, raw_input().split())
print calc.sum(query[0] - 1, query[1] - query[0]) |
18574229d4e7d819b2d64a3d5b01dcb4e0e43bf6 | bhojnikhil/LeetCodeProblems | /Grokking/Sliding Window/smallest_subarry.py | 1,066 | 4.03125 | 4 | # smallest contiguous subarray whose sum is greater than or equal to ‘S’
# Input: [2, 1, 5, 2, 3, 2], S=7
# Output: 2
# Explanation: The smallest subarray with a sum greater than or equal to '7' is [5, 2]
# arr=[2, 1, 5, 2, 3, 2]
# s=7
# N = len(arr)
def smallest_subarray_with_given_sum(s, arr):
shortestLen = 999
currentLen = 0
windowStart = 0
window_sum = 0
for windowend in range(0,len(arr)):
window_sum += arr[windowend]
print("Window SUm",window_sum)
print("Window End",windowend)
while window_sum >= s:
shortestLen = min(shortestLen, windowend - windowStart + 1)
window_sum -= arr[windowStart]
windowStart += 1
return shortestLen
def main():
print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])))
# print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])))
# print("Smallest subarray length: " + str(smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])))
main()
|
e02a472a9f52e2ddb6662c3bac4ee4a59c08dbfc | i8cake/querygeneration | /genquery.py | 3,678 | 3.59375 | 4 | #program to create queries
def gen(*stmts):
global flag
k=len(stmts) #find number of list in argument
if k==1:
q,s=simple(stmts[0]) #it is a simple query
print(s)
else:
flag=1
multi(stmts) #uses and/or
#function to generate simple queries
def simple(stmt):
global flag
#print(stmt)
coll=stmt[0]
con=-1
if coll[0]!='1': #to see if a collection is present
print("ERROR:Statement does not specify collection name")
return
else:
count=len(stmt) #find the number of items in simple list
c,coll,val,key=0,'0','0','0' #intialization
op=[]
for x in stmt:
if x[0]=='1': #for getting collection name
coll=x[2:]
elif x[0]=='2': #for getting the attribute/key
key=x[2:]
elif x[0]=='4': #for getting the value of attribute
val=x[2:]
elif x[0]=='5': #for checking condition
#flag=1
if x[2:]=="and":
con=1
else:
con=0
else: #for getting the operators
for j in x:
c=c+1 #counts number of operators
op=x[2:]
#op.append(item)
c=c-2
if c==1: #operation is either greater than or lesser than
if op[0]=='<':
s="db."+coll+".find({"+key+":{$lt:"+val+"}}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":"$lt"}
else:
s="db."+coll+".find({"+key+":{$gt:"+val+"}}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":"$gt"}
elif c==2: #operation is >= or <= or not equal to
if op=='<=':
s="db."+coll+".find({"+key+":{$lte:"+val+"}}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":"$lte"}
elif op=='>=':
s="db."+coll+".find({"+key+":{$gte:"+val+"}}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":"$gte"}
else:
s="db."+coll+".find({"+key+":{$ne:"+val+"}}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":"$ne"}
else: #operation is equal to
s="db."+coll+".find({"+key+":"+val+"}).pretty()"
q1= { "coll": coll, "key": key, "val":val,"op":""}
if flag==0:
#print(s)
return q1,s
else:
return q1,con
#function to generate multiple queries
def multi(stmts):
k=len(stmts)
q={}
for x in range(k-1): #to get individual queries for all except the last one
q[x],con=simple(stmts[x])
q[k-1],r=simple(stmts[k-1]) #to get the last individual query
if con==1:
con="and"
else:
con="or"
s="db."+q[0]["coll"]+".find({$"+con+":["
for x in range(k):
if q[x]["op"]=="":
s=s+"{"+q[x]["key"]+":"+q[x]["val"]+"}"
else:
s=s+"{"+q[x]["key"]+":{"+q[x]["op"]+":"+q[x]["val"]+"}}"
if x<=k-2:
s=s+","
else:
s=s+"]}).pretty()"
print(s)
flag=0
gen(["1:collection", "2:age","3:<=","4:10","5:or"],["1:collection", "2:name", "4:tom","5:and"],["1:collection", "2:mark", "4:100"])
|
ee380a976456d801d3deb70ff266d62c960e8d97 | dn1eper/genetic-trading | /mutator.py | 5,151 | 3.65625 | 4 |
from copy import deepcopy
from abc import ABC, abstractmethod
import random as rand
import math
class Mutator(ABC):
@abstractmethod
def mutate(self) -> list:
pass
class RandomGeneChainMutator(Mutator):
def __init__(self, n:int):
if n > 0:
self._n = n
else:
raise ValueError("n must be greater than 0")
def mutate(self, gene_chains: list):
result = [deepcopy(gene_chains[0]) for i in range(self._n)]
for gene_chain in result:
gene_chain.set_random()
return gene_chains + result
class MutRandomIndivs(Mutator):
def __init__(self, sigma, indiv_indpb, gene_indpb, save_part):
self.sigma = sigma
self.indiv_indpb = indiv_indpb
self.gene_indpb = gene_indpb
self.save_part = save_part
def mutate(self, individuals: list):
save_indivs = int(len(individuals) * self.save_part)
save_indivs = save_indivs + 1 if save_indivs == 0 else save_indivs
new_indivs = deepcopy(individuals[:save_indivs])
for idx in range(len(individuals) - save_indivs):
indiv = deepcopy(rand.choice(individuals))
if rand.random() < self.indiv_indpb:
GausianMutator(indiv, self.sigma, self.gene_indpb)
new_indivs.append(indiv)
return new_indivs
def GausianMutator(individual, sigma, indpb):
"""
Mutate individual in place; sigma much higher that 0.25 can will leed to long execution time
:param sigma: mutation strength, 0.05 < sigma < 0.25 recommended
:param indpb: independent probability of each gene to mutate
:returns new individual
"""
for idx, gene in enumerate(individual):
if rand.random() > indpb:
dtype = gene.type
if dtype == bool:
gene.value(not gene.value())
continue
min_value, max_value = gene.min, gene.max
if not gene.is_interval:
sigma_v = sigma * (min_value - max_value)
if dtype == int and sigma_v < 0.5:
sigma_v = 0.5
result = math.inf
i = 0
while not min_value <= result <= max_value:
result = rand.gauss(gene.value(), sigma_v)
if dtype == int:
result = dif.floor(result)
if i > 10000:
raise ValueError("tried to mutate trading attribute over 10 000 times")
i += 1
gene.value(result)
else:
# finding center for new range
rng_srt, rng_end, rng_ctr = gene.range_start(), gene.range_end(), gene.range_center()
min_rng = gene.min_range
min_rad = min_rng / 2
rng = rng_end - rng_srt
rng_rad = rng / 2
min_rng_ctr, max_rng_ctr = min_value + (min_rng / 2), max_value - (min_rng / 2)
sigma_c = sigma * (max_rng_ctr - min_rng_ctr)
if dtype == int and sigma_c < 0.5: # to make int variables with small range be able to mutate
sigma_c = 0.5
if dtype == int and (rng_srt % 1 != 0 or rng_end % 1 != 0):
raise ValueError("int attribute has floating point range\n" + gene)
counter = 0
new_rng_ctr = math.inf
while new_rng_ctr > max_rng_ctr or new_rng_ctr < min_rng_ctr:
new_rng_ctr = rand.gauss(rng_ctr, sigma_c)
if dtype == int:
new_rng_ctr = dif.floor_to_05(new_rng_ctr)
if counter >= 10000:
print("min_rng_ctr =", min_rng_ctr, "max_rng_ctr =", max_rng_ctr, rng_ctr, sigma_c)
raise ValueError("tried to generate new range center over 10000 times")
counter += 1
max_rad = min(new_rng_ctr - min_value, max_value - new_rng_ctr)
sigma_r = sigma * (max_rad - (min_rng / 2))
if dtype == int and sigma_r < 0.5:
sigma_r = 0.5
mu = min(rng_rad, max_rad)
new_rng_rad = math.inf
counter = 0
while new_rng_rad < min_rad or new_rng_rad > max_rad:
new_rng_rad = rand.gauss(mu, sigma_r)
if dtype == int and new_rng_ctr % 1 == 0.5:
new_rng_rad = dif.floor_to_05(new_rng_rad)
if new_rng_rad % 0.5 != 0:
new_rng_rad = math.inf
elif dtype == int and new_rng_ctr % 1 == 0:
new_rng_rad = dif.floor(new_rng_rad)
if (counter >= 100):
print(new_rng_ctr, min_rad, min_value, max_value, sigma_r, sigma)
raise ValueError("tried to generate new range radius over 100 times")
counter += 1
gene._range_center = new_rng_ctr
gene.radius(new_rng_rad)
return []
|
accc852cf4c460d0d9e52b1601e9e03437574d1f | flatlining/ProjectEuler | /p0004.py | 923 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Matias Schertel (flatlining@ProjectEuler) - [email protected]
# Most simple one
def SimpleSolution():
large = 0
for n in range(999, 99, -1):
for m in range(n, 99, -1):
if str(m*n) == str(m*n)[::-1] and m*n > large:
large = m*n
print "> The largest palindrome from the product of two 3-digit numbers is %s" % (large)
# A refined solution
def RefinedOne():
print "> %s" % ()
if __name__ == '__main__':
import sys, re
from timeit import Timer
SOLUTION = "SimpleSolution"
TESTS = 1
PNUM = re.split("p0*", sys.argv[0].split(".")[0])[1]
print ">>> Project Euler / Problem %s - http://projecteuler.net/index.php?section=problems&id=%s" % (PNUM, PNUM)
t = Timer(SOLUTION + "()", "from __main__ import " + SOLUTION)
elapsed = t.timeit(number=TESTS)/TESTS
print ">>> Function %s() takes %0.5f seconds/pass" % (SOLUTION, elapsed)
|
43fea607dac8a649240031774cfcefd008b40dcb | pschafhalter/Johann | /voice_leading/helpers.py | 3,006 | 3.703125 | 4 | from music21 import interval
def is_lower_note(expected_lower, expected_upper):
"""Given two notes, returns whether the first note is lower or equal to the second note.
>>> from music21 import note
>>> is_lower_note(note.Note('C3'), note.Note('D3'))
True
>>> is_lower_note(note.Note('C3'), note.Note('B2'))
False
"""
return interval.getAbsoluteLowerNote(expected_lower, expected_upper) is expected_lower
def resolves(voice, resolve_interval):
"""Given a voice starting with the note that must resolve, checks whether it resolves according to the provided resolveInterval integer
>>> from music21 import note, stream
>>> voice = stream.Part()
>>> for current_note in map(note.Note, ['f4', 'e4', 'f4']):
... voice.append(current_note)
>>> resolves(voice, -2)
True
>>> resolves(voice, 2)
False
"""
if len(voice) < 2:
return True
first_note = voice[0]
for note in voice[1:]:
current_interval = interval.notesToInterval(first_note, note)
if current_interval.generic.directed == resolve_interval:
return True
# returns false if the resolve interval is wrong or there a chromatic step in the wrong direction
if current_interval.generic.directed != 1 or resolve_interval * current_interval.chromatic.directed < 0:
return
return True
def is_fourth(lower_note, upper_note):
"""Returns whether the interval between two given notes reduced to an octave is a is_fourth.
>>> from music21 import note
>>> c4 = note.Note('C4')
>>> f4 = note.Note('F4')
>>> g4 = note.Note('G4')
>>> is_fourth(c4, f4)
True
>>> is_fourth(c4, g4)
False
"""
test_interval = interval.notesToGeneric(lower_note, upper_note)
if test_interval.simpleUndirected == 4:
return True
return False
def is_perfect_fifth(lower_note, upper_note):
"""Returns whether the interval between two given notes reduced to an octave is a perfect fifth.
>>> from music21 import note
>>> c4 = note.Note('C4')
>>> g4 = note.Note('G4')
>>> g7 = note.Note('G7')
>>> is_perfect_fifth(c4, g4)
True
>>> is_perfect_fifth(c4, g7)
True
>>> is_perfect_fifth(g4, g7)
False
"""
test_interval = interval.Interval(lower_note, upper_note)
if test_interval.simpleName == "P5":
return True
return False
def is_perfect_octave(lower_note, upper_note):
"""Returns whether the interval between two given notes reduced to an octave is a perfect octave.
>>> from music21 import note
>>> c4 = note.Note('C4')
>>> c5 = note.Note('C5')
>>> is_perfect_octave(c4, c5)
True
>>> c6 = note.Note('C6')
>>> is_perfect_octave(c4, c6)
True
>>> g4 = note.Note('G4')
>>> is_perfect_octave(c4, g4)
False
"""
test_interval = interval.Interval(lower_note, upper_note)
if test_interval.semiSimpleName == "P8":
return True
return False
|
71037955dee0e6d9dd809c7bb47a561396cd3175 | daisy0x00/LeetCode_Python | /LeetCode628/LeetCode628.py | 536 | 3.890625 | 4 | #coding:utf-8
class Solution():
def maximumProduct(self, nums):
"""
:param nums: List[int]
:return: int
"""
if len(nums) < 3:
return 0
numsSorted = sorted(nums)
result1 = numsSorted[-1] * numsSorted[-2] * numsSorted[-3]
result2 = numsSorted[0] * numsSorted[1] * numsSorted[-1]
return max(result1, result2)
def main():
test = Solution()
nums = [-9, -8, 5, 6, 10]
print(test.maximumProduct(nums))
if __name__ == '__main__':
main() |
f64506c28f6fd883e0375ea9899496afedbb58da | MosaicOrange/Portfolio | /Python/pydev/HackerRank - Miscellaneous/compress_the_string.py | 457 | 3.625 | 4 | x = input().strip() + "x"
return_list = list()
last_value = ""
tmp_inc = 1
for c in x:
if c is "x":
return_list.append((tmp_inc, int(last_value)))
break
if last_value:
if int(last_value) == int(c):
tmp_inc += 1
else:
return_list.append((tmp_inc, int(last_value)))
last_value = c
tmp_inc = 1
else:
last_value = c
for x in return_list:
print(x, end=" ") |
91bcd6886a825494f0013eb115ee3f8ac5871ec8 | LialinMaxim/Toweya | /league_table.py | 2,866 | 4.21875 | 4 | """
The LeagueTable class tracks the score of each player in a league.
After each game, the player records their score with the record_result function.
The player's rank in the league is calculated using the following logic:
* The player with the highest score is ranked first (rank 1). The player with the lowest score is ranked last.
* If two players are tied on score, then the player who has played the fewest games is ranked higher.
* If two players are tied on score and number of games played,
then the player who was first in the list of players is ranked higher.
Implement the player_rank function that returns the player at the given rank.
For example:
table = LeagueTable(['Mike', 'Chris', 'Arnold'])
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print(table.player_rank(1))
All players have the same score.
However, Arnold and Chris have played fewer games than Mike, and as Chris is before Arnold in the list of players,
he is ranked first. Therefore, the code above should display "Chris".
"""
class LeagueTable:
__empty_player = {'scores': 0, 'games': 0, 'last_game': None}
__last_game = 0
def __init__(self, players: list):
self.players = {p: dict(LeagueTable.__empty_player) for p in players} # dict() need to make a new objs
def __srt__(self):
return f'<LeagueTable obj: {self.players}>'
def record_result(self, player: str, score: int):
data_player = self.players.get(player)
if data_player:
data_player['scores'] += score
data_player['games'] += 1
data_player['last_game'] = self.__get_last_game()
def player_rank(self, rank=None):
if rank and (rank > len(self.players) or rank < 0):
return None
ps = self.players
# List of Tuples [(player name, scores, games, game order) ... ]
table_rank = [(p, ps[p]['scores'], ps[p]['games'], ps[p]['last_game']) for p in ps]
table_rank = sorted(table_rank, key=lambda p: (-p[1], p[2], p[3]))
if rank:
return table_rank[rank - 1]
return table_rank
def add_player(self):
pass
@classmethod
def __get_last_game(cls, ):
cls.__last_game += 1
return cls.__last_game
if __name__ == '__main__':
table = LeagueTable(['Mike', 'Chris', 'Arnold', 'Nike', 'Max'])
table.record_result('Max', 2)
table.record_result('Nike', 2)
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print('The leader:', table.player_rank(1), )
from pprint import pprint
print("\nRating of all players")
pprint(table.player_rank())
print("\nPlayers")
pprint(table.players)
|
6732cc904880abe386974c871a3e8c5d599cb6bc | TheFibonacciEffect/interviewer-hell | /palindromes/is_palindrome.py | 1,551 | 3.65625 | 4 | """
Determines whether a string is a palindrome.
Requires the third-party 'regex' library; to obtain, 'pip install
regex'. See https://pypi.python.org/pypi/regex for details.
"""
import sys
import unicodedata
import unittest
import regex
def is_palindrome(s):
"""
Determines whether a given string is a palindrome.
"""
graphemes = [
g for g in regex.findall(
r'(\X)',
''.join(
c for c in
unicodedata.normalize('NFC', s.casefold())
if unicodedata.category(c).startswith('L')
)
)
]
return graphemes and graphemes == graphemes[::-1]
class PalindromeTests(unittest.TestCase):
def test_palindromes(self):
for p in (
'racecar',
'tacocat',
'Able was I, ere I saw Elba.',
'A man, a plan, a canal: Panama!',
'an\u0303a',
'a\u00f1a',
'\ufdfa',
):
self.assertTrue(is_palindrome(p))
def test_non_palindrome(self):
for p in (
'',
',!?',
'not',
'Able was I, ere I saw Elbe.',
unicodedata.normalize('NFKC', '\ufdfa'),
):
self.assertFalse(is_palindrome(p))
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(unittest.main())
if is_palindrome(sys.argv[1]):
print("Input is a palindrome.")
else:
print("Input is not a palindrome.")
|
70e771665ca4363716fa54df09e224190e6e4aea | ChirantanTech/wordcounter | /wordcounter.py | 218 | 4.09375 | 4 | print("Welcome to the word counter software.")
a = input("Type the article you want to count the words : ")
print("Number of words in these string is:",len(a))
#Desc
A simple beginner project created in python.
|
ef71a581e9b955e55434c7447b2326483d42c528 | sarathkumar1981/MYWORK | /Python/AdvPython/Files/stringcheckfile.py | 215 | 3.65625 | 4 | with open('filecore.txt','w') as fob:
print("please enter the text\n")
str= None
while (str!='@'):
str = input()
if (str !='@'):
fob.write(str + '\n')
#print(fob.read()) |
bb286e11918e609c9755157e17f64ed373b918fe | IshmaelDojaquez/Python | /Python101/NestedLoops.py | 290 | 4.28125 | 4 | for x in range(4):
for y in range(3):
print(f"{x},{y}") # nesting a for loop in a for loop to make coordinate values
# Practice
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
output = ''
for count in range(x_count):
output += 'x'
print(output) |
27a8d1b4d72f520cfa44f6bed9807be50beed1c2 | lucianoww/Python | /pybrexer0007.py | 542 | 4.34375 | 4 | '''
Solução para exercicios https://wiki.python.org.br/EstruturaSequencial
#07) Faça um Programa que calcule a área de um quadrado,
em seguida mostre o dobro desta área para o usuário.
'''
comprimentox=float(input('Digite o comprimento :'))
largurax=float(input('Digite a largura :'))
areax=comprimentox*largurax
print('Uma área com {} de comprimento por {} de largura possui uma area total de {} em m²'
.format(comprimentox, largurax, areax))
print('O dobro desta área em m²: {}'.format(areax*2)) |
42c119150aa13a3ab523d8012db81eab139ecacb | Greilfang/OS | /FileSystem/code/basics.py | 2,140 | 3.515625 | 4 | #超级块,记录文件系统信息
class SuperBlock(object):
def __init__(self):
self.file_system_name = "GreilOS"
self.bit = 8
self.file_system_size = 1024*1024*1024 #1G的文件大小
self.block_index_size = 4 #块索引的大小
self.node_size = 128 #每一个数据块的大小
self.node_num = 120 #最多存储120个文件
self.data_block_size = 8 * 1024
self.data_block_num = 12000
self.__address_size = 4
class Node(object):
def __init__(self,sign=None):
self.file_size = 0
self.block_num = 0
self.sign=sign
#用于表示其对应的数据块节点
self.block_index = {}
#采用ufs的索引结构
for i in range(12):
self.block_index[i]=None
self.block_index[13]={}
#文件大小信息处理函数
def get_file_size(self):
return self.file_size
def set_file_size(self,file_size):
self.file_size=file_size
def set_sign(self,sign):
self.sign=sign
def set_block_indexs(self,block_indexs):
#传入索引块数据列表
self.block_num=len(block_indexs)
count=0
for index in block_indexs:
count=count+1
if count<13:
self.block_index[count]=index
elif count>=13 and count<2048+13:
self.block_index[13][count-12]=index
#用于返回i节点的信息
def get_file_information(self):
return{"size":self.file_size,"block_num":self.block_num}
def get_block_indexs(self):
index_dict=self.block_index
block_indexs=[]
count = 0
for i in range(self.block_num):
count = count+1
if count < 13:
block_indexs.append(self.block_index[count])
elif count >= 13 and count < 2048 + 13:
block_indexs.append(self.block_index[13][count-12])
return block_indexs
class User(object):
def __init__(self):
self.dir_index = 0
def set_dir_index(self,dir_index):
self.dir_index = dir_index
|
44e5807fad722b84076472ba42f1871a22bccc22 | Ayushmanglani/competitive_coding | /leetcode/May/LC_M7_BinaryTreeCousins.py | 1,053 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def level(root, a, l):
if root is None:
return 0
if root.val == a:
return l
lv = level(root.left,a,l+1)
if lv != 0:
return lv
return level(root.right,a,l+1)
def isSibling(root,a,b):
if root is None:
return 0
try:
if (root.left.val == a and root.right.val == b) or (root.left.val == b and root.right.val == a) :
return True
except:
if (root.left == a and root.right == b) or (root.left == b and root.right == a) :
return True
return (isSibling(root.left, a, b) or isSibling(root.right, a, b))
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
if ((level(root,x,1) == level(root, y, 1)) and
not (isSibling(root, x, y))):
return 1
else:
return 0
|
f3eaba6966eaa390fbdcdf4592c8d9bd96195a6a | jakubpulaczewski/codewars | /8-kyu/reversed-words.py | 726 | 4.21875 | 4 | """
Reversed Words
The link: https://www.codewars.com/kata/51c8991dee245d7ddf00000e
Problem Description:
Complete the solution so that it reverses all of the words within the string passed in.
Examples:
reverseWords("The greatest victory is that which requires no battle")
should return "battle no requires which that is victory greatest The"
"""
#First Solution
def reverseWords(s):
text = s.split()
text.reverse()
str = ""
for word in range(len(text)):
if word < len(text) - 1:
str = str + text[word] + " "
else:
str = str + text[word]
return str
# more robust solution
def reverseWords(str):
return " ".join(str.split(" ")[::-1])
|
d25bece5be6109e24fd77541f6c79afcba55c7ad | JustinDoghouse/LeetcodeAnswer | /Swap Nodes in Pairs.py | 581 | 3.765625 | 4 | __author__ = 'burger'
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
if not head or not head.next:
return head
h = ptr = ListNode(0)
ptr.next = head
while ptr.next and ptr.next.next:
tmp = ptr.next
ptr.next = tmp.next
tmp.next = ptr.next.next
ptr.next.next = tmp
ptr = tmp
return h.next |
173b24af94ddf098fc0a8788059cdfb177b60e85 | ctc316/algorithm-python | /Lintcode/Tag_String/421. Simplify Path.py | 453 | 3.796875 | 4 | class Solution:
"""
@param path: the original path
@return: the simplified path
"""
def simplifyPath(self, path):
cmds = path.strip().split("/")
dirs = []
for c in cmds:
if c == '' or c == '.':
continue
elif c == '..':
if len(dirs) > 0:
dirs.pop()
else:
dirs.append(c)
return "/" + "/".join(dirs) |
195060f0693a50422ddcfc32430a5ef645df3630 | zhxgigi/toolkids | /python/singleton.py | 438 | 3.65625 | 4 |
class Singleton(object):
def __new__(cls, *args, **argkw):
if not hasattr(cls, "_instance"):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **argkw)
return cls._instance
class MyClass(Singleton):
def __init__(self):
self.name = "zhang"
for i in range(10):
ss = MyClass()
print id(ss)
class MySubClass(MyClass):
age = 10
msc = MySubClass()
|
3c534b9c97f4bbcaee7e7deeee185d262436ae00 | colin-bethea/competitive-programming | /codeforces/A_Boy_or_Girl.py | 243 | 3.65625 | 4 | __author__ = 'Colin Bethea'
def main(name):
charset = set()
for char in name:
charset.add(char)
return 'CHAT WITH HER!' if len(charset) % 2 == 0 else 'IGNORE HIM!'
if __name__ == "__main__":
name = input()
print(main(name))
|
237c921c9d5702544ca8abe11a85e353ee998a3d | Gio1609/Python_Basic | /chap-1_Arrays_and_Strings/1.9.py | 370 | 4.0625 | 4 | # Given two strings s1 and s2, write code to check if s2
# is a rotation of s1 using only one call to isSubstring
def isRotation(s1, s2):
if len(s1) == len(s2) and len(s1) > 0:
s1s1 = ''.join([s1, s1])
if s2 in s1s1:
return True
return False
if __name__ == "__main__":
import sys
print(isRotation(sys.argv[1], sys.argv[2])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.