blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
efcb7e7ad8bdadbbe60e67a1d675b57341ab4131 | saequus/learn-python-favorites | /Patterns/StrategyPattern.py | 1,290 | 3.6875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Context:
def __init__(self, strategy: Strategy) -> None:
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy: Strategy) -> None:
self._strategy = strategy
def do_business_logic(self):
print("Working according to chosen %s's plan." % self._strategy)
result = self._strategy.do_algorithm(['d', 'da', '3s', 'vm', 'a', 'da9'])
print(''.join(str(i) for i in result))
class Strategy(ABC):
@abstractmethod
def do_algorithm(self, data: List):
pass
class ConcreteStrategyA(Strategy):
class Meta:
verbose_name = 'Strategy A'
def do_algorithm(self, data: List):
return sorted(data)
def __str__(self):
return self.Meta.verbose_name
class ConcreteStrategyB(Strategy):
def __init__(self):
self._name = 'Strategy B'
def do_algorithm(self, data: List):
return reversed(sorted(data))
def __str__(self):
return self._name
context = Context(ConcreteStrategyA())
context.do_business_logic()
context.strategy = ConcreteStrategyB()
context.do_business_logic()
|
5610a99d5ef0fc6c26b5dcf6cdeab13dd262d357 | saequus/learn-python-favorites | /Tasks/AdjacencyListGraph.py | 868 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.vertex = data
self.next = None
class Graph:
def __init__(self, verteces):
self.V = verteces
self.graph = self.V * [None]
def add_edge(self, src, dst):
node = Node(dst)
node.next = self.graph[src]
self.graph[src] = node
node = Node(src)
node.next = self.graph[dst]
self.graph[dst] = node
def print_graph(self):
for i in range(self.V):
print('Adj vertex {}'.format(i), end='')
temp = self.graph[i]
while temp:
print(' --> {}'.format(temp.vertex), end='')
temp = temp.next
print('\n')
g = Graph(6)
g.add_edge(0, 1)
g.add_edge(0, 3)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)
g.add_edge(3, 5)
g.add_edge(4, 5)
g.print_graph()
|
f2817ece55a255b4fcba92a35384f296f8954ad9 | saequus/learn-python-favorites | /Tasks/241_DIfferentWaysToAddParentheses.py | 996 | 3.6875 | 4 | class Solution(object):
def comp(self, exp):
if len(exp) == 1:
return [int(exp[0])]
res_list = []
# [left] [i] [right]
for i in range(1, len(exp), 2):
left_list = self.comp(exp[:i])
right_list = self.comp(exp[i + 1:])
for l in left_list:
for r in right_list:
if exp[i] == '+':
res_list += [l + r]
elif exp[i] == '-':
res_list += [l - r]
else:
res_list += [l * r]
return res_list
def diff_ways_to_compute(self, exp):
import re
exp = re.findall(r'(\d+|\W)', exp)
return self.comp(exp)
# Code driver
solution = Solution()
print(solution.diff_ways_to_compute('2-1-1'))
print('To compare with: [2,0]')
print(solution.diff_ways_to_compute("2-4*3+1-5"))
print('To compare with: [6,6,-6,-9,-6,2,2,-14,-10,-19,-16,-13,-14,-10]')
|
82a2b51be110ac173653dabca2d3e17236a0d985 | saequus/learn-python-favorites | /Tasks/ReverseNumber.py | 837 | 3.9375 | 4 | # Reverse Number (Print Number Backwards)
# Given integers 1204900, 431, -453. The func must return 94021, 134, -354
def reverse_number(num) -> str: # not the fastest, optimise
""" Reverse number.
Keep negative if needed. Remove zeros if ended with 0.
:param: num
:return: str
"""
res = list()
neg = 0
num = int(num)
if num < 0:
num *= -1
neg = 1
while num % 10 == 0:
num /= 10
num = list(str(int(num)))
for i in range(len(num)):
res.append(num[-i - 1])
res = ''.join(str(res[j]) for j in range(len(num)))
res = int(res)
if neg == 1:
res *= -1
return 'Reversed number is %d' % res
# Driver Code
first = 1204900
second = 431
third = -453
print(reverse_number(first))
print(reverse_number(second))
print(reverse_number(third))
|
d630f1c990fecd8c466c3876f0f6a34a9084c262 | saequus/learn-python-favorites | /SortTypes/CountingSort.py | 1,151 | 3.609375 | 4 | # ============================================================================
# ========================== CountSort Algorithm =============================
# ============================================================================
def count_sort(arr):
output = [0 for _ in range(256)]
# Create a count array to store count of individual
# characters and initialize count array as 0
count = [0 for _ in range(256)]
# For storing the resulting answer since the
# string is immutable
ans = ["" for _ in arr]
# Store count of each character
for i in arr:
count[ord(i)] += 1
# Change count[i] so that count[i] now contains actual
# position of this character in output array
for i in range(256):
count[i] += count[i - 1]
# Build the output character array
for i in arr:
output[count[ord(i)] - 1] = i
count[ord(i)] -= 1
# Copy the output array to arr, so that arr now
# contains sorted characters
for i in range(len(arr)):
ans[i] = output[i]
return ans
a = 'work having no sleep and try to sort it'
ans = count_sort(a)
print(ans)
|
1f95015507e7f2a6137f3a4e172c384676b236e9 | saequus/learn-python-favorites | /Tasks/IsIntercalaryYear.py | 229 | 3.84375 | 4 | def isIntercalaryYear(n):
if n % 4 != 0 or (n % 100 == 0 and n % 400 != 0):
return '{} '.format(n) + 'year is usual.'
else:
return '{} '.format(n) + 'year is intercalary.'
print(isIntercalaryYear(1900))
|
96c1bae43ccfda525a075cdbccbb7751270fa77f | Bonaparto/Programming-Principles-II | /stepik/lilprojects/passwordgen.py | 1,078 | 3.90625 | 4 | import random
def generate_password(c, l):
print(*random.sample(c, l), sep='')
digits = '23456789'
lowercase_letters = 'abcdefghjkmnpqrstuvwxyz'
uppercase_letters = 'ABCDEFGHIJKMNPQRSTUVWXYZ'
punctuation = '!#$%&*+-=?@^_'
chars = ''
print('How many passwords do you need?')
amount = int(input())
print('Enter the length of passwords.')
plength = int(input())
print('Choose what the password(s) should contain.')
print('Enter "1" to add and "2" otherwise.\n')
print('Should password contain digits?')
if input() == '1':
chars += digits
print('Should password contain uppercase letters?')
if input() == '1':
chars += uppercase_letters
print('Should password contain lowercase letters?')
if input() == '1':
chars += lowercase_letters
print('Should password contain symbols?')
if input() == '1':
chars += punctuation
print('Should password contain confusable characters (il1Lo0O)?')
if input() == '1':
chars += 'il1Lo0O'
print('Generating in process...')
for i in range(amount):
generate_password(chars, plength)
print('Everything is done!') |
433fccd7627612b9feed8105f9860f9fa323d640 | Bonaparto/Programming-Principles-II | /weeks/week11/2.py | 2,040 | 3.609375 | 4 | import pygame
pygame.init()
White = (255, 255, 255)
Red = (255, 0, 0)
Green = (0, 255, 0)
Blue = (0, 0, 255)
Black = (0, 0, 0)
Win_Height = 600
Win_Width = 600
screen = pygame.display.set_mode((Win_Width, Win_Height))
screen.
clock = pygame.time.Clock()
block = 10
body = [[150, 150]]
def level_choose():
pass
def game_start():
title = 'SNAKE'
while True:
screen.fil(Black)
screen.blit()
def game_end():
pass
def save_game():
pass
class Player:
def __init__(self) -> None:
pass
class Food:
def __init__(self) -> None:
pass
dx, dy = block, 0
radius = 5
score = 0
menu_font = pygame.font.SysFont('arial', 100)
game_start()
game_end()
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
dx = block
dy = 0
if event.key == pygame.K_LEFT:
dx = -block
dy = 0
if event.key == pygame.K_UP:
dx = 0
dy = -block
if event.key == pygame.K_DOWN:
dx = 0
dy = block
if event.key == pygame.K_SPACE:
body.append([body[len(body) - 1][0], body[len(body) - 1][1]])
for i in range(len(body) - 1, 0, -1):
body[i][0] = body[i - 1][0]
body[i][1] = body[i - 1][1]
body[0][0] += dx
body[0][1] += dy
if body[0][0] < 10:
body[0][0] = Win_Width - radius
if body[0][0] > Win_Width - radius:
body[0][0] = radius
if body[0][1] < 10:
body[0][1] = Win_Height - radius
if body[0][1] > Win_Height - radius:
body[0][1] = radius
screen.fill(White)
for i, (x, y) in enumerate(body):
color = Red if i == 0 else Green
pygame.draw.circle(screen, Green, (x, y), radius)
pygame.display.flip()
clock.tick(30)
pygame.quit() |
54f54e98b511674581c7f8a66443a2ef7d6e94a7 | Bonaparto/Programming-Principles-II | /practice/1.py | 336 | 3.734375 | 4 | import turtle
wn = turtle.Screen()
wn.bgcolor('lightgreen')
cherepaha = turtle.Turtle()
cherepaha.color('purple')
cherepaha.shape('turtle')
cherepaha.speed(10)
cherepaha.pensize(6)
cherepaha.down()
move = 90
angle = 72
for i in range(5):
cherepaha.forward(move)
cherepaha.stamp()
cherepaha.right(angle)
wn.exitonclick() |
26610b9a962da30ef8dbe732e2a4c4fc4034a1d2 | Bonaparto/Programming-Principles-II | /ejudge/midtermg2/h.py | 307 | 3.84375 | 4 | n = input()
l = input().split()
n = list(input())
n.clear()
l1 = input().split()
for i in l:
if i not in l1:
n.append(i)
n1 = []
for i in l1:
if i not in l:
n1.append(i)
print('Missed students:')
for i in n:
print('-', i)
print('Not in the group:')
for i in n1:
print('-', i) |
1d5f61971e8c0fd10fcbe629415ea789410a148e | Bonaparto/Programming-Principles-II | /weeks/week6/1.py | 646 | 3.671875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def printer(self):
print(f'Name is: {self.name}', f'Age: {self.age}', sep='\n')
def summation(self, age2):
print(self.age + age2)
class Student(Person):
def __init__(self, name, age, school, grade):
self.school = school
self.grade = grade
super().__init__(name, age)
def printer1(self):
print(self.school, self.grade)
# p1 = Person('Kek', 931)
# p2 = Person('Lol', 123)
# p1.printer()
s1 = Student('Lol', '17', '49', '11A')
# print(s1.grade, s1.school)
s1.printer()
s1.printer1() |
69b96c77d2172ec2531e5868743ea8835483e6f5 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/types/d.py | 132 | 3.640625 | 4 | pi = 0
for i in range(0, 10):
if i % 2 == 0:
pi += (4 / (1 + i * 2))
else:
pi -= (4 / (1 + i * 2))
print(pi) |
6932fafa7b24d2bd97ed6f21dc99050fd4f85228 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/while/s.py | 165 | 3.59375 | 4 | b, a = int(input()), int(input())
while(a != b):
if(b // 2 >= a and b % 2 == 0):
b //= 2
print(':2')
else:
b -= 1
print('-1') |
8c9ae30706e1e811b6473b53120b8ca823b91410 | Bonaparto/Programming-Principles-II | /weeks/week1/informatics/funcs/n.py | 182 | 3.71875 | 4 | def sol(a, b):
if(b == 1):
return a
if(a == b or b == 0):
return 1
return (sol(a - 1, b - 1) + sol(a - 1, b))
print(int(sol(int(input()), int(input())))) |
11b9eeb47410574de7b944a6e55e61f5a5d31e88 | nmanzini/MPCSPE | /2012/raindrops/main.py | 221 | 3.78125 | 4 | from math import floor
input()
array = [int(x) for x in input().split(" ")]
validarray = [x for x in array if x >= 0]
if validarray == []:
print ("INSUFFICIENT DATA")
else:
print(floor(sum(validarray)/len(validarray))) |
713b343a06e3f6ea37971c487ee6a8c6c2eb30d0 | nmanzini/MPCSPE | /calendar/calendar_conondrum.py | 283 | 3.5625 | 4 |
import sys
line = sys.stdin.readline()
a,b,c = line.split(" ")
a = int(a)
b = int(b)
c = int(c)
if a > 31:
print ("Format #3")
elif a > 12 and a <=31:
if c > 31:
print("Format #2")
else:
print("ambiguous")
else:
if b >12:
print("Format #1")
else:
print("ambiguous") |
28b78648f715ffd78e51b9a5c234477dea70da0b | battistowx/cis1400 | /AverageGrade.py | 2,184 | 3.859375 | 4 | # Author: Chris Battisto
# Date: 10/15/2014
# Program: AverageGrade.py
# Descr:
# Program that takes an input of five percentage grades, calculates
# the average grade, and displays a letter grade for that average.
def main():
counter=4
listScores=[]
listGrades=[]
for counter in range(0,5):
localScore=getValidScore()
listScores.append(localScore)
indexCounter=0
for counter in range (0,5):
grade=str(determineGrade(listScores, indexCounter))
listGrades.append(grade)
indexCounter=indexCounter+1
print('Your Grades Are: ',listGrades)
print('Your Average Percentile is: ', calcAverage(listScores))
def getValidScore():
scoreInput=float(input('Input a score:'))
isInvalidScore(scoreInput)
if isInvalidScore(scoreInput)==True:
return scoreInput
else:
print('Input a score above 0 and below 100')
main()
def isInvalidScore(scoreInput):
if scoreInput >=0.0 and scoreInput <=100.0:
valid=True
return valid
else:
valid=False
return valid
def determineGrade(listScores, indexCounter):
if listScores[indexCounter] <60.0:
return 'F'
elif listScores[indexCounter] >=60.0 and listScores[indexCounter] <=69.9:
return 'D'
elif listScores[indexCounter] >=70.0 and listScores[indexCounter] <=79.9:
return 'C'
elif listScores[indexCounter] >=80.0 and listScores[indexCounter] <=89.9:
return 'B'
elif listScores[indexCounter] >=90.0 and listScores[indexCounter] <=100.0:
return 'A'
def calcAverage(listScores):
totalPercentile=float(listScores[0]+listScores[1]+listScores[2]+listScores[3]+listScores[4])
average=totalPercentile / 5
return average
main()
##OUTPUT:
##Input a score:101
##Input a score above 0 and below 100
##Input a score:-1
##Input a score above 0 and below 100
##Input a score:98.5
##Input a score:45.6
##Input a score:87.4
##Input a score:95.5
##Input a score:65.0
##Your Grades Are: ['A', 'F', 'B', 'A', 'D']
##Your Average Percentile is: 78.4
##Input a score:
|
dd9f3e8b4ff34e53b63af387666b3b4252dfbf41 | battistowx/cis1400 | /MarsMemoryGame/Mars_Memory_Class.py | 472 | 3.65625 | 4 | # MARSMemory.py Class
# This class generates a random numbered list
from random import random
class Mars_Memory:
def setGenerateList(self, generateList):
#generate a 10-item list of random numbers between 0 and 9
generateList=[]
for i in range (10):
generateList.append(random.randrange(0,15,1))
self.setGenerateList=generateList
def getGenerateList(self):
return self.generateList
|
8e9893c1df93bcf48ec9fec7b716b0d61c926809 | NWabuokei-Tega1/Early-days | /wordplay.py | 325 | 3.53125 | 4 | fin = open('/storage/sdcard0/crossword.txt')
for i in fin:
word = i.strip()
if len(i) == 20:
print(word)
print('-------------------------------')
#if a word has 'e', print False, else print True
text = open('/storage/sdcard0/crossword.txt')
#word = input('enter a word: ')
if 'e' not in text:
a = i
a = len(a)
print(a)
|
2bae5c52909db58b3f00e877dcae4934b0afe892 | rumdrums/ml | /cost_function.py | 261 | 3.734375 | 4 | import numpy as np
def cost(X, y, theta):
""" return cost, given matrices for X, y, theta """
m = y.shape[0]
predictions = X * theta
squared_errors = np.square((predictions-y))
numerator = 1.0/(2*m)
cost = numerator * squared_errors.sum()
return cost
|
fbbc647c801512f2e08097f0110f548088fdecf9 | petitlapin86/firstpython | /inputandoutput.py | 484 | 4 | 4 | #input and output
#ask for users name
name = input("what is your name? ")
#welcome user with name
print("Hi {}, get ready to play madlibs!".format(name))
verb = input("Please enter a verb: ")
noun = input("Please enter a noun: ")
adjective = input("Please enter a adjective: ")
print("I enjoy running. I find it helps me to", verb, "better.")
print("without running, my", noun, "would probably not even work.")
print("My speed is getting more", adjective, "every single day!")
|
cc943205395b920a32f5eaf3167dd1ce4338324e | blackwings001/algorithm | /leetcode/51-100/_73_setZeros.py | 821 | 3.59375 | 4 | class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
row = len(matrix)
col = len(matrix[0])
for i in range(row):
for j in range(col):
if matrix[i][j] == 0:
for m in range(row):
matrix[m][j] = "x" if matrix[m][j] != 0 else 0
for n in range(col):
matrix[i][n] = "x" if matrix[i][n] != 0 else 0
for i in range(row):
for j in range(col):
if matrix[i][j] == "x":
matrix[i][j] = 0
if __name__ == '__main__':
matrix = [
[0]
]
Solution().setZeroes(matrix)
print(matrix)
|
468a2362832863ac15f3ee5a529e47521dcb559b | blackwings001/algorithm | /leetcode/101-150/_148_sortList.py | 1,601 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
# 找到中间点
length = 0
p = head
while p:
p = p.next
length += 1
mid = head
length = length // 2 - 1
while length > 0:
mid = mid.next
length -= 1
tmp = mid
mid = mid.next
tmp.next = None
return self.merge(self.sortList(head), self.sortList(mid))
def merge(self, head1, head2):
if not head1:
return head2
if not head2:
return head1
dump = ListNode(0)
p = dump
while head1 and head2:
if head1.val < head2.val:
p.next = head1
head1 = head1.next
else:
p.next = head2
head2 = head2.next
p = p.next
if head1:
p.next = head1
elif head2:
p.next = head2
return dump.next
if __name__ == '__main__':
head1 = ListNode(5)
head2 = ListNode(3)
head3 = ListNode(1)
head4 = ListNode(2)
head5 = ListNode(4)
head1.next = head2
head2.next = head3
head3.next = head4
head4.next = head5
head = Solution().sortList(head1)
while head:
print(head.val)
head = head.next |
2178e78961ef078f714489330030c4d623c72043 | blackwings001/algorithm | /leetcode/51-100/_86_partition.py | 1,344 | 3.984375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head == None:
return None
# l是最后一个小于x的节点
dump = ListNode(0)
dump.next = head
l = dump
while head.next != None:
if head.val < x:
l = head
head = head.next
elif head.next.val >= x:
head = head.next
else: # 出现了逆序,前一个大于等于x,后一个小于x
tmp = head.next
head.next = tmp.next
tmp.next = l.next
l.next = tmp
l = l.next
return dump.next
if __name__ == '__main__':
head = ListNode(1)
head.next = ListNode(4)
head.next.next = ListNode(2)
head.next.next.next = ListNode(3)
head.next.next.next.next = ListNode(5)
head.next.next.next.next.next = ListNode(2.5)
head = Solution().partition(head, 3)
while head:
print("{} -> ".format(head.val), end="")
head = head.next
if head == None:
print(head)
|
dbaae72f54e8385e98da8ed826394323346f7bbd | blackwings001/algorithm | /leetcode/51-100/_97_isInterleave.py | 949 | 3.84375 | 4 | class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
n = len(s1)
m = len(s2)
if n + m != len(s3):
return False
# 进行动态规划
matrix = [[False for _ in range(m + 1)] for _ in range(n + 1)]
matrix[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
length = i + j
# 一共有两种情况,matrix[i][j]的值可以为True,
if (i != 0 and s1[i - 1] == s3[length - 1] and matrix[i - 1][j] == True) or (j != 0 and s2[j - 1] == s3[length - 1] and matrix[i][j - 1] == True):
matrix[i][j] = True
return matrix[n][m]
if __name__ == '__main__':
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbbaccc"
res = Solution().isInterleave(s1, s2, s3)
print(res) |
9ed01210152201461b2986c96ce71a4ab126db68 | blackwings001/algorithm | /leetcode/1-50/_9_isPalindrome.py | 441 | 3.78125 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
reverse_x = 0
tmp = x
while tmp != 0:
reverse_x = reverse_x * 10 + tmp % 10
tmp = tmp // 10
return True if reverse_x == x else False
if __name__ == '__main__':
result = Solution().isPalindrome(1)
print(result) |
f1faf4010a554b17696fe9aaa28c217c5fe3847a | blackwings001/algorithm | /leetcode/51-100/_54_spiralOrder.py | 1,681 | 3.65625 | 4 | class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
if matrix == []:
return result
i = 0 # 第几圈,每圈的起点是matrix[i][i]
cur_row = len(matrix) # 第i圈的行数
cur_col = len(matrix[0]) # 第i圈的列数
while True:
# 定位该圈四个点的横纵坐标, 只需要对角两个点的坐标即可
row1 = i
row2 = i + cur_row - 1
col1 = i
col2 = i + cur_col - 1
if cur_row >= 2 and cur_col >= 2:
result.extend([matrix[row1][j] for j in range(col1, col2)]) # 使用列表表达式添加元素,matrix[row1:row2][col1]这种方式是错的
result.extend([matrix[i][col2] for i in range(row1, row2)])
result.extend([matrix[row2][j] for j in range(col2, col1, -1)])
result.extend([matrix[i][col1] for i in range(row2, row1, -1)])
cur_row -= 2
cur_col -= 2
i += 1
continue
elif cur_col == 0 or cur_row == 0:
return result
elif cur_row == 1:
# 只有一行的情况
result.extend([matrix[row1][j] for j in range(col1, col2 + 1)])
elif cur_col == 1:
# 只有一列的情况
result.extend([matrix[i][col2] for i in range(row1, row2 + 1)])
return result
if __name__ == '__main__':
solution = Solution()
result = solution.spiralOrder([[3],[2]])
print(result) |
4831797afb0eab49191a996103e686620e6d7dbf | blackwings001/algorithm | /leetcode/1-50/_7_reverse.py | 753 | 3.890625 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
reverse_x = self.reverse_positive(x) if x >= 0 else - self.reverse_positive(x)
return reverse_x
def reverse_positive(self, x):
positive = 1 if x >= 0 else 0
x = x if x >= 0 else - x
reverse_x = 0
while x != 0:
reverse_x = 10 * reverse_x + x % 10
x = x // 10
# 判断是否越界
if (positive == 0 and -reverse_x <= - 2 ** 31) or (positive == 1 and reverse_x >= 2 ** 31 - 1):
return 0
return reverse_x
if __name__ == '__main__':
num = -123
reverse_num = Solution().reverse(num)
print(reverse_num) |
7a537e10a6c7edfe749f91ae7e6e36535f2e6c28 | blackwings001/algorithm | /leetcode/1-50/_22_generate_parenthesis.py | 987 | 3.71875 | 4 | class Solution:
def generateParenthesis(self, n):
result = []
ans = ""
l = 0
r = 0
self.parenthesis(n, l, r, ans, result)
return result
def parenthesis(self, n, l, r, ans, result):
"""
:param n: 一共几对括号
:param l: ans中左括号的数量
:param r: ans中右括号的数量
:param ans: 当前的括号组合
:param result: 符合条件的括号组合
:return:
"""
if l == n and r == n:
result.append(ans)
return
else:
# 有两种情况可以添加括号,一种是l<n时,添加左括号,另一种是r<l时,添加右括号
if l < n:
self.parenthesis(n, l+1, r, ans+"(", result)
if r < l:
self.parenthesis(n, l, r+1, ans+")", result)
if __name__ == '__main__':
n = 4
result = Solution().generateParenthesis(n)
print(result) |
7e0233df3a54efebde03d370dd0abec31a01afbe | blackwings001/algorithm | /leetcode/151-200/_167_twoSum.py | 673 | 3.640625 | 4 | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if not numbers:
return []
start = 0
end = len(numbers) - 1
while end > start:
if numbers[start] + numbers[end] > target:
end -= 1
elif numbers[start] + numbers[end] < target:
start += 1
else:
return [start + 1, end + 1]
return []
if __name__ == '__main__':
numbers = [2, 7, 9, 11]
target = 9
res = Solution().twoSum(numbers, target)
print(res)
|
d9efa33507a47f17a078d0e26b82d7c34f9a56b1 | blackwings001/algorithm | /leetcode/101-150/_147_insertionSortList.py | 1,244 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
import sys
dump = ListNode(-sys.maxsize)
dump.next = head
cur = head
while cur.next:
p = cur.next
if p.val < cur.val:
cur.next = p.next
first = dump
while True:
if first.next.val > p.val:
tmp = first.next
first.next = p
p.next = tmp
break
else:
first = first.next
else:
cur = cur.next
return dump.next
if __name__ == '__main__':
head1 = ListNode(5)
head2 = ListNode(2)
head3 = ListNode(3)
head4 = ListNode(1)
head1.next = head2
head2.next = head3
head3.next = head4
head = Solution().insertionSortList(head1)
while head:
print(head.val)
head = head.next
|
4b3ec9c71382f0a099910e075a4c806825bb32b1 | blackwings001/algorithm | /leetcode/101-150/_128_longestConsecutive.py | 927 | 3.53125 | 4 | class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
# 使用哈希表让查找的速度缩短为O(1)
nums = set(nums)
longest_len = 0
# 遍历哈希表中的每一个元素,注意只有连续序列的首元素才会进行第二轮遍历
# 也就是说貌似是一个双重遍历,但实际上每个元素最多被遍历两次,总体的时间复杂度是O(n)
for ele in nums:
if ele - 1 not in nums:
cur_len = 0
while ele in nums:
cur_len += 1
ele += 1
longest_len = max(longest_len, cur_len)
return longest_len
if __name__ == '__main__':
nums = [200, 4, 100, 1, 3, 2]
res = Solution().longestConsecutive(nums)
print(res)
|
32ec08abb779f7fcad9c231c179f16cbb8d593c2 | blackwings001/algorithm | /leetcode/51-100/_85_maximalRectangle.py | 1,412 | 3.515625 | 4 | class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
row = len(matrix)
col = len(matrix[0])
max_area = 0
heights = [0 for _ in range(len(matrix[0]))]
def get_area(heights):
if len(heights) == 0:
return 0
area = 0
stack = [-1] # 存储索引
for i, h in enumerate(heights + [-1]):
# 小心数组越界
if i == len(heights) or h < heights[stack[-1]]:
while stack[-1] != -1 and h < heights[stack[-1]]:
area = max(area, heights[stack[-1]] * (i - stack[-2] - 1))
stack.pop()
stack.append(i)
return area
for i in range(row):
# 计算该行的柱子高度
for j in range(col):
heights[j] = heights[j] + 1 if matrix[i][j] == "1" else 0
# 计算该行的最大面积
max_area = max(max_area, get_area(heights))
return max_area
if __name__ == '__main__':
matrix = [
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
res = Solution().maximalRectangle(matrix)
print(res)
|
619489ae150b0edd3b2a0ca7da3f31d5b5be5bcf | blackwings001/algorithm | /sort_algorithm/binary_search.py | 684 | 3.703125 | 4 | class Solution:
def binary_search(self, nums, target):
"""
返回nums中值为target的最左元素的索引
:param nums:
:param target:
:return:
"""
if nums == []:
return -1
l = 0
r = len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] >= target:
r = mid
else:
l = mid + 1
if nums[l] == target:
return l
else:
return -1
if __name__ == '__main__':
nums = [1,2,3,3,3,3,5,21,21,4]
target = 21
result = Solution().binary_search(nums, target)
print(result) |
d2befa34c8897f0e19a6ecf076ba08aa9d9b8e78 | blackwings001/algorithm | /leetcode/51-100/_89_grayCode.py | 518 | 3.609375 | 4 | class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n == 0:
return [0]
if n == 1:
return [0, 1]
res = [0, 1]
for i in range(1, n):
length = len(res) # 当前列表的长度
for j in range(length):
res.append(length + res[length - j - 1])
return res
if __name__ == '__main__':
n = 3
res = Solution().grayCode(n)
print(res) |
4983ce5f51d32706025dead611acdbfdea92594c | Ramtrap/lpthw | /ex16.py | 1,284 | 4.125 | 4 | from sys import argv
print "ex16.py\n"
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
# target.write(line1)
# target.write("\n")
# target.write(line2)
# target.write("\n")
# target.write(line3)
# target.write("\n")
# Above is too long, this is truncated below
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
print "Now let's take a look at what it says!"
raw_input("Press ENTER to continue:")
print "Here's your file %r:" % filename
print "\n"
target = open(filename, 'r')
print target.read()
print "And finally, we close it."
target.close()
# print "Type the filename again:"
# file_again = raw_input("> ")
#
# txt_again = open(file_again)
#
# print txt_again.read()
# txt.close
# txt_again.close
# print "Your files, %r and %r, have been closed." % (filename, file_again)
|
040472f6d0676e03ab3361c79003f267b46cfb06 | etiennenoel/ctf | /goals/Goal.py | 664 | 3.53125 | 4 | class Goal:
"""Classe abstraite représentant un but"""
def __init__(self, gameInfo):
"""Methode pour initialiser le but"""
self.gameInfo = gameInfo
self.goalString = ""
self.defaultValue = 0
def calculateUtility(self, bot, blackboard):
"""Methode abstraite permettant de calculer l'utilite du but"""
abstract
def numberOfBotWithSameGoal(self, blackboard):
# nombre de bot qui ont déjà cet ordre
numberOfBot = 0
for goal in blackboard.botsAssignGoal.values():
if goal == self.goalString:
numberOfBot += 1
return numberOfBot |
1da3c1521a8a1ba2943d3268762bb8f98f9801fc | jocelynr24/PythonExamples | /Classe/voiture/voiture.py | 657 | 3.578125 | 4 | # Ma classe Voiture
class Voiture:
# Constucteur de la classe voiture
def __init__(self, marque, roues, couleur, vole):
self.marque = marque
self.roues = roues
self.couleur = couleur
self.vole = vole
# Méthode afficherVoiture() pour afficher une description de la voiture
def afficherVoiture(self):
if(self.vole):
texteVoler = "peut voler"
else:
texteVoler = "ne peut pas voler"
descriptionFinale = "Ma voiture de marque", self.marque, "de couleur", self.couleur, "possède", str(self.roues), "roues et", texteVoler
return " ".join(descriptionFinale) |
2700e8c285d5da8be1789928bc8fc91b60e24842 | aditya18/movie_trailer | /inheritance.py | 829 | 3.9375 | 4 | class Parent():
def __init__(self, last_name, eye_color):
print("Parent called")
self.lastname = last_name
self.eyecolor = eye_color
def show_info(self):
print("Last Name = "+self.lastname)
print("Eye Color ="+self.eyecolor)
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
print("Child called")
Parent.__init__(self, last_name, eye_color)
self.number_of_toys = number_of_toys
def show_info(self):
print("Last Name = "+self.lastname)
print("Eye = "+self.eyecolor)
print("Toys = "+str(self.number_of_toys))
billy = Parent("Adi", "blue")
billy.show_info()
rao = Child("Rao", "red", 5)
rao.show_info()
#print(rao.lastname)
#print(rao.number_of_toys)
|
8f6af55a263b766ae2f521702dbc0304f1653336 | christinajoice/begin-set11 | /uppercase.py | 85 | 3.984375 | 4 | str1=input()
str1[1].upper()
for i in str1:
if i==' ':
i+1.upper()
print(str1)
|
ea8daa797fc7f221b09b4580852a67a45e79b8d0 | brunolomba/exercicios_logica | /banco_itau.py | 1,698 | 4.03125 | 4 | # 341 - ITAU
# Tamanha da Agência - 4 dígitos
# Tamanha da conta - 5 dígitos
# Exemplo:
# Agência: 2545
# Conta: 023661
# Para Obter o DV, multiplica-se cada número da Agência e Conta em sua ordenação. Sequências PAR multiplica-se por 1 e ÍMPARES por 2. Se o número encontrado for maior que 9, soma-se as unidades da dezena.
# Conta: AAAACCCCCD
# Peso: 212121212
# Módulo (10) 39/10 = 9 ~ Resto = 9 ~ Dígito = 10 - 9 = 1
# OBS: se o RESTO = 0 ~ o Dígito é 0
# Entradas
agencia = input('Digite a sua Agência.')
conta = input('Digite a sua Conta.')
# Junção e conversão da conta em inteiros
conta_completa = list(agencia + conta)
conta_convertida = [int(valor) for valor in conta_completa]
# Verificação e isolamento do digíto
digito_removido = []
if len(conta_convertida) == 10:
digito_removido = conta_convertida.pop(9)
# Multiplicação dos valores PARES
for i in range(len(conta_convertida)):
if i % 2 == 0:
conta_convertida[i] = conta_convertida[i] * 2
# Conversão dos números de 2 digítos
soma_unidade = 0
for i, numero in enumerate(conta_convertida):
if numero > 9:
for unidade in str(numero):
soma_unidade += int(unidade)
conta_convertida[i] = soma_unidade
# Cálculo do digíto
soma = sum(conta_convertida)
resto = soma % 10
digito = 10 - resto
# Verificação do digíto, se a pessoa já tiver passado ele
if digito == digito_removido:
print('O digito da conta está correto')
print(f'Os numeros conta_convertida é: {conta_convertida}, a soma deles é: {soma} e o digíto é :{digito}.')
print(f'O número da conta é ag / conta: {agencia} / {conta[:-1]}-{digito}')
print('FIM DO PROGRAMA') |
b4b8da6dd62e73b25cd334af6948c7ff2d6f582c | brunolomba/exercicios_logica | /Estrutura condicional/multiplos.py | 171 | 4.03125 | 4 | x = int(input('Digite um número'))
y = int(input('Digite outro número'))
if x % y == 0 or y % x == 0:
print('São multiplos')
else:
print('Não são multiplos') |
46ac2b687530ac76a3d5da828aec3aaed74da0a0 | brunolomba/exercicios_logica | /Matrizes/matriz_geral_pedro.py | 963 | 3.984375 | 4 | N = int(input("Qual é a ordem da matriz? "))
mat = [[0 for x in range(N)]for x in range(N)]
for i in range(0,N):
for j in range(0,N):
mat[i][j] = int(input(f"Elemento [{i},{j}]: "))
SomaPositivos = 0
for i in range(0,N):
for j in range(0,N):
if mat[i][j] > 0:
SomaPositivos = SomaPositivos + mat[i][j]
print(f"A soma dos positivos é {SomaPositivos}")
print()
Linha = int(input("Escolha uma linha: "))
for j in range(0,N):
print(f"{mat[Linha][j]} ", end="")
print()
Coluna = int(input("Escolha uma coluna: "))
for i in range(0,N):
print(f"{mat[i][Coluna]} ", end="")
print()
print("Diagonal Principal")
for i in range(0,N):
for j in range(0,N):
if i == j:
print(f"{mat[i][j]} ", end="")
print()
print("Matriz Alterada")
for i in range(0,N):
for j in range(0,N):
if mat[i][j] < 0:
mat[i][j] = mat[i][j] * mat[i][j]
print(f"{mat[i][j]} ", end="")
print() |
b8c35c6bd26826fe250b5ed42d649fbf2af00dba | brunolomba/exercicios_logica | /Vetores/subtracao_vetores.py | 733 | 3.984375 | 4 | print('#' * 120)
print('Programa que recebe 2 vetores A e B com 5 números inteiros do usuário e soma os valores em um vetor C')
print('#' * 120)
quantidade_elementos = int(input('Digite a quantidade de elementos no vetor.'))
vetor_a = [0 for x in range(quantidade_elementos)]
vetor_b = []
vetor_soma = [0 for x in range(quantidade_elementos)]
for i in range(quantidade_elementos):
vetor_a[i] = int(input('Digite um valor para o vetor A:'))
for i in range(quantidade_elementos):
vetor_b.append(int(input('Digite um valor para o vetor B:')))
for i in range(quantidade_elementos):
vetor_soma[i] = vetor_a[i] - vetor_b[i]
print(f'A subtração dos {vetor_a} com o {vetor_b} é: {vetor_soma}.')
print('Fim do programa') |
f441e2ebbcff6098d0a3e752550f770eb13ed708 | brunolomba/exercicios_logica | /banco_itau_funcao.py | 2,645 | 4.34375 | 4 | # 341 - ITAU
# Tamanha da Agência - 4 dígitos
# Tamanha da conta - 5 dígitos
# Exemplo:
# Agência: 2545
# Conta: 023661
# Para Obter o DV, multiplica-se cada número da Agência e Conta em sua ordenação. Sequências PAR multiplica-se por 1 e ÍMPARES por 2. Se o número encontrado for maior que 9, soma-se as unidades da dezena.
# Conta: AAAACCCCCD
# Peso: 212121212
# Módulo (10) 39/10 = 9 ~ Resto = 9 ~ Dígito = 10 - 9 = 1
# OBS: se o RESTO = 0 ~ o Dígito é 0
def calcular_digito_correto():
# Entradas
agencia = input('Digite a sua Agência.')
conta = input('Digite a sua Conta.')
# Junção e conversão da conta em inteiros.
conta_completa = list(agencia + conta)
conta_convertida = [int(valor) for valor in conta_completa]
# Isolamento do digíto.
digito_removido = remocao_digito(conta_convertida)
# Atualização da conta.
conta_convertida_sem_digito = conta_convertida
# Multiplicação por 2 dos valores PARES.
conta_multiplicada = multiplicao_valores(conta_convertida_sem_digito)
# Conversão dos números de 2 digítos.
conta_multiplicada_sem_2_digitos = conversao_numero_2_digitos(conta_multiplicada)
# Cálculo do digíto.
digito = calculo_digito(conta_multiplicada_sem_2_digitos)
# Verificação do digíto.
if digito == digito_removido:
print(f'O digito da conta está correto, é: {digito}')
#Exibição da verificação do digíto e da conta completa.
exibicao(agencia, conta, digito)
# Funções
def remocao_digito(conta_convertida):
digito_removido = []
if len(conta_convertida) == 10:
digito_removido = conta_convertida.pop(9)
return digito_removido
def multiplicao_valores(conta_convertida_sem_digito):
for i in range(len(conta_convertida_sem_digito)):
if i % 2 == 0:
conta_convertida_sem_digito[i] = conta_convertida_sem_digito[i] * 2
return conta_convertida_sem_digito
def conversao_numero_2_digitos(conta_multiplicada):
soma_unidade = 0
for i, numero in enumerate(conta_multiplicada):
if numero > 9:
for unidade in str(numero):
soma_unidade += int(unidade)
conta_multiplicada[i] = soma_unidade
return conta_multiplicada
def calculo_digito(conta_multiplicada_sem_2_digitos):
soma = sum(conta_multiplicada_sem_2_digitos)
resto = soma % 10
digito = 10 - resto
return digito
def exibicao(agencia, conta, digito):
print(f'O número da conta é ag {agencia} / conta: {conta[:-1]}-{digito}')
print('FIM DO PROGRAMA')
if __name__ == '__main__':
calcular_digito_correto() |
b5ce51ae7333dd52603e1a391d78a62ab98834b8 | brunolomba/exercicios_logica | /Estruturas repetitivas/quadrante.py | 443 | 4.0625 | 4 | x = int(input('Digite a coordenada "X"'))
y = int(input('Digite a coordenada "Y"'))
while x != 0 and y != 0:
if x > 0 and y > 0:
print('Coordenada Q1')
elif x < 0 and y > 0:
print('Coordenada Q2')
elif x < 0 and y < 0:
print('Coordenada Q3')
else:
print('Coordenada Q4')
x = int(input('Digite a coordenada "X"'))
y = int(input('Digite a coordenada "Y"'))
print('Fim do programa!') |
862a1afa23038173122c1da925120046959b11b2 | brunolomba/exercicios_logica | /Estrutura condicional/lanchonete.py | 434 | 3.703125 | 4 | codigo = int(input('Digite o código do produto'))
quantidade = int(input('Digite a quantidade de produtos'))
valor_pago = 0
if codigo == 1:
valor_pago = 5 * quantidade
elif codigo == 2:
valor_pago = 3.5 * quantidade
elif codigo == 3:
valor_pago = 4.8 * quantidade
elif codigo == 4:
valor_pago = 8.9 * quantidade
elif codigo == 5:
valor_pago = 7.32 * quantidade
print(f'O valor a ser pago é {valor_pago} reais') |
1a6957707b3291a2158b3449f164e9d9a7b3a940 | brunolomba/exercicios_logica | /contagem_strings.py | 757 | 3.640625 | 4 | print('#' * 120)
print('Programa que conta quantas letras tem até 1000')
print('#' * 120)
zero = 'zero'
vetor_1 = ['um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove']
vetor_2 = ['dez', 'onze', 'doze', 'treze', 'quatorze', 'quize', 'dezesseis', 'dezessete', 'dezoito', 'dezenove']
vetor_3 = ['trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta', 'oitenta', 'noventa']
vetor_4 = ['cem', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos', 'seissentos', 'setecentos', 'oitocentos', 'novecentos']
soma = zero + ''
soma_total = 0
for i in vetor_1:
soma += i * 10
for i in vetor_2:
soma += i * 10
for i in vetor_3:
soma += i * 10
for i in vetor_3:
soma += i
soma_total += len(soma)
print(soma)
print(soma_total) |
f6852400f5e8b2a0e35ebf7928a50d0cd37b42d3 | brunolomba/exercicios_logica | /Estrutura condicional/glicose.py | 172 | 3.625 | 4 | glicose = float(input('Digite o valor da sua glicose em mg/dl'))
if glicose < 100:
print('Normal')
elif glicose < 140:
print('Elevado')
else:
print('Diabetes') |
4831f52a0c18c7c349d3a479db10be7a6631bb73 | culvin2/Sequential-Search-Python | /sequential search.py | 364 | 3.703125 | 4 | testlist=[1,2,32,44,88,13,0]
a = 1
b = 32
def SequentialSearh(testlist,a):
for i in range(0,len(testlist)-1,1) :
if testlist[i]== a :
print("Found in index : ")
return i
break
else:
print("Sorry, not found!")
return False
print(SequentialSearh(testlist,a))
print(SequentialSearh(testlist,b))
|
b2b35fe6e2a3a079b2f296538fe73528b5d52eb1 | txj44522/Phys5311TJ | /hw03/sciprog3.py | 4,221 | 3.734375 | 4 | """
This script will open DST file from KYPTO, parse the data, and load the hourly DST data into a one-dimensional
numpy array and the date-time objects into 1-D array; both arrays will print to screen.
It will also print to screen min, max, mean, median, and std of hourly DST data.
Next, import the module:
#>>>import sciprog2
Author: Tre'Shunda James
"""
def read_dst(infile, debug=False):
'''
This functionopen DST file from KYPTO, parse the data, and load the hourly DST data into a one-dimensional
numpy array and the date-time objects into 1-D array; both arrays will print to screen.
It will also print to screen min, max, mean, median, and std of hourly DST data.
Usage:
#>>>data = read_dst('some_file_name.dat')
The returned value is a dictionary of values read from the file.
The *debug* kwarg, if set to **True**, will create debug print outs.
This function serves as a simple example; in real-life, creating a class
that knows how to read, write, and plot these types of files is way more
useful!
'''
# Import datetime package
import datetime as dt
# Open DST file
f = open('Dst_July2000.dat')
# Read the lines in the file and assign them to a variable called lines
lines = f.readlines()
# Close the file
f.close()
#print(lines) to check the data is opened, read and assigned as expected
nLines = len(lines)
#data2 = {} # empty dictionary.
#data2['time'] = np.zeros(nLines, dtype='object')
#data2['dst'] = np.zeros(nLines)
# Empty array for the DST values
data = []
# Empty array for list of date-time strings
time = []
# Empty array for converted list of date-time objects (Bonus)
date_time = []
## Planning for parsing the DST data
#For each line:
# Skip first 20 characters and stop before the last 4 characters and save it as l2
# For character in l2:
# Split l2 every 4 characters
# Make string to int and save as data2
# Append data2 to data array
# For loop to go through each line in file
for j,l in enumerate(lines):
l2 = l[20:117] # Hourly DST data starts at character 20 and ends with character 116 for each line assigned
# to list l2
l1 = l[3:17] # String of characters that include the date and time for each line assigned to list l1
n = 4 # Number of characters used for each hourly DST value
# for-loop to parse l2 every four characters
for i in range(0, len(l2)-1, n):
data2 = int(l2[i:i+n]) # Every set of four characters is converted into an integer and assigned to data2
data.append(data2) # data2 is added to the empty data array
#data2['dst'][j] = data4
# now for-loop to increment the hour by 1 from 0-23 (24 hours).
for k in range(0, 24, 1):
data3 = (l1[11:13]+l1[1:3]+l1[2:4]+l1[5:7]+str(k)) # Stringing together only the parts that contribute to
# date-time. First two digits of year+ second two
# digits of year+month+date+ str(hour) and assign to data3
time.append(data3) # data3 is added to empty time array
# Now for-loop to convert time from a list of string of numbers into a list in datetime format
for item in time: # For every string in the time array
date= dt.datetime.strptime(item, '%Y%m%d%H') # Use the datetime.strptime function on string in time array
# that has the format YYYYMMDDH to convert it to date-time
# object. Assign date a string of date-time objects.
#data2['time'][j] = dt.datetime.strptime(data3, '%Y%m%d%H')
date_time.append(date) # date is added to empty date_time array
data2 = {} # empty dictionary.
data2['time'] = date_time # add the date_time array to data2 dictionary under keyword time
data2['dst'] = data # add the data array to data2 dictionary under keyword time
return(data2)
|
51f28609cb8f18378556bc6ada002c97432536cf | nahalkk/learning_python | /stats.py | 981 | 3.828125 | 4 | #!/usr/bin/env python3
from math import sqrt
import fileinput
# Write a program that computes typical stats
# Count, Min, Max, Mean, Std. Dev, Median
# No, you cannot import any other modules!
scores = []
for line in fileinput.input():
if line.startswith('#'): continue
scores.append(float(line))
mean = sum(scores) / len(scores)
count = len(scores)
val = sum([(i - mean) ** 2 for i in scores]) / len(scores)
stddev = sqrt(val)
scores.sort()
minimum = scores[0]
maximum = scores[-1]
if len(scores) % 2 == 0:
median1 = scores[len(scores) // 2]
median2 = scores[len(scores) // 2 - 1]
median = (median1 + median2 ) / 2
else:
median = scores[len(scores) // 2]
#ouput
print(f'Count: {count}')
print(f'Minimum: {minimum}')
print(f'Maximum: {maximum}')
print(f'Mean: {mean}')
print(f'Std. dev: {stddev:.3f}')
print(f'Median: {median}')
"""
python3 stats.py numbers.txt
Count: 10
Minimum: -1.0
Maximum: 256.0
Mean: 29.147789999999997
Std. dev: 75.777
Median 2.35914
"""
|
87633563b026a250ff45f402a4162c5d996d6934 | crb8v2/3130algs_projec1 | /fibTiming.py | 954 | 4.0625 | 4 | from timeit import default_timer as timer
def fib_recursion(n):
if n == 0:
return 0
if n == 1:
return 1
return fib_recursion(n-1) + fib_recursion(n-2)
def fib_iteration(n):
if n == 0:
return 0
if n == 1:
return 1
minus_two = 0
minus_one = 1
for x in range(1, n):
result = minus_two + minus_one
minus_two = minus_one
minus_one = result
return result
def fib_iteration_buffer(n):
if n == 0:
return 0
if n == 1:
return 1
minus_two = 0
minus_one = 1
for x in range(1, n):
result = minus_two + minus_one
minus_two = minus_one
minus_one = result
return result
# recursion
print("RECURSIVE")
start = timer()
fib_recursion(35)
end = timer()
print (" time:",(end - start))
# iteration
print("ITERATIVE")
start1 = timer()
fib_iteration(35)
end1 = timer()
print (" time:",(end1 - start1)) |
266ab42bab539d38658df119958d615348fae38d | nadhiyap/pr1 | /sqr.py | 321 | 3.765625 | 4 | ax=int(input("enter a-x"))
ay=int(input("enter a-y"))
bx=int(input("enter b-x"))
by=int(input("enter b-y"))
cx=int(input("enter c-x"))
cy=int(input("enter c-y"))
dx=int(input("enter d-x"))
dy=int(input("enter d-y"))
if ax==ay and ay==bx and by==cx and cx==cy and cy==dx and dy==ax:
print("yes")
else:
print("no")
|
38a596998fe2dd4f89738c1dfc15617b83c90339 | dakelkar/pccc_general_info | /add_update_sql.py | 2,454 | 3.546875 | 4 | def update_single(conn, cursor, table, column, file_number, var):
# update a single column in a sql db. Key is file_number.
sql_update = "UPDATE " + table + " SET " + column + "= ? WHERE File_number = '" + file_number + "'"
cursor.execute(sql_update, [var])
conn.commit()
def insert(conn, cursor, table, columns, data):
# insert data in multiple cols in a sql db. adds a new row
col_number = len(data)
place_holder = ["?"] * col_number
place_str = ",".join(place_holder)
sql_insert = "INSERT INTO " + table + "(" + columns + ") VALUES (" + place_str + ")"
cursor.execute(sql_insert, data)
conn.commit()
def insert_file_number (conn, cursor, file_number):
# insert data in multiple cols in a sql db. adds a new row
sql_insert = "INSERT INTO Patient_Information_History(File_number) VALUES (?)", file_number
cursor.execute(sql_insert, data)
conn.commit()
def update_multiple(conn, cursor, table, columns, file_number, data):
# update multiple columns in a sql db. Key is file_number.
col_number = len(data)
for index in range(0, col_number):
sql_update = "UPDATE " + table + " SET " + columns[index] + "= ? WHERE File_number = '" + file_number + "'"
var = data[index]
cursor.execute(sql_update, [var])
conn.commit()
def add_columns(cursor, table, columns):
col_number = len(columns)
for index in range(0, col_number):
sql_add = "ALTER TABLE " + table + " ADD " + columns[index]
cursor.execute(sql_add)
def review_input (file_number, columns, data):
from ask_y_n_statement import ask_y_n
col_number = len (data)
print ("Entries for database are as follows : ")
for index in range (0, col_number):
print (columns[index] +": " + data[index])
ans = ask_y_n("Are entries for file "+ file_number+ " correct ?", True, False)
return ans
def display_data (cursor, table, file_number, columns, section_number):
import ask_y_n_statement
section = ", ".join(columns)
sql = "SELECT "+section+" FROM "+table+" WHERE File_number = ?"
cursor.execute(sql, (file_number,))
data = cursor.fetchall()
data_list = list(data[0])
col_number = len(columns)
print("Available data in database")
for index in range ((section_number -1), col_number):
print (columns[index] +": " + data_list[index])
enter = ask_y_n_statement.ask_y_n("Enter "+ section_name)
return enter
|
1fb110f434a06cf6714d8e9c89e3d6988d425b05 | battlesysadmin/pr4e | /pr4e-final-2.py | 105 | 3.6875 | 4 | abc = None
lst = [1, 2, 3]
for val in lst:
if abc == None or val > abc:
abc = val
print abc
|
2cb6dee85b05b1b27323275f6d1db88c9522f086 | Li-Pro/Word-Search | /diclib/__init__.py | 893 | 3.578125 | 4 | """
Author: Li-Pro 2020
The main file of dictionary library.
"""
import string
import requests
from bs4 import BeautifulSoup
""" The dictionaries """
from .Dictionary import OxfordLearners
from .Dictionary import Urban
from .Dictionary import Cambridge
__all__ = ['OxfordLearners', 'Urban', 'Cambridge', 'searchWord', 'getWordPage']
# The extensible dictionary list!
dic_list = {'oed': OxfordLearners.DIC_OBJ,
'urb': Urban.DIC_OBJ,
'camb': Cambridge.DIC_OBJ}
def getWordPage(key, dic_obj):
""" Send request towards the online dictionary. """
return dic_obj.requestWord(key)
def searchWord(key, dicname='camb'):
"""
Provide a search utility.
key -- the word
dicname -- the dictionary name (as in dic_list)
"""
if not dicname in dic_list:
dicname = 'camb'
dic_obj = dic_list[dicname]
rep = getWordPage(key, dic_obj)
return dic_obj.parse(BeautifulSoup(rep, 'lxml'), key) |
f225e2275c88d121e1bc0f268325b1dddf9e0d5a | bridgecrew-perf7/Heroku_NLP_Deployment | /Spam-Ham-Classification-NLP.py | 1,134 | 3.5 | 4 | # # SMS CLASSIFICATION USING NLP
# importing necessary libraries
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
# Loading the input dataset
dframe = pd.read_csv(r'./sms-dataset.csv')
# Data Cleaning
# Dropping unnecessary columns
dframe.drop(columns= ['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1, inplace=True)
def convert_class_to_num(text):
if text == 'ham':
return 1
else:
return 0
# Converting the class names to numerics
dframe['class']=dframe['class'].apply(convert_class_to_num)
# Segregating the output from input features
X = dframe['message']
y = dframe['class']
# Bag of Words Calculation
cv = CountVectorizer()
X = cv.fit_transform(X)
# Splitting the data into training and test dataset
X_train,X_test,y_train,y_test = train_test_split(X,y, test_size=0.3,random_state = 42)
# Model building and training
nlp_model = MultinomialNB()
nlp_model.fit(X_train,y_train)
# Serializing the model
pickle.dump(nlp_model,open('nlp_model.pkl','wb')) |
6a90e05a2712f070fb62e16a90c2fa4fd9424ed1 | m-119/PY111-2020-1 | /Tests/c1_test_fact.py | 1,019 | 3.5625 | 4 | import unittest
import math
import Tasks.c1_fact as fact
class MyTestCase(unittest.TestCase):
def test_fact_recursive(self):
self.assertEqual(math.factorial(7), fact.factorial_recursive(7), msg="Something gonna wrong...")
def test_fact_rec_exc(self):
with self.assertRaises(ValueError, msg="ValueError should be here..."):
fact.factorial_recursive(-11231)
def test_fact_rec_zero(self):
self.assertEqual(math.factorial(-0), fact.factorial_recursive(0), msg="Something gonna wrong...")
def test_fact_iterative(self):
self.assertEqual(math.factorial(12), fact.factorial_iterative(12), msg="I think there's a mistake :)")
def test_fact_iter_exc(self):
with self.assertRaises(ValueError, msg="ValueError should be here..."):
fact.factorial_iterative(-1121)
def test_fact_iter_zero(self):
self.assertEqual(1, fact.factorial_iterative(0), msg="I think there's a mistake :)")
if __name__ == '__main__':
unittest.main()
|
c184bb6e001926857882bb723ce7e6ee1370633a | BigSamu-Coding-Dojo-Python-Assignments/User_with_Bank_Accounts | /user_with_bank_accounts.py | 4,231 | 3.875 | 4 | import random
import string
class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
self.account_number = ''.join(random.choices(string.digits,k = 10))
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance>=amount:
self.balance -= amount
else:
self.balance -= 5
print("Insufficient funds: Charging a $5 fee")
return self
def display_account_info(self,name):
print(f"Name: {name} Account: {self.account_number} Balance: {self.balance}")
return self
def yield_interest(self):
if self.balance > 0:
self.balance = self.balance*(1+self.int_rate)
else:
print("Account overdrwan: No interests given")
return self
class User: # here's what we have so far
# Constructor
def __init__(self, name, email, number_of_accounts=1,init_rate=0,balance=0):
self.name = name
self.email = email
self.number_of_accounts = number_of_accounts
self.account = []
for i in range(number_of_accounts):
self.account.append(BankAccount(init_rate,balance))
# adding the deposit method
def make_deposit(self, amount, accountNumber):
self.account[self.account_index(accountNumber)].deposit(amount)
return self
# adding the withdrawal method
def make_withdrawal(self, amount, accountNumber):
self.account[self.account_index(accountNumber)].withdraw(amount)
return self
# adding the display method
def display_user_balance(self,accountNumber):
self.account[self.account_index(accountNumber)].display_account_info(self.name)
return self
def transfer_money(self, amount, account_number_origin,user_recipient,account_number_destinatary):
self.make_withdrawal(amount, account_number_origin)
user_recipient.make_deposit(amount, account_number_destinatary)
print(f"Origin: {self.name} - Destinatary: {self.name} - Amount: {amount}")
print(f"Origin Account: {account_number_origin} - Destinatary_Account: {account_number_destinatary}")
return self
def account_index(self,accountNumber):
for i in range(self.number_of_accounts):
if self.account[i].account_number == accountNumber:
return i
# Create Two users, both of them with two accounts
guido = User("Guido van Rossum", "guido@python.com",number_of_accounts=2,init_rate=0,balance=0)
monty = User("Monty Python", "monty@python.com",number_of_accounts=2,init_rate=0,balance=0)
# We extract the account numbers of both users
#GUIDO INFO
print("\n","GUIDO INFO\n")
# Account Numbers of Guido
guido_account_number_1 = guido.account[0].account_number
guido_account_number_2 = guido.account[1].account_number
# We make a deposit of 100 and 200 on accounts 1 and 2 of Guido
guido.account[guido.account_index(guido_account_number_1)].deposit(100)
guido.account[guido.account_index(guido_account_number_2)].deposit(200)
# We get the status of accounts 1 and 2 of Guido
guido.display_user_balance(guido_account_number_1)
guido.display_user_balance(guido_account_number_2)
print("\n","*"*100,"\n")
#MONTI INFO
print("MONTI INFO\n")
# Account Numbers of Monty
monty_account_number_1 = monty.account[0].account_number
monty_account_number_2 = monty.account[1].account_number
# We make a deposit of 50 and 80 on accounts 1 and 2 of Monty
monty.account[monty.account_index(monty_account_number_1)].deposit(50)
monty.account[monty.account_index(monty_account_number_2)].deposit(80)
# We get the status of accounts 1 and 2 of Monty
monty.display_user_balance(monty_account_number_1)
monty.display_user_balance(monty_account_number_2)
print("\n","*"*100,"\n")
#TRANSFERENCES
print("TRANSFERS INFO\n")
guido.transfer_money(40,guido_account_number_1,monty,monty_account_number_1)
guido.display_user_balance(guido_account_number_1)
guido.display_user_balance(guido_account_number_2)
monty.display_user_balance(monty_account_number_1)
monty.display_user_balance(monty_account_number_2)
print("\n","*"*100,"\n") |
b458910d53b2e63d4732adff493764bcc6ddc11d | Magorx/ray_tracing | /vector.py | 2,836 | 3.765625 | 4 | from math import sqrt, sin, cos
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return Vector(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
def len(self):
return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normal(self):
length = self.len()
if length == 0:
return Vector(0, 0, 0)
else:
return Vector(self.x / length, self.y / length, self.z / length)
def proection(self, other):
return self.normal() * self.dot(other.normal()) * other.len()
def to_ints(self):
return Vector(int(self.x), int(self.y), int(self.z))
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __mul__(self, other):
if isinstance(other, Vector):
return Vector(self.x * other.x, self.y * other.y, self.z * other.z)
else:
assert type(other) == float or type(other) == int
return Vector(self.x * other, self.y * other, self.z * other)
def __truediv__(self, other):
if isinstance(other, Vector):
return Vector(self.x / other.x, self.y / other.y, self.z / other.z)
else:
assert type(other) == float or type(other) == int
return Vector(self.x / other, self.y / other, self.z / other)
def __pow__(self, other):
return Vector(self.x ** other, self.y ** other, self.z ** other)
def __repr__(self):
return '{' + '{}, {}, {}'.format(self.x, self.y, self.z) + '}'
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
def __lt__(self, other):
return self.x < other.x or self.y < other.y or self.z < other.z
def rotx(vec, ang):
x = vec.x
y = vec.y * cos(ang) - vec.z * sin(ang)
z = vec.y * sin(ang) + vec.z * cos(ang)
return Vector(x, y, z)
def roty(vec, ang):
x = vec.x * cos(ang) + vec.z * sin(ang)
y = vec.y
z = vec.z * cos(ang) - vec.x * sin(ang)
return Vector(x, y, z)
def rotz(vec, ang):
x = vec.x * cos(ang) - vec.y * sin(ang)
y = vec.y * cos(ang) - vec.x * sin(ang)
z = vec.z
return Vector(x, y, z)
def rot(vec, dx=0, dy=0, dz=0, rotation=()):
if rotation:
dx = rotation[0]
dy = rotation[1]
dz = rotation[2]
if dx == 0 and dy == 0 and dz == 0:
return vec * 1
return rotz(roty(rotx(vec, dx), dy), dz)
|
2b7a236fee6cd3332a3d35e8356e0a206253193c | FOSSRIT/knowledge | /knowledge/model/vertical/dictlike.py | 4,121 | 3.8125 | 4 | """Mapping a vertical table as a dictionary.
This example illustrates accessing and modifying a "vertical" (or
"properties", or pivoted) table via a dict-like interface. These are tables
that store free-form object properties as rows instead of columns. For
example, instead of::
# A regular ("horizontal") table has columns for 'species' and 'size'
Table('animal', metadata,
Column('id', Integer, primary_key=True),
Column('species', Unicode),
Column('size', Unicode))
A vertical table models this as two tables: one table for the base or parent
entity, and another related table holding key/value pairs::
Table('animal', metadata,
Column('id', Integer, primary_key=True))
# The properties table will have one row for a 'species' value, and
# another row for the 'size' value.
Table('properties', metadata
Column('animal_id', Integer, ForeignKey('animal.id'),
primary_key=True),
Column('key', UnicodeText),
Column('value', UnicodeText))
Because the key/value pairs in a vertical scheme are not fixed in advance,
accessing them like a Python dict can be very convenient. The example below
can be used with many common vertical schemas as-is or with minor adaptations.
"""
class VerticalProperty(object):
"""A key/value pair.
This class models rows in the vertical table.
"""
def __init__(self, key, value):
self.key = key
self.value = value
def __repr__(self):
return '<%s %r=%r>' % (self.__class__.__name__, self.key, self.value)
class VerticalPropertyDictMixin(object):
"""Adds obj[key] access to a mapped class.
This is a mixin class. It can be inherited from directly, or included
with multiple inheritence.
Classes using this mixin must define two class properties::
_property_type:
The mapped type of the vertical key/value pair instances. Will be
invoked with two positional arugments: key, value
_property_mapping:
A string, the name of the Python attribute holding a dict-based
relation of _property_type instances.
Using the VerticalProperty class above as an example,::
class MyObj(VerticalPropertyDictMixin):
_property_type = VerticalProperty
_property_mapping = 'props'
mapper(MyObj, sometable, properties={
'props': relation(VerticalProperty,
collection_class=attribute_mapped_collection('key'))})
Dict-like access to MyObj is proxied through to the 'props' relation::
myobj['key'] = 'value'
# ...is shorthand for:
myobj.props['key'] = VerticalProperty('key', 'value')
myobj['key'] = 'updated value']
# ...is shorthand for:
myobj.props['key'].value = 'updated value'
print myobj['key']
# ...is shorthand for:
print myobj.props['key'].value
"""
_property_type = VerticalProperty
_property_mapping = None
__map = property(lambda self: getattr(self, self._property_mapping))
def __getitem__(self, key):
return self.__map[key].value
def __getattr__(self, key):
return self.__map[key].value
def get(self, key, default=None):
value = self.__map.get(key, default)
if hasattr(value, 'value'):
return value.value
return value
def __setitem__(self, key, value):
property = self.__map.get(key, None)
if property is None:
self.__map[key] = self._property_type(key, value)
else:
property.value = value
def __delitem__(self, key):
del self.__map[key]
def __delattr__(self, key):
del self.__map[key]
def __contains__(self, key):
return key in self.__map
# Implement other dict methods to taste. Here are some examples:
def keys(self):
return self.__map.keys()
def values(self):
return [prop.value for prop in self.__map.values()]
def items(self):
return [(key, prop.value) for key, prop in self.__map.items()]
def __iter__(self):
return iter(self.keys())
|
ca47efef3c0309c33c25db8967bf9185793adac0 | muzhen321/FPIR17 | /pir_h1.py | 2,920 | 3.53125 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Rank sentences based on cosine similarity and a query."""
from argparse import ArgumentParser
from collections import Counter
import numpy as np
def get_sentences(file_path):
"""Return a list of sentences from a file."""
with open(file_path, encoding='utf-8') as hfile:
return hfile.read().splitlines()
def get_top_k_words(sentences, k):
"""Return the k most frequent words as a list."""
words = []
for sentence in sentences:
words.extend(sentence.split())
#调用了库文件 Counter
return [word for word, _ in Counter(words).most_common(k)]
def encode(sentence, vocabulary):
"""Return a vector encoding the sentence."""
words = Counter(sentence.split())
vector = [words.get(token, 0) for token in vocabulary]
return np.asarray(vector)
def get_top_l_sentences(sentences, query, vocabulary, l):
"""
For every sentence in "sentences", calculate the similarity to the query.
Sort the sentences by their similarities to the query.
Return the top-l most similar sentences as a list of tuples of the form
(similarity, sentence).
"""
encoded_query = encode(query, vocabulary)
similarities = []
for sentence in sentences:
encoded_sentence = encode(sentence, vocabulary)
sim = cosine_sim(encoded_sentence, encoded_query)
similarities.append((sim, sentence))
# sort by similarities, descending, and keep the top-l ones
return sorted(similarities, key=lambda x: x[0], reverse=True)[:l]
def cosine_sim(u, v):
"""Return the cosine similarity of u and v."""
return np.dot(u, v) / np.linalg.norm(u) / np.linalg.norm(v)
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('INPUT_FILE', help='An input file containing sentences, one per line')
arg_parser.add_argument('QUERY', help='The query sentence')
arg_parser.add_argument('-k', type=int, default=1000,
help='How many of the most frequent words to consider')
arg_parser.add_argument('-l', type=int, default=10, help='How many sentences to return')
args = arg_parser.parse_args()
sentences = get_sentences(args.INPUT_FILE)
top_k_words = get_top_k_words(sentences, args.k)
query = args.QUERY.lower()
print('using vocabulary: {}\n'.format(top_k_words))
print('using query: {}\n'.format(query))
# suppress numpy's "divide by 0" warning.
# this is fine since we consider a zero-vector to be dissimilar to other vectors
with np.errstate(invalid='ignore'):
result = get_top_l_sentences(sentences, query, top_k_words, args.l)
print('result:')
for sim, sentence in result:
print('{:.5f}\t{}'.format(sim, sentence))
if __name__ == '__main__':
main()
|
8d38d519cc851e7e8203fcf9d057d6f2404fe07a | maxlauhi/cspy3 | /1_7_2_mu_rec.py | 246 | 4.40625 | 4 | """determine whether a number is odd or even by mutual recursion"""
def is_even(n):
if n == 0:
return True
else:
return is_odd(n-1)
def is_odd(n):
if n == 0:
return False
else:
return is_even(n-1)
|
16b98888bf8a11bd18c57bca1c4ae572e02b9472 | maxlauhi/cspy3 | /2_3_2_Sequence.py | 431 | 3.84375 | 4 | def count(s, value):
"""Count the number of occurrences of value in sequence s.
"""
total = 0
for elem in s:
if elem == value:
total = total + 1
return total
"""
structure of FOR statment:
for <name> in <expression>:
<suite>
* <expression> must yield an iterable value.
* Bind <name> to that value in the current frame.
* Excute the <suite> statment each loop.
"""
|
f8045a971b7f68e8dab65223d9478a770eeb9638 | alon-strik/localaws | /classes/class_variables.py | 742 | 3.625 | 4 | ## Logicly group a data and function for reuse
## attributes and methods assosiated with calss
# this is a class
class Employee:
## this is a constrctore or init method
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
# this is class instance
emp_1 = Employee('Alon','Strikovksy',5000)
emp_2 = Employee('Chen','Elakbez',10000)
# print (emp_1.email)
# print (emp_2.email)
#action - call a method
print(emp_1.fullname())
print(emp_2.fullname())
# This is the same a above
print(Employee.fullname(emp_1))
print(Employee.fullname(emp_2)) |
ef3e1712df8cf28034c6ab2fc8d3fd46b4683783 | shivsun/pythonappsources | /Exercises/Integers/accessing elements in the list with messages.py | 1,294 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 21:09:17 2020
@author: bpoli
"""
#Accessing Elements in a List
#Lists are ordered collections, so you can access any element in a list by
#telling Python the position, or index, of the item desired. To access an element
#in a list, write the name of the list followed by the index of the item
#enclosed in square brackets.
#For example, let’s pull out the first bicycle in the list bicycles:
bikes = ["Royal Enfield", "Rajdoot", "Bajaj Chetak", "TVS Super"]
name = 'kishore'
name2 = 'vidya'
name3 = 'Sam'
print (bikes[3].title())
print (bikes[2])
print (bikes[-1])
message = "my first bike was " + bikes[2].title().upper() + "\t\nThen i bought" + bikes [0].lower()
message = "I have 2 friends, and both" + name.title() + "," + name2.title() + "comes to school on the bikes"
print (message + "They ride" + bikes[2]+ "," + bikes [0] + "respectively!")
print (message)
#Python has a special syntax for accessing the last element in a list. By asking
#for the item at index -1, Python always returns the last item in the list:
#Tvs Super
#Bajaj Chetak
#TVS Super
#I have 2 friends, and bothKishore,Vidyacomes to school on the bikesThey rideBajaj Chetak,Royal Enfieldrespectively!
#I have 2 friends, and bothKishore,Vidyacomes to school on the bikes |
ff82f8cee9baae9fd747ffa2cc9eca60f1d35b01 | Shivani2601/Training_NPCI | /Python/Tower_Ques2.py | 1,201 | 3.859375 | 4 | incr=3
rows=3
first=1
n=2*rows-2
for i in range(0, rows):
for j in range(0, n):
print(end=" ")
n=n-1
y=first
for j in range(0, i+1):
print(y, end=" ")
y+=1
first+=incr
print(" ")
print("\n")
##########################################
first_ele=0
total_sum=1
for i in range(0,rows):
if(i==0):
print("Row 1 = 1")
first_ele=1+incr
else:
row_sum=0
x=first_ele
for j in range(0,i+1):
row_sum+=x
x+=1
print("Row ", i+1, " = ",row_sum)
total_sum+=row_sum
first_ele+=incr
print("Total sum : ", total_sum, "\n")
##########################################################
Matrix = [[0 for x in range(3)] for y in range(3)]
x=1
for i in range(2,-1,-1):
y=x
for j in range(0,3-i):
Matrix[i][j]=y
y=y+1
x=x+incr
for i in range(0,3):
print(Matrix[i])
print("\n")
##########################################################
for i in range(0,3):
for j in range(0,3):
Matrix[i][j]=Matrix[i][j]*Matrix[i][j]
print("Square of matrix : ")
for i in range(0,3):
print(Matrix[i])
|
67346fc55b06883e5bdd78ef4d7a673fd179fef6 | b26/Amazon-Reviews-CLI | /Python/Dictionary style/people.py | 916 | 3.625 | 4 | #!/usr/bin/env python3
import bsddb3
import os.path
# Create the database
if os.path.isfile("people.db"):
db = bsddb3.btopen("people.db", "w")
else:
db = bsddb3.btopen("people.db", "c")
# Add data to the database
data = {b'Ian': 'Smith', b'Carl': 'Horwitz', b'Ted': 'Smith', b'Fred': 'Torrens'}
for key, value in data.items():
db[key] = value
# Find the last name of 'Carl'
print(db.get(b'Carl').decode(), end="\n\n")
# Find everyone with the last name 'Smith'
cursor = db.db.cursor()
try:
record = cursor.first()
except bsddb3.db.DBNotFoundError:
pass
else:
if record[1].decode() == 'Smith':
print(record[0].decode())
while True:
try:
record = cursor.next()
if record[1].decode() == 'Smith':
print(record[0].decode())
except bsddb3.db.DBNotFoundError:
break
cursor.close()
# Close the database
db.close()
|
75cd0ac7964c03527eda2ef93663ee623f1e0307 | zeleksa/ALS1 | /DU4/b_tree.py | 3,261 | 3.734375 | 4 |
class B_tree():
def __init__(self, t):
self.t = t
self.root = None
def traverse(self):
if self.root is not None:
self.root.traverse()
def search(self, num):
if self.root is None:
return None
self.root.search(num)
def insert(self, num):
if self.root is None:
self.root = B_node(self.t, is_leaf=True)
self.root.keys[0] = num
self.root.n = 1
else:
if self.root.n == 2*self.t - 1:
new_root = B_node(self.t)
new_root.children[0] = self.root
new_root.split_child(0, self.root)
i = 0
if new_root.keys[0] < num:
i += 1
new_root.children[i].insert_non_full(num)
self.root = new_root
else:
self.root.insert_non_full(num)
class B_node():
def __init__(self, t, is_leaf=False):
self.keys = [None for _ in range(2*t - 1)]
self.children = [None for _ in range(2*t)]
self.t = t
self.n = 0
self.is_leaf = is_leaf
def traverse(self):
j = 0
for i in range(self.n):
if not self.is_leaf:
self.children[i].traverse()
print(self.keys[i], end=" ")
j += 1
if not self.is_leaf:
self.children[j].traverse()
def search(self, num):
i = 0
while i < self.n and num > self.keys[i]:
i += 1
if self.keys[i] == num:
print("Found")
return self.keys
if self.is_leaf:
print("Not Found")
return None
return self.children[i].search(num)
def insert_non_full(self, num):
i = self.n - 1
if self.is_leaf:
while i >= 0 and self.keys[i] > num:
self.keys[i+1] = self.keys[i]
i -= 1
self.keys[i+1] = num
self.n += 1
else:
while i >= 0 and self.keys[i] > num:
i -= 1
if self.children[i+1].n == 2*self.t - 1:
self.split_child(i+1, self.children[i+1])
if self.keys[i+1] < num:
i += 1
self.children[i+1].insert_non_full(num)
def split_child(self, i, old_node):
new_node = B_node(old_node.t, is_leaf=old_node.is_leaf)
new_node.n = self.t-1
for j in range(self.t-1):
new_node.keys[j] = old_node.keys[j+self.t]
if not old_node.is_leaf:
for j in range(self.t):
new_node.children[j] = old_node.children[j+self.t]
old_node.n = self.t - 1
for j in range(self.n, i, -1):
self.children[j+1] = self.children[j]
self.children[i+1] = new_node
for j in range(self.n - 1, i, -1):
self.keys[j+1] = self.keys[j]
self.keys[i] = old_node.keys[self.t-1]
self.n += 1
if __name__ == "__main__":
bt = B_tree(3)
bt.insert(10)
bt.insert(20)
bt.insert(5)
bt.insert(6)
bt.insert(12)
bt.insert(30)
bt.insert(7)
bt.insert(17)
bt.traverse()
print()
bt.search(6)
bt.search(15)
|
d65b8b02e60862b40c2ec1f2d03ace49f592a477 | nismojkee/RLE_encode_decode | /rle.py | 1,097 | 3.703125 | 4 | class RLE:
def rle_encode(data):
encoding = ''
previous_character = ''
counter = 1
if not data:
return ''
for character in data:
if character != previous_character:
if previous_character:
encoding += str(counter) + previous_character
counter = 1
previous_character = character
else:
counter += 1
else:
encoding += str(counter) + previous_character
return encoding
def rle_decode(data):
decode = ''
counter = ''
for character in data:
if character.isdigit():
counter += character
else:
decode += character * int(counter)
counter = ''
return decode
# Example Encode:
# encoded_val = RLE.rle_encode('AAAAAAFDDCCCCCCCAEEEEEEEEEEEEEEEEE')
# print(encoded_val)
# 6A1F2D7C1A17E
# Example Decode
# decoded_val = RLE.rle_decode(encoded_val)
# print(decoded_val)
# AAAAAAFDDCCCCCCCAEEEEEEEEEEEEEEEEE
|
6533350573503fb7b0c17d2bb1d4e8f791a559d1 | Harshpatel44/RemindMe | /test.py | 442 | 3.65625 | 4 | __author__ = 'harsh'
import random
import Tkinter as tk
list=[1,2,3,4,5]
print(random.choice(list))
root = tk.Tk()
v = tk.IntVar()
tk.Label(root, text="""Choose a programming language:""",justify = tk.LEFT,padx = 20).pack()
radio1=tk.Radiobutton(root, text="Python",padx = 20, variable=v, value=1).pack(anchor=tk.W)
radio2=tk.Radiobutton(root, text="Perl",padx = 20, variable=v, value=2).pack(anchor=tk.W)
if(radio1==1)
root.mainloop() |
23e5736c95fc1c31ec33fbd533bd72c89ff7f014 | celier/Exercism-python | /pangram/pangram.py | 928 | 3.78125 | 4 | def is_pangram(sentence):
try:
if len(sentence) < 26:
return False
else:
checker = []
for i in range(26):
checker.append(False)
for letter in sentence.lower():
# Using Unicode number representation for index calculation
ind = ord(letter) - ord('a')
if 0 <= ind <= 27:
checker[ind] = True
# Missing character check
for x in checker:
if x == False:
# Where ord('a') could be replaced with 97, it's a constant
print('La lettre %s est absente.' % (chr(x + ord('a'))))
return False
return True
except IndexError as i:
print(i)
return False
except TypeError as e:
print(e)
return False
pass
|
fb7ebd58dc36524ee88ba886fbdc238c8018aa91 | waalge/snake_cube | /tests/basic_tests.py | 1,828 | 3.546875 | 4 | #!/usr/bin/python3
import os
import sys
import unittest
sys.path.append("../snake_cube")
import cube_data
import toy
class TestSnakeCube(unittest.TestCase):
def test_solutions_pass(self):
"""
Check that known solutions work
"""
cube = cube_data.CUBES[2]
strip_lengths = cube["strip_lengths"]
rel_solutions = cube["rel_solutions"]
T = toy.Toy(strip_lengths)
for start in rel_solutions:
T.start(start)
self.assertEqual(T.fail(), 0) # Doesn't fail
self.assertEqual(T.solved(), 1) # Strips used.
pass
def test_some_nonsolutions_fail(self):
"""
Check that known nonsolutions do NOT work
"""
cube = cube_data.CUBES[2]
strip_lengths = cube["strip_lengths"]
rel_solution = cube["rel_solutions"][0]
rel_solution[-1] = (rel_solution[-1] + 1)%3
T = toy.Toy(strip_lengths)
T.start(rel_solution)
self.assertEqual(T.fail(), 1) # DOES fail
pass
def test_input(self):
"""
Check raises error if strips do not have the correct number of cubelets
Some bad inputs.
"""
cube = cube_data.CUBES[2]
strip_lengths = cube["strip_lengths"][:-1]
with self.assertRaises(ValueError):
T = toy.Toy(strip_lengths)
strip_lengths = [1]
with self.assertRaises(ValueError):
T = toy.Toy(strip_lengths)
def test_2_cube(self):
"""
There is essentially only one 2-cube.
There are 6 solutions which you can draw by hand.
"""
strip_lengths = [2, 2, 2, 2, 2, 2, 2]
T = toy.Toy(strip_lengths)
T.run()
self.assertEqual(len(T.solutions()), 6)
if __name__ == "__main__":
unittest.main()
|
126e98cabf536543ce3ea5d9b7af10890e913857 | tareksmoubarak/Coderbyte-Challenges-Python | /longest-word.py | 192 | 4.21875 | 4 | def longestWord(string):
array = string.split()
max = ''
for word in array:
if (len(word) > len(max)):
max = word
return max
print longestWord(raw_input()) |
e083c1cbb643249c39457e466d9f37e5308ca35b | joswong13/Poetry-Tester | /poetry_functions.py | 13,850 | 4.21875 | 4 | """
A poetry pattern: tuple of (list of int, list of str)
- first item is a list of the number of syllables required in each line
- second item is a list describing the rhyme scheme rule for each line
"""
"""
A pronunciation dictionary: dict of {str: list of str}
- each key is a word (a str)
- each value is a list of phonemes for that word (a list of str)
"""
# ===================== Helper Functions =====================
def clean_up(s):
""" (str) -> str
Return a new string based on s in which all letters have been
converted to uppercase and punctuation characters have been stripped
from both ends. Inner punctuation is left untouched.
>>> clean_up('Birthday!!!')
'BIRTHDAY'
>>> clean_up('"Quoted?"')
'QUOTED'
"""
punctuation = """!"'`@$%^&_-+={}|\\/,;:.-?)([]<>*#\n\t\r"""
result = s.upper().strip(punctuation)
return result
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from original,
determined by splitting original on any of the separators.
separators is a string of single-character separators.
>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', 'Finally', "we're done."]
>>> split_on_separators("Row, Row, Row your boat", ".!,")
['Row', 'Row', 'Row your boat']
"""
result = [original]
# Cycles through the set of separators individually
for separator in separators:
split_words = []
# #########################################################################
# Cycle through the strings in the list of strings from result. Extends the
# list split_words with the strings split at separator. result is now
# the list of strings split with separator.
# #########################################################################
for string in result:
words = string.split(separator)
for strings in words:
if strings != '' and strings != ' ':
split_words.append(strings.strip())
result = split_words
return result
def pattern_dict(pattern):
''' (list of int, list of str) -> dict
Return a dictionary where keys are the poetry pattern and the value is the
index of occurrence.
>>> pattern = ([5, 7, 5], ['A', 'B', 'A'])
>>> poetry_dict = pattern_dict(pattern)
>>> poetry_dict == {'B': [1], 'A': [0, 2]}
True
>>> pattern = ([5, 7, 5, 4, 3], ['A', 'B', 'A', 'C', 'A', 'C', 'A'])
>>> poetry_dict = pattern_dict(pattern)
>>> poetry_dict == {'B': [1], 'C': [3, 5], 'A': [0, 2, 4, 6]}
True
'''
pattern_dict = {}
# Looks at the second element in the pattern tuple
lst = pattern[1]
# #########################################################################
# For the number of values in the second element of tuple, create dictionary
# key and append the index (i) of occurrence. If value in dictionary,
# append the index (i) to the key.
# #########################################################################
for i in range(len(lst)):
if lst[i] not in pattern_dict:
pattern_dict[lst[i]] = [i]
else:
pattern_dict[lst[i]].append(i)
return pattern_dict
def lst_of_lst_of_strings(rhyme_pattern):
''' (dict) -> list of list of str
Return a list of list of string based on the sorted dictionary key.
>>> rhyme_pattern = {'B': [1], 'A': [0, 2]}
>>> lst_of_lst_of_strings(rhyme_pattern)
[[0, 2], [1]]
>>> rhyme_pattern = {'B': [1], 'A': [0, 2], 'C': []}
>>> lst_of_lst_of_strings(rhyme_pattern)
[[0, 2], [1]]
'''
# For the sorted keys in the dictionary, append the values to a new list
lst_of_values = []
lst_return = []
for keys in sorted(rhyme_pattern):
lst_of_values.append(rhyme_pattern[keys])
# If the value is not an empty list, append value to new list .
for lst_of_lsts in lst_of_values:
if not len(lst_of_lsts) == 0:
lst_return.append(lst_of_lsts)
return lst_return
# ===================== Required Functions =====================
def count_lines(lst):
r""" (list of str) -> int
Precondition: each str in lst[:-1] ends in \n.
Return the number of non-blank, non-empty strings in lst.
>>> count_lines(['The first line leads off,\n', '\n', ' \n',
... 'With a gap before the next.\n', 'Then the poem ends.\n'])
3
>>> count_lines(['First line,\n', 'Second line,\n', ' \n',
... 'Third line after gap,\n', 'Fourth line,\n',
... 'Fifth line,\n', 'Ending line.\n'])
6
"""
# For each string in list, performs clean_up and if line is not empty string
# will add 1 to num_lines.
num_lines = 0
for lines in lst:
clean_lines = clean_up(lines)
if clean_lines.strip() != '':
num_lines += 1
return num_lines
def get_poem_lines(poem):
r""" (str) -> list of str
Return the non-blank, non-empty lines of poem, with whitespace removed
from the beginning and end of each line.
>>> get_poem_lines('The first line leads off,\n\n\n'
... + 'With a gap before the next.\nThen the poem ends.\n')
['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
>>> get_poem_lines(' First line,\n\n\nPoems are fun!\n\n \n'
... + 'Second line.\nThird line.\n')
['First line,', 'Poems are fun!', 'Second line.', 'Third line.']
"""
result = split_on_separators(poem, '\n')
return result
def check_syllables(poem_lines, pattern, word_to_phonemes):
r""" (list of str, poetry pattern, pronunciation dictionary) -> list of str
Precondition: len(poem_lines) == len(pattern[0])
Return a list of lines from poem_lines that do not have the right number of
syllables for the poetry pattern according to the pronunciation dictionary.
If all lines have the right number of syllables, return the empty list.
>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
>>> pattern = ([5, 5, 4], ['*', '*', '*'])
>>> word_to_phonemes = {'NEXT': ['N', 'EH1', 'K', 'S', 'T'],
... 'GAP': ['G', 'AE1', 'P'],
... 'BEFORE': ['B', 'IH0', 'F', 'AO1', 'R'],
... 'LEADS': ['L', 'IY1', 'D', 'Z'],
... 'WITH': ['W', 'IH1', 'DH'],
... 'LINE': ['L', 'AY1', 'N'],
... 'THEN': ['DH', 'EH1', 'N'],
... 'THE': ['DH', 'AH0'],
... 'A': ['AH0'],
... 'FIRST': ['F', 'ER1', 'S', 'T'],
... 'ENDS': ['EH1', 'N', 'D', 'Z'],
... 'POEM': ['P', 'OW1', 'AH0', 'M'],
... 'OFF': ['AO1', 'F']}
>>> check_syllables(poem_lines, pattern, word_to_phonemes)
['With a gap before the next.', 'Then the poem ends.']
>>> poem_lines = ['The first line leads off,']
>>> check_syllables(poem_lines, ([0], ['*']), word_to_phonemes)
[]
>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
>>> check_syllables(poem_lines, ([5, 0, 4], ['*', '*', '*']), word_to_phonemes)
['Then the poem ends.']
"""
rhy_position = 0
poem = []
# If the poem is only one line and the syllable pattern is 0, return empty list.
if len(pattern[0]) == 1 and pattern[0][0] == 0:
return poem
# #########################################################################
# For each strings in the poem, split the string into list of strings
# (splitting). For each word in splitting, perform clean_up and obtain
# phonemes. For each phonemes, if the last character is digit, syllable
# counter will plus one.
# #########################################################################
for strings in poem_lines:
syllables = 0
splitting = strings.split()
for i in range(len(splitting)):
word = clean_up(splitting[i])
phonemes = word_to_phonemes[word]
for segments in phonemes:
if segments[-1].isdigit() == True:
syllables += 1
# If the syllable pattern at position rhy_position is 0, rhy_pattern counter
# will add one.
if pattern[0][rhy_position] == 0:
rhy_position += 1
# If the syllable counter does not equal the syllable pattern at rhy_position
# append the string.
elif syllables != pattern[0][rhy_position]:
poem.append(strings)
rhy_position += 1
# If syllable counter equals the syllable pattern, rhy_position will add one.
else:
rhy_position += 1
return poem
def check_rhyme_scheme(poem_lines, pattern, word_to_phonemes):
r""" (list of str, poetry pattern, pronunciation dictionary)
-> list of list of str
Precondition: len(poem_lines) == len(pattern[1])
Return a list of lists of lines from poem_lines that should rhyme with
each other but don't. If all lines rhyme as they should, return the empty
list.
>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
>>> pattern = ([5, 7, 5], ['A', 'B', 'A'])
>>> word_to_phonemes = {'NEXT': ['N', 'EH1', 'K', 'S', 'T'],
... 'GAP': ['G', 'AE1', 'P'],
... 'BEFORE': ['B', 'IH0', 'F', 'AO1', 'R'],
... 'LEADS': ['L', 'IY1', 'D', 'Z'],
... 'WITH': ['W', 'IH1', 'DH'],
... 'LINE': ['L', 'AY1', 'N'],
... 'THEN': ['DH', 'EH1', 'N'],
... 'THE': ['DH', 'AH0'],
... 'A': ['AH0'],
... 'FIRST': ['F', 'ER1', 'S', 'T'],
... 'ENDS': ['EH1', 'N', 'D', 'Z'],
... 'POEM': ['P', 'OW1', 'AH0', 'M'],
... 'OFF': ['AO1', 'F']}
>>> check_rhyme_scheme(poem_lines, pattern, word_to_phonemes)
[['The first line leads off,', 'Then the poem ends.']]
>>> poem_lines = ['The first line leads off,', 'With a gap before the next.', 'Then the poem off.']
>>> pattern = ([5, 7, 5], ['*', '*', '*'])
>>> check_rhyme_scheme(poem_lines, pattern, word_to_phonemes)
[]
"""
final_result = []
# Create dictionary for poetry pattern
rhyme_pattern = pattern_dict(pattern)
# Cycle though each key in dictionary and create empty list for each key
for keys in rhyme_pattern:
rhyme = []
list_of_strings = []
# Cycle through each value in keys
for position in rhyme_pattern[keys]:
# #########################################################################
# Split string and get last word from string and perform clean_up to
# reference the key in word_to_phonemes dictionary. Create variables to
# stop for loop.
# #########################################################################
string = poem_lines[position]
stopper = 0
rhyme_counter = 0
splitting = string.split()
last_word = splitting[-1]
word = clean_up(last_word)
pronunciation = word_to_phonemes[word]
# #########################################################################
# Find the syllable in the list of pronunciation starting from the back.
# Append the syllable to the end of the list to a new list, rhyme.
# #########################################################################
for i in range(len(pronunciation)-1, -1, -1):
if stopper < 1:
if pronunciation[i][-1].isdigit() == True:
rhyme.append(pronunciation[i:])
stopper += 1
# #########################################################################
# If rhyme only contains one list, will not compare phonemes. For rhymes
# more than one list, will compare the phonemes and count if the list
# are the same. If the rhymes are not the same, list_of_strings will
# append the lines of the poem that don't rhyme and assign to rhyme_pattern
# dictionary. If the rhymes are the same, then blank list will be assigned
# to rhyme_pattern dictionary.
# #########################################################################
if len(rhyme) == 1 or keys == '*':
list_of_strings = []
rhyme_pattern[keys] = list_of_strings
else:
for i in range(len(rhyme)-1):
if not rhyme[i] == rhyme[i+1]:
rhyme_counter +=1
if rhyme_counter > 0:
for position in rhyme_pattern[keys]:
list_of_strings.append(poem_lines[position])
rhyme_pattern[keys] = list_of_strings
else:
list_of_strings = []
rhyme_pattern[keys] = list_of_strings
# #########################################################################
# Sorts the rhyme_pattern dictionary bye key and appends the new values
# to a new list. Creates list of list of strings.
# #########################################################################
final_result = lst_of_lst_of_strings(rhyme_pattern)
return final_result
if __name__ == '__main__':
import doctest
doctest.testmod()
|
effcb1ac657055345907dc7ab1a2bef64a6ea8be | 9car/IN1000-1 | /uke5/roter_matrise.py | 339 | 3.578125 | 4 | matriseEn = [
[1,4,7],
[2,5,8],
[3,6,9]
]
matriseTo = [
[1,2,3],
[4,5,6],
[7,8,9]
]
def roter(matrise):
returMatrise = []
for i in range(0,len(matrise)):
returMatrise.append([])
for j in range(0, len(matrise[i])):
returMatrise[i].append(matrise[j][i])
return returMatrise
print(roter(matriseTo))
|
ae0599b2660cc5e3fb246a0ce52dd6a18093323a | 9car/IN1000-1 | /uke3/barnebarn.py | 188 | 3.703125 | 4 | person = input("Konge: ")
etterkommere = {"Oscar":"Haakon", "Haakon":"Olav", "Olav":"Harald"}
barn = etterkommere[person]
barnebarn = etterkommere[barn]
print("Barnebarn: " + barnebarn)
|
d940e6fd24a3f53c61a141ae3d4565b455261812 | 9car/IN1000-1 | /2017/kode.py | 3,021 | 3.53125 | 4 | #Oppgave 3a
"""
def hastighet(fart):
if fart <= 60:
return "fart:" + str(fart)
else:
return "fart:over 60"
print(hastighet(56))
print(hastighet(65))
"""
#Oppgave 3b
"""
def sjekkVerdier(tallene, min, max):
for tall in tallene:
if tall <= min or tall => max:
return False
return True
#Dersom min > max vil testen "tall <= min or tall => max" alltid være sant, så funksjonen vil alltid returnere False.
"""
#Oppgave 3c
"""
def hovedprogram():
a = Node("a")
a.settInnHoyre(Node("b"))
a.settInnVenstre(Node("c"))
hovedprogram()
"""
#Oppgave 4
class Bud:
def __init__(self, budgiver, budStr):
self._budgiver = budgiver
self._budStr = budStr
if budStr <= 0:
self._budStr = 1
def hentBudgiver(self):
return self._budgiver
def hentBudStr(self):
return self._budStr
class Annonse:
def __init__(self, annTekst):
self._annTekst = annTekst
self._bud = []
def hentTekst(self):
return self._annTekst
def giBud(self, hvem, belop):
nyttBud = Bud(hvem, belop)
self._bud.append(nyttBud)
def antBud(self):
return len(self._bud)
def hoyesteBud(self):
hoyeste = None
hoyesteVerdi = 0
for bud in self._bud:
if bud.hendtBudStr() > hoyesteVerdi:
hoyeste = bud
hoyesteVerdi = bud.hendtBudStr()
return hoyeste
#Oppgave 4e
def kraftBud(self, hvem, belop, max):
budBelop = belop
hoyeste = self.hoyesteBud().hendtBudStr()
if belop < hoyeste:
budBelop = hoyeste + 1
if budBelop > max:
budBelop = max
self.giBud(hvem, budBelop)
class Kategori:
def __init__(self, katNavn):
self._katNavn = katNavn
self._annonseListe = []
def nyAnnonse(self, annTekst):
ny = Annonse(annTekst)
self._annonseListe.append(ny)
return ny
def hentAnnonser(self):
return self._annonseListe
class Bruktmarked:
def __init__(self):
self._ordbok = {}
def nyKategori(self, katNavn):
if finnKategori(katnavn) == None:
nyKat = Kategori(katnavn)
self._ordbok[katNavn] = nyKat
return nyKat
else:
return None
def finnKategori(self, katNavn):
for kat in self._ordbok:
if kat == katNavn:
return self._ordbok[kat]
return None
def hovedprogram():
bruktmarked = Bruktmarked()
kategori = bruktmarked.nyKategori("sykkellykt")
annonse = kategori.nyAnnonse("New Yorker sykkellykt")
annonse.giBud("Peter", 42)
annonse.giBud("Ann", 0)
annonse.kraftBud("Mary", 40, 50)
hoyesteBudStr = ann.hoyesteBud().hentBudStr()
budGiver = ann.hoyesteBud().hentBudgiver()
print(hoyesteBudStr, "gitt av", budGiver)
#Alternativt med assert
assert hoyesteBudStr == 43
assert budGiver == "Mary"
hovedprogram()
|
71fcf1b193e8f96abba78167d65180f062ca59a8 | 9car/IN1000-1 | /oblig5/regnefunksjon.py | 1,523 | 4.15625 | 4 | def addisjon(tall1, tall2):
tall1 = int(tall1)
tall2 = int(tall2)
# Regner ut summen av to tall
return tall1 + tall2
print(addisjon(2, 9))
def subtraksjon(tall1, tall2):
tall1 = int(tall1)
tall2 = int(tall2)
# Regner ut differansen
return tall1 - tall2
assert subtraksjon(15, 10) == 5
assert subtraksjon(-15, 10) == -25
assert subtraksjon(-5, -5) == 0
def divisjon(tall1, tall2):
tall1 = int(tall1)
tall2 = int(tall2)
# Regner ut kvotienten
return tall1/tall2
assert divisjon(10, 5) == 2
assert divisjon(-10, 5) == -2
assert divisjon(-10, -5) == 2
def tommerTilCm(antallTommer):
antallTommer = int(antallTommer)
assert antallTommer > 0
# Regner ut hvor mange tommer det er i cm
antallTommer = antallTommer * 2.54
return antallTommer
# skriver ut et eksempel tall
print(tommerTilCm(28))
print()
# Prosedyre som ved bruk av input utfører regnestykker ved hjelp av funksjonene som er laget over
def skrivBeregninger():
print("Utregninger:")
tall1 = input("Skriv inn tall 1: ")
tall2 = input("Skriv inn tall 2: ")
print()
print("Resultatet av summering: ", addisjon(tall1, tall2))
print("Resultatet av subtraksjon: ", subtraksjon(tall1, tall2))
print("Resultatet av divisjon: ", divisjon(tall1, tall2))
print()
print("Konvertering fra tommer til cm:")
tall = input("Skriv inn et tall: ")
print("Resultat: ", tommerTilCm(tall))
# Kaller på prosedyren for at den skal kjøres
skrivBeregninger()
|
fc4f97c0c76ef25cd8efcaf8eb93dee153cf6db6 | 9car/IN1000-1 | /uke4/lokker.py | 237 | 4 | 4 | tall = int(input("Tast et heltall: "))
teller = 0
while teller < tall:
print(teller)
teller += 1
tall = 0
while tall != 10:
inp = input("Tast et heltall: ")
tall = int(inp)
print("Du tastet 10, programmet avsluttes")
|
84845b00c49ff78c0f4f06c4903ba398033865f9 | 9car/IN1000-1 | /uke4/heltallsliste.py | 279 | 3.640625 | 4 | tall1 = 0
tall2 = 1
tall3 = 2
tall4 = 3
tall5 = 4
print(tall1)
print(tall2)
print(tall3)
print(tall4)
print(tall5)
tall = []
teller = 0
while teller < 5:
tall.append(teller)
teller += 1
print(tall)
teller = 0
while teller < 5:
print(tall[teller])
teller += 1
|
4632666bba9cbf231408e080387ef5e3eacc22f5 | 9car/IN1000-1 | /uke2/minst.py | 149 | 4.03125 | 4 | tall1 = int(input("Skriv tall 1: "))
tall2 = int(input("Skriv tall 2: "))
if tall1 < tall2:
minst = tall1
else:
minst = tall2
print(minst)
|
dfd6fe415e73a1916574aaa0afcf44136ac28a7a | 9car/IN1000-1 | /oblig4/regnelokke.py | 856 | 4.03125 | 4 | #Tom liste som lagrer alle tallene brukeren taster inn
liste = []
tall = int(input("Tast inn et tall: "))
#Så lenge tallet ikke er 0 vil den kjøre i en evig loop
while tall != 0:
liste.append(tall)
print(tall)
tall = int(input("Tast inn et tall: "))
#Skriver ut alle tallene i listen på en pen måte
for i in range(len(liste)):
print(liste[i])
#Adderer sammen alle tallene i listen og skriver ut en sluttsum
minSum = 0
for tall in liste:
minSum += tall
print("Summen av tallene er:",minSum)
#Finner det minste tallet i listen
minste = liste[0]
for i in liste:
if i < minste:
minste = i
print("Her er det minste tallet:", minste)
#Finner det største tallet i listen
stoerst = liste[0]
for i in range(len(liste)):
if liste[i] > stoerst:
stoerst = liste[i]
print("Her er det største tallet:",stoerst)
|
d1db5bb3eba3dbbf16385db01c338788bf802e0d | 9car/IN1000-1 | /uke2/hello_world.py | 131 | 3.578125 | 4 | hello = "Hello"
print(hello)
world = "World"
print(world)
print(hello + " " + world)
print(hello, "?", " ", world, "?", sep="")
|
a51d3197844b8fa2d3aa3f504d08d89e21df1872 | 9car/IN1000-1 | /uke4/en_plusset_opp_til_hundre.py | 95 | 3.5625 | 4 | tall = 0
summen = 0
while tall <= 100:
summen = summen + tall
tall += 1
print(summen)
|
7db4c3b683edf2b2025950cc8a01f258c2f49fac | 9car/IN1000-1 | /2019H/kode.py | 2,327 | 3.515625 | 4 | """bok = {"a":[3,4,5], "b":[6,7]}
bok["a"].append(8)
print(len(bok["a"]))
"""
"""def funk(a,b):
return a*b
c = funk(2+3,2)*4
print(c)
"""
"""#Oppgave 3a
def pris_inkl_frakt(varepris):
if varepris > 1000:
return varepris
elif varepris >= 500 and varepris <= 1000:
return varepris + 50
elif varepris < 500:
return varepris + 80
assert pris_inkl_frakt(300) == 380
assert pris_inkl_frakt(600) == 650
assert pris_inkl_frakt(1300) == 1300
"""
"""#Oppgave 3b
def fjern_utsolgte(handleliste, utsolgte):
nyliste = []
for vare in handleliste:
if not vare in utsolgte:
nyliste.append(vare)
else:print(vare)
return nyliste
assert fjern_utsolgte( ["melk", "brus", "pasta"], ["kanel","brus"]) == ["melk", "pasta"]"""
"""
#Oppgave 3c
def samlet_vaksinasjon(krav_hvert_land):
vaksiner = []
for krav in krav_hvert_land:
for vaksine in krav:
if not vaksine in vaksiner:
vaksiner.append(vaksine)
return vaksiner
print(samlet_vaksinasjon([["difteri","tyfoid"],["hepati","difteri"]]))"""
"""
#Oppgave 3d
def forkort_setning(setning,fjern):
ny_setning = ""
for ord in setning.split():
if not ord==fjern:
ny_setning = ny_setning + ord + " "
return ny_setning
setning = "en krabbe skal en dag ut av skallet "
setning_v2 = forkort_setning(setning, "en")
setning_v3 = forkort_setning(setning_v2, "skal")
print(setning_v2)
print(setning_v3)
"""
def sjekk_om_fyord(setning, fyord, synonym_liste):
biter = setning.split()
for bit in biter:
for synonym in synonym_liste:
if bit in synonym and fyord in synonym:
return True
return fyord in biter
assert sjekk_om_fyord("spis masse godsaker", "snop",
[["saft","lemonade"],["snacks","snop","godsaker"],["mye","masse"]]) == True
assert sjekk_om_fyord("spis masse godsaker", "godsaker",
[["saft","lemonade"],["snacks","snop","godsaker"],["mye","masse"]]) == True
assert sjekk_om_fyord("spis masse godsaker", "godsaker", []) == True
assert sjekk_om_fyord("spis masse godsaker", "lemonade",
[["saft","lemonade"],["snacks","snop","godsaker"],["mye","masse"]]) ==False
assert sjekk_om_fyord("spis masse godsaker", "agurk", [["mye","masse"],["spis","gomle"],["snacks","snop","godsaker"]]) == False
|
b8589ee02e53c0fa67f2bc5d78a820e472c82fc6 | 9car/IN1000-1 | /oblig4/funksjoner.py | 776 | 3.703125 | 4 | #lager en funksjon som returnerer to tall addert med hverandre
def adder(tall1,tall2):
return tall1 + tall2
#Skriver de ut
sum = adder(2, 4)
print("Her er summen av tallene:", sum)
sum = adder(6, 10)
print("Her er summen av tallene:", sum)
#Lager en funksjon som teller hvor mange ganger en bokstav forekommer i en tekst
def tellForekomst(minTekst, minBokstav):
#Lager en variabel med navn teller som øker med en hver gang bokstaven forekommer
teller = 0
for tegn in minTekst:
if tegn == minBokstav:
teller +=1
return teller
#Skriver ut resultatet
minTekst = input("Skriv inn et ord: ")
minBokstav = input("Skriv inn en bokstav (f.eks: a): ")
print("Det finnes", tellForekomst(minTekst,minBokstav), minBokstav, "i ordet", minTekst)
|
7bb84903c775f616e0bf51f6d883fdf722ac5627 | vbellee/python_simulation | /FiberSetup.py | 7,743 | 3.5625 | 4 | # @file FiberSetup.py
"""
.. module:: FiberSetup
:synopsis: Fiber Definition and fiber_stack definition
.. moduleauthor:: <sebastiana.giani@epfl.ch>
"""
import numpy as np
import math
import random
import ROOT
import Sipm
import MainSimulation
class Fiber(object):
"""Class to define the object fiber.
Each object fiber is defined by the center coordinates (the attributes Xc and Yc), the
diameter and the refraction index of the core material.
All the method of this class are definide here:
"""
def __init__(self, Xc=0, Yc=0, diameter=250e-06, core_index=1.59):
"""The init method is invoked to create a new class instance """
self.Xc = Xc
self.Yc = Yc
self.diameter = diameter
self.core_index = core_index
self.photons = 0
def getImpact(self, Theta, X0, Y0):
"""Method to calculate the impact parameter.
Given the initial position of the particle (Theta, X0,Y0) and the coordinate
of the fiber center, returns the impact parameter of the particle with respect
to the fiber axis. This method is invoked by the method :func:`producePhotons`."""
Xp=X0 + math.sin(Theta)*math.sin(Theta)*(self.Xc-X0) + math.sin(Theta)*math.cos(Theta)*(self.Yc-Y0);
Yp=Y0 + math.sin(Theta)*math.cos(Theta)*(self.Xc-X0) + math.cos(Theta)*math.cos(Theta)*(self.Yc-Y0);
impact=math.sqrt((self.Xc-Xp)*(self.Xc-Xp)+(self.Yc-Yp)*(self.Yc-Yp))
#print 'imp', impact,'xp', Xp, 'yp', Yp, self.Xc, self.Yc
return impact
def producePhotons(self, Theta, X0, Y0):
"""Generation of photons.
According to the value of the impact parameter, calculated calling the method :func:`getImpact`,
a certain number of photons is generetad randomly following the shape of some functions. These functions
represent the photons distribution obtained by a Geant simulation.
This function returns a number of photons greater than zero only if the impact parameter is lower
than tha radius of the fiber"""
impact=self.getImpact(Theta, X0,Y0)
#print impact
#impact=0.000123
#print self.diameter
if impact<=self.diameter/2:
# print impact
impact=impact*1000000
if impact>=0 and impact<=25:
f1=ROOT.TF1("f1","57.5095*exp(-0.5*pow((x-22.1398)/6.16924,2))",0,50)
number=f1.GetRandom()
elif impact>25 and impact<=50:
f1=ROOT.TF1("f1","TMath::Landau(x,18.4867,2.66185,0)*341.192",0,50)
number=f1.GetRandom()
elif impact>50 and impact<=75:
f1=ROOT.TF1("f1","TMath::Landau(x,17.9427,2.74043,0)*364.594",0,50)
number=f1.GetRandom()
elif impact>75 and impact<=100:
f1=ROOT.TF1("f1","68.0951*exp(-0.5*pow((x-18.178)/4.91197,2))",0,50)
number=f1.GetRandom()
elif impact>100 and impact<=125:
f1=ROOT.TF1("f1","59.8287*exp(-0.5*pow((x-12.1788)/4.54820,2))",0,40)
number=f1.GetRandom()
self.photons=int(round(number))
else:
self.photons=0
#print self.photons
def resetPhotons(self):
self.photons=0
class Setup(object):
"""This class define the geometry of the setup.
Given a certain number of layers, number of fiber per layers, the gap between two
close fiber in the same layer,usint the class method __init__ a class instance is created
with these caracheteristics.
The most important attribute of this class is :attr:`fiber_stack` that representes one matrix of
fiber objects. For each fiber, a position for the center is assigned in order to define the geometry
of the simulated setup.
All the method of this class are definide here """
#def __init__(self, filename, layers=5, nfibers=128, diameter=250e-06, gap_diam=30e-06, ch_widht=0.25e-03, ch_height=1.5e-03):
def __init__(self, parameter):
#self.param=MainSimulation.Parameters(filename)
self.param = parameter
self.layers = self.param.layers
#self.nfibers = nfibers
#self.diameter = diameter
#self.gap = gap_diam
#self.channel_widht = ch_widht
#self.channel_height = ch_height
self.nfibers =self.param.nfibers
self.diameter = self.param.diameter
self.gap = self.param.fiber_gap
self.channel_width = self.param.ch_width
self.channel_height = self.param.ch_height
self.channel_array = Sipm.ChannelArray(parameter)
self.x = -random.random()*self.diameter/2
self.y = math.sqrt(math.pow(self.diameter,2) - math.pow((self.diameter+self.gap)/2,2))
self.y0 = self.diameter/2*math.cos(math.asin((self.diameter+self.gap)/2/self.diameter))
self.fiber_stack = []
"""Matrix of fiber objects.
This matrix represent a stack of fibers, our setup. For each fiber, a position for the center is assigned in order to define the geometry
of the simulated setup. """
pro=[]
x= self.x
for i in range (self.nfibers):
temp = []
for j in range (self.layers):
if j%2==0:
temp.append(Fiber(x, 2.0*(j-1.0)*self.y-j*self.y,self.diameter,1.59 ))
else:
temp.append(Fiber(x+(self.diameter+self.gap),(-2.0+j)*self.y,self.diameter,1.59))
x+= self.diameter+self.gap
pro.append(temp)
a=np.array(pro).T #the list of list "pro" is transformed in a numpy array because we need to transpose it.
self.fiber_stack=a
def simulateParticle(self, Theta, X0,Y0):
"""This method simulates the particle passing through the stack of fibers.
For each fiber in the stack, the :func:`producePhotons` in the class :class:`Fiber` is called.
After the photons production,in oder to simulate the signal produced by photons in the detector
the functions :func:`Sipm.ChannelArray.fillPixels`, :func:`Sipm.ChannelArray.fillChannelArray`, from :mod:`Sipm`, class :class:`Sipm.ChannelArray`
are invoked."""
print self.nfibers
for layers in range(self.layers):
for nfibers in range(self.nfibers):
#for layers in range(self.layers):
self.fiber_stack[layers][nfibers].producePhotons(Theta,X0,Y0)
if self.fiber_stack[layers][nfibers].photons>0:
print layers, nfibers, self.fiber_stack[layers][nfibers].Yc
print self.fiber_stack[layers][nfibers].photons
for nfibers in range(self.nfibers):
for layers in range(self.layers):
self.channel_array.fillPixels(self.fiber_stack[layers][nfibers])
self.channel_array.fillChannelArray()
def reset(self):
self.channel_array.resetArray()
for nfibers in range(self.nfibers):
for layers in range(self.layers):
self.fiber_stack[layers][nfibers].resetPhotons()
def checkFiberCrossTalk(self):
pass
def getObjectChannel(self):
"""This method retuns an object from :mod:`Sipm`, class :class:`ChannelArray`, used to get
attributes of the class"""
return self.channel_array
|
0b111a4e7f476a46248db5680d9c0ab9d1aebc1d | miffymon/Python-Learning | /ex06.py | 1,210 | 4.40625 | 4 |
#Python function pulls the value although its not announced anywhere else
#string in a string 1
x = "There are %d types of people." % 10
#naming variable
binary = "binary"
#naming variable
do_not = "don't"
#assigning sentence to variable and calling other assigned variables
#string in a string 2
y = "Those who know %s and those who %s." % (binary, do_not)
#printing sentences by their variables
print x
print y
#prints left side of sentence, calls a format and assignes variable which completes the rest of the sentence
#string in a string 3
print "I said: %r" % x
print "I also said: '%s'" % y
#names variable hilarious to false
hilarious = False
#names variable to rep a sentence and include the ref to another variable to be named
#string in a string 4
joke_evaluation = "Isn't that joke so funny?! %r"
#calls upon 2 variables and puts them side-by-side
#string in a string 5
print joke_evaluation % hilarious
#calls variables rep by parts of a sentence
w = "This is the left side of ..."
e = "a string with a right side."
#adds the first variable's value to the other in the same order
#w+e makes a longer string because the two assigned sentences assigned to the variables are long
print w + e
|
41b9362f35f0f4f97d43258315b595cfb5ed545b | smccrave/python595 | /lec08/scientific_computing.py | 3,371 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Python Lecture 8: Scientific Computing
# ## Jarret Petrillo copyright 2020
# ## AMS 595
# # Learning Goals
#
# Review code sample to produce *deterministic chaos*.
#
# This involves solving *ordinary differential equations*, a hallmark of scientific computation and computational applied mathematics.
#
# References: S. Pope *Turbulent Flows*, ch. 3
#
# # Lorenz System of ODEs
#
# See *Chaos* by James Gleick. It is a great story how a new branch of mathematics was developed to study the non-linear problems classical physicists ignored.
#
# *Deterministic* chaos can happen in systems of at least three variables. Given some starting conditions the outcome after a few steps is *unpredictable*.
#
# We will see this in action.
# In[36]:
# code credit to Christian Hill @ https://scipython.com
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Lorenz paramters
sigma, beta, rho = 10, 2.667, 28
def lorenz(state, t, sigma, beta, rho):
"""The Lorenz equations."""
u, v, w = state # unpack state tuple
u_new = -sigma*(u - v)
v_new = rho*u - v - u*w
w_new = -beta*w + u*v
return u_new, v_new, w_new # return state tuple
# # Numerical Solutions to ODEs
#
# A numerical *solution* is not a standard answer from an ODE class.
#
# Numerical solutions give the *value of the solution function at predetermined points.*
#
# In this case we specify the times for which we would like the state variables (u,v,w).
# In[23]:
# 10,000 steps from 0 to 100
times_to_solve = np.linspace(0, 100, 10000)
print(times_to_solve)
# In[17]:
help(odeint)
# In[37]:
# initial conditions
u0, v0, w0 = 0, 1, 1.05
f = odeint(lorenz, (u0, v0, w0), times_to_solve, args=(sigma, beta, rho))
u_alltime, v_alltime, w_alltime = f.T
print(type(u_alltime))
print(u_alltime.shape) #10,000 matches number inputs
# In[35]:
plt.plot(u_alltime)
# In[ ]:
# # "A butterfly flapping its wings can cause a hurrican on the other side of the world..."
#
# This is chaos!
#
# Small changes in initial conditions can have big effects.
#
# We test this.
#
# In[38]:
# first initial conditions
u0, v0, w0 = 0, 1, 1.05
# new initial conditions
u1, v1, w1 = 0.0000001, 1, 1.05
# In[40]:
f = odeint(lorenz, (u1, v1, w1), times_to_solve, args=(sigma, beta, rho))
u1_alltime, v1_alltime, w1_alltime = f.T
# # Will there be a big difference in u from the first and second initial conditions?
#
# Mind the difference is 10e-7.
#
# These types of measurement errors could be anywhere.
#
# We compare the difference: u_alltime - u1_alltime
# In[41]:
plt.plot(u_alltime-u1_alltime)
# # Result
#
# For 25 seconds there is no effect. But, then their is complete differences.
#
# Compare to the first plot.
#
# These differences are on the order of magnitude to the original values of u at the initial conditions.
# # Statistical Mechanics
# It is impossible to forecast a chaotic system past a key point in time. Beyond it, even the smallest changes have wild effects.
#
# "A solution" is clearly not the goal for studies of chaotic processes because the tiniest measurement error and the solution is a different one.
#
# Knowing that *many important processes are chaotic*, what do you think the aim of this research should be?
#
|
f533dddb9e2ba1ecb1d1a7b0a4a6ceb20976d022 | ferisso/phytonexercises | /exercise7.py | 893 | 4.21875 | 4 | # Question:
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j.
# Note: i=0,1.., X-1; j=0,1,¡Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should be:
# [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
# Hints:
# Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form.
first_input = input("> ")
dimensions = [int(x) for x in first_input.split(',')]
numero_de_linhas = dimensions[0]
numero_de_colunas = dimensions[1]
matriz = [[0 for col in range(numero_de_colunas)] for row in range(numero_de_linhas)]
for row in range(numero_de_linhas):
for col in range(numero_de_colunas):
matriz[row][col]= row*col
print (matriz) |
0f7140089e5db6941ebeddc8fc1796c09c5609b6 | VinPer/DiscordBot | /extensions/rng.py | 3,826 | 3.75 | 4 | # -*- coding: utf-8 -*-
import discord
import random
import math
from discord.ext import commands
"""
This extension implements basic commands based upon the use of randomly
generated numbers or choices, just to add some interactivity to the bot.
"""
class RNG:
def __init__(self, client):
self.client = client
"""
8ball is a very simple eight ball command, answering a yes or no
question with a randomly selected choice, having the possibility
of 2 uncertain answers, 4 affirmative answers and 4 negative answers.
"""
@commands.command(name="8ball",
description="Answers all your yes or no questions.",
pass_context=True)
async def eight_ball(self, context, message: str=None):
if message is not None:
author = context.message.author
possible_responses = [
"bears ate my response",
"ask again later",
"yes.",
"definitely.",
"it is certain.",
"absolutely.",
"no.",
"absolutely not.",
"don't bet on it.",
"negative."
]
await self.client.say(author.mention + ", " +
random.choice(possible_responses))
else:
await self.client.say(author.mention + ", you must supply a ",
"question for me to answer.")
"""
roll simulates the roll of a dice, although being able to take any
amount of sides. It allows for you to roll multiple dice and add
a value to the final result.
"""
@commands.command(name="roll",
description="Rolls a dice of your choice. Use -d to " +
"see all rolls.",
aliases=['dice', 'r'])
async def roll(self, message: str=None, mode: str=None):
try:
rolls = int(message.split("d")[0])
limit = int(message.split("+")[0].split("d")[1])
# check for presence of + argument
if len(message.split("+")) > 1:
add = int(message.split("+")[1])
else:
add = 0
rolls_array = []
result = 0
for r in range(rolls):
random_roll = random.randint(1, limit)
rolls_array.append(str(random_roll))
result += random_roll
# if -d mode is active, display all rolls.
# may not work with large numbers
if mode == "-d":
message = ", ".join(rolls_array) + "\nYou have rolled: " \
+ str(result+add)
else:
message = "You have rolled: " + str(result + add)
await self.client.say(message)
except Exception as e:
await self.client.say("There was an error. Make sure you're " +
"utilizing the NdN or NdN+N formats.")
"""
choose has the bot choose randomly from a set of text options the user
provides, separated by commas.
"""
@commands.command(name="choose",
description="Chooses between a set of options. " +
"Separate them by a comma.",
aliases=["choice"],
pass_context=True)
async def choose(self, context):
try:
content = context.message.content.split(" ", maxsplit=1)[1]
options = content.split(",")
await self.client.say("I have chosen: " + random.choice(options))
except Exception:
await self.client.say("You gave me no options to choose from.")
def setup(client):
client.add_cog(RNG(client))
|
fb719360014e44e85e16f13ba806ec60c59eb97d | yanlingsishao/study | /day2/高阶函数.py | 3,405 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月16日
@author: WangQiyuan
'''
#高阶函数定义
#1.函数接收的参数是一个函数名
#2.函数的返回值是一个函数名
#3.满足上述条件任意一个,都可称之为高阶函数
#(1)
# import time
# def foo():
# time.sleep(3)
# print("hell,你好")
# def test(func):
# start_time=time.time()
# func()
# stop_time=time.time()
# print("函数运行时间是%s"%(stop_time-start_time))
#
# test(foo)
#(2)
# def foo():
# print("nihao")
# def test(func):
# return func
# # res=test(foo)
# # res()
# foo=test(foo)
# foo()
#(3)不修改foo源代码,不修改foo调用方式
# import time
# def foo():
# time.sleep(3)
# print("nihao")
# def test(func):
# return func
# def timer(func):
# start_time = time.time()
# func()
# stop_time=time.time()
# print("函数运行时间是%s"%(stop_time-start_time))
# return func
# foo=timer(foo)
# 函数嵌套
def father(name):
print('from father %s' %name)
def son():
print('from son')
def grandson():
print('from grandson')
grandson()
son()
father('王琦渊')
# 闭包,作用域的一种体现
# num_1=[1,2,10]
# ret=[]
# for i in num_1:
# ret.append(i**2)
#
# print(ret)
# def map_test(func,array):
# ret =[]
# for i in array:
# res=func(i)
# ret.append(res)
# return ret
#
# gg = list(map(lambda x:x+1,num_1))
# print(gg)
# movie_people=['alex','wupeiqi','yuanhao','sb_alex','sb_wupeiqi','sb_yuanhao']
# def filter_test(func,array):
# ret=[]
# for i in array:
# if func(i):
# ret.append(i)
# return ret
#
# print(filter_test(tell_sb,movie_people))
#函数filter,返回可迭代对象
# print(list(filter(lambda x:x.startswith('sb'),movie_people)))
from functools import reduce
#map 处理序列中的每个元素,得到的结果是一个列表,该列表元素个数及位置于原来一样
# print(list(map(lambda x:x+2, [1, 2, 3])))
#>>>[3, 4, 5]
# print(list(map(lambda x,y:x+y, [2, 3], [1, 2])))
# >>>[3, 5]
#
# 处理一个序列,然后把序列进行和并操作
# print(reduce(lambda x,y:x+y, [1,2,3,4],10))
# >>>20
#
# filter 遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来,过滤
# print(list(filter(lambda x:x%2==1, range(20))))
# >>>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# zip
# p={"name":1,"age":50,"gender":"none"}
# print(list(zip(("a","b","c","h"),(1,2,3))))
# print(list(zip(p.keys(),p.values())))
# l=[1,2,3,-5]
# print(max(l))
# dic = {'age1':18,'age2':10}
# print(max(dic))
# print(max(dic.values()))
# print(max(zip(dic.values(),dic.keys())))#结合zip比较value。出key
#1、max函数处理的是可迭代对象,相当于一个for循环取出各个元素进行比较,注意,不同类型之间不能进行比较
#2、每个元素间进行比较,是从每个元素的每一个位置依次比较,如果这一个位置分出大小,后面的就不需要比较了,直接得出这两元素的大小。
# people = [
# {"name":"alex","age":1000},
# {"name":"wupeiqi","age":10000},
# {"name":"zhazha","age":9000},
# {"name":"wangqiyuan","age":18}
# ]
# print(max(people,key=lambda dic:dic["age"]))
# ret=[]
# for item in people:
# ret.append(item["age"])
# print(ret)
# max(ret)
|
0fb118912300df21ec01aec163395fe8fe733a51 | yanlingsishao/study | /ATM/ATM/atm_back/main.py | 544 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月9日
@author: WangQiyuan
'''
import login
def Exit():
print("程序退出")
exit()
def Main():
msg='''
欢迎来到:
1:登录
2:退出'''
msg_dic = {
"1":login.login_user,
"2":Exit,
}
while True:
print(msg)
choice = input("请输入你的选项:").strip()
if choice not in msg_dic.keys(): continue
res=msg_dic[choice]()
if __name__ == "__main__":
Main()
|
4f1518f7984890d31abf3f9e0f3a96aa2f6ee478 | yanlingsishao/study | /day1/three_lv menu.py | 2,040 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Created on 2017年5月9日
@author: WangQiyuan
'''
dic = {
'山西省':{'晋城市':['高平县','泽州县','沁水县'],'长治市':['长子县']},
'河北省': {'保定市': ['雄县']},
}
e = list(dic['山西省'].keys())
f = list(dic['河北省'].keys())
e1 = list(dic["山西省"]["晋城市"])
e2 = list(dic["山西省"]["长治市"])
f1 = list(dic['河北省']["保定市"])
n = 0
def province_inf(province):
y = list(dic[province].keys())[0:]
return y
province_inf("山西省")
while True:
print("全国省份:")
for i in enumerate(dic):
index = i[0]
P_list = i[1]
print(P_list)
x = input("please input your Province:")
if x == '山西省':
print (e[0],e[1])
if n == 0:
while True:
C1 = input("please input your City(x:返回上级,q:退出):")
if C1 == '晋城市':
print (e1[0],e1[1],e1[2])
elif C1 == '长治市':
print (e2[0])
elif C1 == 'q':
n = 1
break
elif C1 == 'x':
break
else:
print("没有查询到此城市,继续输入")
if n == 1:
break
else:
continue
elif x == '河北省':
print (f[0])
if n == 0:
while True:
C2 = input("please input your City:")
if C2 == "保定市":
print (f1[0])
elif C2 == 'q':
n = 1
break
elif C2 == 'x':
break
else:
print("没有查询到此城市,继续输入")
if n == 1:
break
else:
continue
elif x == 'q':
break
else:
print("数据库未查出该省,退出输入q,查询请重新输入")
#
|
0d7f58aa6c9cc2d4c4a58ad2475ad2f74d35059b | zhankun/python-orm | /Four.py | 736 | 3.703125 | 4 | import fileinput
# w = open("/Users/zhankun/Desktop/test.txt")
with open("/Users/zhankun/Desktop/test.txt") as file:
while True:
line = file.readline()
if not line:
break
print(line)
print("-----------我是万恶的分割线------------")
with open("/Users/zhankun/Desktop/test.txt") as file:
for line in file.readlines():
print(line)
print("-----------我是万恶的分割线------------")
# 使用fileinput实现延迟迭代,减少内存占用
for line in fileinput.input("/Users/zhankun/Desktop/test.txt"):
print(line)
print("-----------我是万恶的分割线------------")
with open("/Users/zhankun/Desktop/test.txt") as f:
for line in f:
print(line) |
faff1cec10dcababbf86d53ae4d01d8e1dda8b5c | jalilGJ/Ordenamiento_Mezcla | /Ordenamiento_Mezcla.py | 2,228 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 21:16:52 2021
@author: jalil
"""
import random # se importa la libreria para poder generar numeros aleatorios
def merge_sort(data):
mid = len (data) //2 # divide la mitad del arreglo
if len(data)> 1: #si la longitud del data es mayor a uno
L=data[mid:] # darreglo obteniendo los valores que se encuentran en la izquierda
R=data[:mid] # los valores que se encuentran en la derecha del arreglo
data.clear()#refreash
# se hace dos llamadas recursivas
merge_sort(L) # arreglo de la izquierda
merge_sort(R) # arreglo de la derecha esto va ser que se dividadan
#hasta que todos los elemntos sean igual que uno
#Metodo para hacer el ordenamineto por mezcla
while len(L)>0 and len(R)>0:# longitud del arreglo de la izquierda sea mayor a cero y la longitud
#del arreglo de la derecha sea mayor a cero
if L[0]< R[0]: #si el elemento que se encuentra en la posicion cero del arreglo de la izquierda
#es menor al elemento que se encuentra en la posicion cero del arreglo de la derecha
data.append(L.pop(0)) # agrega al arreglo data el elemento que esta en la posicion cero
else:# si no
data.append(R.pop(0)) # agrega el elemento de la posicion cero del arreglo
while len(L) > 0: # cuando la longitud del lado izquierda sea mayor a cero va a agregar el arreglo data el elemento que se encuentre la posicion cero
data.append(L.pop(0))#agrega
while len (R) > 0: # pasa con el arreglo de la derecha
data.append(R.pop(0))
return data # retorna la lista ordenada
print (" \n ALGORITMO DE ORDENAMIENTO EXTERNO MEZCLA\n")
data =[random.randint(-50, 50) for i in range(20)] #se genera un arreglo, un dato a la cual estoy generando.
print(f"arreglo original:{data} \n") # se imprime el arreglo original para que se pueda notar cuales son los elementos que se ordenaron
x=merge_sort(data)
print(f"Arreglo ordenado:{x} \n") # imprimir el arreglo ordenado
|
5a978d96695e8673b6e0d615957c9751288417cb | CheeseTheMonkey/AdventOfCode | /2019/day22.py | 1,857 | 3.6875 | 4 |
def new_stack(deck):
return deck[::-1]
def cut(deck, index):
return deck[index:] + deck[:index]
def deal_with_increment(deck, increment):
new_deck = [False] * len(deck)
index = 0
for card in deck:
new_deck[index] = card
index += increment
index = index % len(deck)
return new_deck
def shuffle(deck, instructions):
for instruction in instructions:
if instruction == "deal into new stack":
deck = new_stack(deck)
elif instruction.startswith("cut"):
deck = cut(deck, int(instruction.split()[-1]))
elif instruction.startswith("deal with increment"):
deck = deal_with_increment(deck, int(instruction.split()[-1]))
return deck
if __name__ == '__main__':
instructions = [
'deal with increment 7',
'deal into new stack',
'deal into new stack',
]
assert(shuffle(list(range(10)), instructions) == [0, 3, 6, 9, 2, 5, 8, 1, 4, 7])
instructions = [
'cut 6',
'deal with increment 7',
'deal into new stack',
]
assert(shuffle(list(range(10)), instructions) == [3, 0, 7, 4, 1, 8, 5, 2, 9, 6])
instructions = [
'deal into new stack',
'cut -2',
'deal with increment 7',
'cut 8',
'cut -4',
'deal with increment 7',
'cut 3',
'deal with increment 9',
'deal with increment 3',
'cut -1',
]
assert(shuffle(list(range(10)), instructions) == [9, 2, 5, 8, 1, 4, 7, 0, 3, 6])
instructions = [a.strip() for a in open('day22.input').readlines()]
print('Part 1:', shuffle(list(range(10007)), instructions).index(2019))
# Part 2
deck = list(range(119315717514047))
for _ in range(101741582076661):
deck = shuffle(deck, instructions)
print("Part 2:", deck[2020])
|
0408db7520cc0a1805cf0b570d550743e27b7b71 | 1ynden/CS451-FinalProject-AIsnake | /snake.py | 2,899 | 3.59375 | 4 | from pygame import display, time, draw, QUIT, init, KEYDOWN, K_LEFT, K_RIGHT, K_UP, K_DOWN, K_q
from random import randint
import pygame
from numpy import sqrt
init()
done = False
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
cols = 30
rows = 30
width = 600
height = 600
blockW = width/cols
blockH = height/rows
dir = 1
dis = display.set_mode([width, height])
display.set_caption("Snake")
clock = time.Clock()
font_style = pygame.font.SysFont("consolas", 25)
class Space:
def __init__(self, x, y):
self.x = x
self.y = y
grid = [[Space(i, j) for j in range(cols)] for i in range(rows)]
snake = [grid[rows//2][cols//2]]
food = grid[randint(0, rows-1)][randint(0, cols-1)]
head = snake[-1]
game_over = False
while not done:
clock.tick(12)
dis.fill(BLACK)
while game_over == True:
dis.fill(WHITE)
mesg = font_style.render("Game Over! Press Q to quit!", True, RED)
dis.blit(mesg, [width / 6, height / 3])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
for event in pygame.event.get():
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
if event.key == K_UP and not dir == 0:
dir = 2
elif event.key == K_LEFT and not dir == 1:
dir = 3
elif event.key == K_DOWN and not dir == 2:
dir = 0
elif event.key == K_RIGHT and not dir == 3:
dir = 1
if dir == 0:
if(head.y+1 >= cols):
game_over = True
else:
snake.append(grid[head.x][head.y + 1])
elif dir == 1:
if(head.x+1 >= rows):
game_over = True
else:
snake.append(grid[head.x + 1][head.y])
elif dir == 2:
if(head.y-1 < 0):
game_over = True
else:
snake.append(grid[head.x][head.y - 1])
elif dir == 3:
if(head.x-1 < 0):
game_over = True
else:
snake.append(grid[head.x - 1][head.y])
head = snake[-1]
if head.x >= rows or head.x < 0 or head.y >= cols or head.y < 0:
game_over = True
for x in snake[:-1]:
if x == head:
game_over = True
if head.x == food.x and head.y == food.y:
while 1:
food = grid[randint(0, rows - 1)][randint(0, cols - 1)]
if not (food in snake):
break
else:
snake.pop(0)
for seg in snake:
draw.rect(dis, GREEN, [seg.x*blockH, seg.y*blockW, blockH, blockW])
draw.rect(dis, RED, [food.x*blockH, food.y*blockW, blockH, blockW])
display.flip() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.