blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ab7cfe6d79b6424074d6acc8b6884f25ba35c613 | Densatho/Python-2sem | /aula3/ex2.py | 339 | 3.734375 | 4 | volume_mensal = float(input("Insira o volume de vendas mensal: "))
if volume_mensal <= 5000:
comissao = 2 / 100
elif volume_mensal <= 10000:
comissao = 5 / 100
elif volume_mensal <= 1200:
comissao = 7 / 100
else:
comissao = 9 / 100
print(f"O valor da comissão é R${round(comissao * volume_mensal, 2):.2f}")
|
b0488b571dc4fe6b169be0bf6ecb612006bcc897 | DahlitzFlorian/article-introduction-to-itertools-snippets | /itertools_zip_longest.py | 160 | 3.71875 | 4 | from itertools import zip_longest
a = [1, 2, 3]
b = ["One", "Two"]
result1 = list(zip(a, b))
result2 = list(zip_longest(a, b))
print(result1)
print(result2)
|
18a64cd20d80d99f407c5a8de0e7c43102a6ab53 | DahlitzFlorian/article-introduction-to-itertools-snippets | /itertools_accumulate.py | 302 | 4.0625 | 4 | from itertools import accumulate
from operator import mul
numbers = [1, 2, 3, 4, 5]
result1 = accumulate(numbers)
result2 = accumulate(numbers, mul)
result3 = accumulate(numbers, initial=100)
print(f"Result 1: {list(result1)}")
print(f"Result 2: {list(result2)}")
print(f"Result 3: {list(result3)}")
|
8df3ddd0971c52ea5a918ab28b2a3ef0ac82f92c | EgorBodrov/task_6_bomberman_sapper | /sapper.py | 6,887 | 3.5625 | 4 | """
Script imitates pure console version of Sapper.
According to Wikipedia, you win only when all bombs are marked with a flag.
Copyright by Bodrov Egor, 20.09.2021.
"""
import os
import sys
import random
import datetime
import time
from sapper_input import game_input
# The signs, which are used in field presentation
flag_sign = '?' # Marked cells
boomed_sign = '!' # If you picked a bomb
class Sapper:
"""
Class contains all initial data and provides game functions.
Attributes:
- rows (int): Number of rows in game field
- columns (int): Number of columns in game field
- bombs_number (int): Number of bombs number
- field: 2D-list that is shown for user
- bombs: 2D-list that contains bombs location and number of neighbors
- start_time: starting timer
- result_file: file with match data
- original_stdout: save stdout to choose between console and file
Methods:
- generate_bombs():
Randomly generate bombs on the field.
- win_condition() -> bool:
Check are all bombs were marked with a flag.
- show():
Print field as convinient table.
- count_bombs():
Count the number of neibors-bombs for each cell.
- open(row, column):
Open cell in specific row and column.
- set_flag(row, column):
Set flag in specific row and column.
- save_step(text=None):
Save text or field in file
- play():
Main method, calls other methods.
"""
def __init__(self, rows, columns, bombs_number):
self.rows = rows
self.columns = columns
self.bombs_number = bombs_number
self.field = [['x'] * self.columns for x in range(self.rows)]
self.bombs = [[0] * self.columns for x in range(self.rows)]
self.start_time = time.time()
self.result_file = open(
f'{datetime.datetime.now().strftime(r"%d-%m-%y_%H-%M-%S_match.txt")}',
mode='a+'
)
self.original_stdout = sys.stdout
def generate_bombs(self) -> None:
generated = 0
while generated < self.bombs_number:
row = random.randint(0, self.rows - 1)
column = random.randint(0, self.columns - 1)
if self.bombs[row][column] == 0:
self.bombs[row][column] = -1
generated += 1
def win_condition(self) -> bool:
pairs = list(zip(sum(self.field, []), sum(self.bombs, [])))
if pairs.count((flag_sign, -1)) == self.bombs_number:
return True
return False
def show(self):
print('\n Y')
for i in range(self.rows, 0, -1):
print(f' {i} ', end=' ') if i < 10 else print(f'{i} ', end=' ')
print(*self.field[self.rows - i], sep=' ')
print('\n ', end='')
for i in range(1, self.columns + 1):
print(f' {i}', end=' ') if i < 10 else print(f'{i}', end=' ')
print('X\n')
def count_bombs(self):
for i in range(self.rows):
for j in range(self.columns):
if self.bombs[i][j] > -1:
if i > 0 and self.bombs[i - 1][j] == -1:
self.bombs[i][j] += 1
if i > 0 and j < self.columns - 1 and self.bombs[i - 1][j + 1] == -1:
self.bombs[i][j] += 1
if j < self.columns - 1 and self.bombs[i][j + 1] == -1:
self.bombs[i][j] += 1
if j < self.columns - 1 and i < self.rows - 1 and self.bombs[i + 1][j + 1] == -1:
self.bombs[i][j] += 1
if i < self.rows - 1 and self.bombs[i + 1][j] == -1:
self.bombs[i][j] += 1
if i < self.rows - 1 and j > 0 and self.bombs[i + 1][j - 1] == -1:
self.bombs[i][j] += 1
if j > 0 and self.bombs[i][j - 1] == -1:
self.bombs[i][j] += 1
if i > 0 and j > 0 and self.bombs[i - 1][j - 1] == -1:
self.bombs[i][j] += 1
def open(self, row, column):
if row >= self.rows or column >= self.columns or row < 0 or column < 0 or \
self.field[row][column] != 'x':
return
if self.bombs[row][column] > 0:
self.field[row][column] = str(self.bombs[row][column])
elif self.bombs[row][column] == 0:
self.field[row][column] = '0'
self.open(row, column - 1)
self.open(row + 1, column - 1)
self.open(row + 1, column)
self.open(row + 1, column + 1)
self.open(row, column + 1)
self.open(row - 1, column + 1)
self.open(row - 1, column)
self.open(row - 1, column - 1)
def set_flag(self, row, column):
if self.field[row][column] == 'x':
self.field[row][column] = flag_sign
elif self.field[row][column] == flag_sign:
self.field[row][column] = 'x'
def save_step(self, text=''):
sys.stdout = self.result_file
if text == '':
self.show()
else:
self.result_file.write(text + '\n')
sys.stdout = self.original_stdout
def play(self) -> bool:
os.system('cls')
self.generate_bombs()
self.count_bombs()
while self.win_condition() is False:
self.show()
self.save_step()
row, column, action = game_input(self.rows, self.columns)
self.save_step(text=f'{column + 1} {self.rows - row} {action}\n')
if action == 'Open':
if self.bombs[row][column] == -1:
self.field[row][column] = boomed_sign
self.show()
print('YOU LOST!')
self.save_step(text='YOU LOST!\n')
break
self.open(row, column)
else:
self.set_flag(row, column)
else:
self.show()
self.save_step()
print('YOU WON!\n')
self.save_step(text='YOU WON!\n')
self.result_file.write(f'match duration: {time.time() - self.start_time} seconds\n')
self.result_file.write(f'Parameters: {self.rows} rows, {self.columns} columns, {self.bombs_number} bombs')
self.result_file.close()
print('\nWant to play one more time? (Y/n)')
answer = input()
if answer.lower() in ('y', 'yes', 'да'):
return True
else:
return False
|
dd4b29077279603558c9e505a7693fb2d97d51c4 | SamuelHalsey/Chapter6_Demo | /main.py | 9,949 | 3.671875 | 4 | # Mr. Jones
# This is a sample Python script Based on CH.6 material
# ASCII text generated with http://www.network-science.de/ascii/
# Donte Jones jones_donte@dublinschools.net
# IT Academy @ Emerald Campus
#
# Notes PYCHARM users: Use 'CTRL+/' keys to uncomment or comment any selected lines of code
import random
import jones
"""
8888888888 888 d8b
888 888 Y8P
888 888
8888888 888 888 88888b. .d8888b 888888 888 .d88b. 88888b. .d8888b
888 888 888 888 "88b d88P" 888 888 d88""88b 888 "88b 88K
888 888 888 888 888 888 888 888 888 888 888 888 "Y8888b.
888 Y88b 888 888 888 Y88b. Y88b. 888 Y88..88P 888 888 X88
888 "Y88888 888 888 "Y8888P "Y888 888 "Y88P" 888 888 88888P'
Functions allow you to breakup your code into more managable chunks
Programs that implement functions are easier to create and manage
Functions should do a specific task to keep them organized
*Functions in Python always need to be defined before they can be called!
"""
#
# # Functions begin with a definition
# def anAmazingFunction():
# """ This is referred to as a Docstring it is optional but can help explain the function """
# print("This is the body of the method")
# print("The individual tasks your function should preform go here")
#
# # The Method can be used or 'Called' by using its name followed by parenthesis
# anAmazingFunction()
"""
d8888 888 888 888 d8b
d88888 888 888 888 Y8P
d88P888 888 888 888
d88P 888 88888b. .d8888b 888888 888d888 8888b. .d8888b 888888 888 .d88b. 88888b.
d88P 888 888 "88b 88K 888 888P" "88b d88P" 888 888 d88""88b 888 "88b
d88P 888 888 888 "Y8888b. 888 888 .d888888 888 888 888 888 888 888 888
d8888888888 888 d88P X88 Y88b. 888 888 888 Y88b. Y88b. 888 Y88..88P 888 888
d88P 888 88888P" 88888P' "Y888 888 "Y888888 "Y8888P "Y888 888 "Y88P" 888 888
By using and creating functions you are practicing one of the concepts
of OOP or Object Oriented Programming
You are practicing what is known as Abstraction
Abstraction is not needing to know the details of creation but only needing to
know how to use it
"""
# function that reports the current time
# How does it actually work? We don't necessarily need to know through 'Abstraction'
# We just need to know how to use it
# import time
#
# # Prints your system time
# def whatTimeIsIt(): # Defines the function
# """ Displays the system time""" # Docstring, this is optional
# print(time.ctime()) # Function Body
#
#
# whatTimeIsIt() # Calling the function to get a result
"""
8888888b. 888
888 Y88b 888
888 888 888
888 d88P .d88b. 888888 888 888 888d888 88888b.
8888888P" d8P Y8b 888 888 888 888P" 888 "88b
888 T88b 88888888 888 888 888 888 888 888
888 T88b Y8b. Y88b. Y88b 888 888 888 888
888 T88b "Y8888 "Y888 "Y88888 888 888 888
Receiving and Returning Values
Our functions provide ways to communicate with the rest of our code
This is done through receiving values through 'Parameters'
We can return information to the caller of the method through a 'Return' value
"""
#
# # Receive and Return
# # Demonstrates parameters and return values
#
#
# def display(message): # Our function takes one argument in the parameter defined as message
# print(message) # Data entered here will be accessible within the body of the function
#
#
# def give_me_five(): # Function takes no arguments
# five = 5
# return five # Returns the value of 'five' which is the integer '5'
#
#
# def ask_yes_no(question): # Takes 1 argument
# """Ask a yes or no question."""
# response = None # No value set
# while response not in ("y", "n"):
# response = input(question).lower() # alters the value of response to exit the loop
# return response # the value of 'response' is 'Returned' to the caller
#
#
# # main
# display("Here's a message for you.\n")
#
#
# number = give_me_five()
# print("Here's what I got from give_me_five():", number)
#
# answer = ask_yes_no("\nPlease enter 'y' or 'n': ")
# print("Thanks for entering:", answer)
#
# input("\n\nPress the enter key to exit.")
#
# # Birthday Wishes
# # Demonstrates keyword arguments and default parameter values
#
#
# # positional parameters
# def birthday1(name, age):
# print("Happy birthday,", name, "!", " I hear you're", age, "today.\n")
#
#
# # parameters with default values
# def birthday2(name = "Jackson", age = 1):
# print("Happy birthday,", name, "!", " I hear you're", age, "today.\n")
#
#
# birthday1("Jackson", 1)
# birthday1(1, "Jackson")
# birthday1(name = "Jackson", age = 1)
# birthday1(age = 1, name = "Jackson")
#
# birthday2()
# birthday2(name = "Katherine")
# birthday2(age = 12)
# birthday2(name = "Katherine", age = 12)
# birthday2("Katherine", 12)
#
# input("\n\nPress the enter key to exit.")
"""
8888888888 888 888 d8b
888 888 888 Y8P
888 888 888
8888888 88888b. .d8888b 8888b. 88888b. .d8888b 888 888 888 8888b. 888888 888 .d88b. 88888b.
888 888 "88b d88P" "88b 888 "88b 88K 888 888 888 "88b 888 888 d88""88b 888 "88b
888 888 888 888 .d888888 888 888 "Y8888b. 888 888 888 .d888888 888 888 888 888 888 888
888 888 888 Y88b. 888 888 888 d88P X88 Y88b 888 888 888 888 Y88b. 888 Y88..88P 888 888
8888888888 888 888 "Y8888P "Y888888 88888P" 88888P' "Y88888 888 "Y888888 "Y888 888 "Y88P" 888 888
888
888
888
Understanding Visibility & Encapsulation
By default Python does not make you specify the visibility of variables
The first thing we must know is any variable created outside of a loop, or function is considered to be
in the 'Global' scope this variable can be accessed and changed from anywhere
'Encapsulation' is a way of hiding the details much in the same way we hide
variables in functions from the rest of the program
No variable including parameters of a function can be accessed outside of a function
"""
# # Global Reach
# # Demonstrates global variables
#
# def read_global():
# print("From inside the local scope of read_global(), value is:", money)
#
#
# def shadow_global():
# money = -10
# print("From inside the local scope of shadow_global(), value is:", money)
#
#
# def change_global():
# global money
# money = -10
# print("From inside the local scope of change_global(), value is:", money)
#
#
# def change_global_and_return_it():
# global money
# money *= 100
# return money
#
#
# # main
# # value is a global variable because we're in the global scope here
# money = 10
# print("In the global scope, value has been set to:", money, "\n")
#
# read_global()
# print("Back in the global scope, value is still:", money, "\n")
#
# shadow_global()
# print("Back in the global scope, value is still:", money, "\n")
#
# change_global()
# print("Back in the global scope, value has now changed to:", money)
#
#
# change_global_and_return_it()
# newMoney = change_global_and_return_it() # Catching the results returned from a function and
# # storing them in a variable 'newMoney'
# print("This is the value returned by the 'change_global_and_return_it()' function: ", newMoney)
#
# input("\n\nPress the enter key to exit.")
"""
888b d888 888 888
8888b d8888 888 888
88888b.d88888 888 888
888Y88888P888 .d88b. .d88888 888 888 888 .d88b. .d8888b
888 Y888P 888 d88""88b d88" 888 888 888 888 d8P Y8b 88K
888 Y8P 888 888 888 888 888 888 888 888 88888888 "Y8888b.
888 " 888 Y88..88P Y88b 888 Y88b 888 888 Y8b. X88
888 888 "Y88P" "Y88888 "Y88888 888 "Y8888 88888P'
Software Reuse & Creating Modules
By creating our own functions we can reuse code across projects
We can also create our own modules to store/ organize functions we commonly use
Once a module is imported it becomes an object in our code therefore we use the
same '.' dot notation as with any other object see example below
"""
#
# import jones # This is another python file named jones.py
# # It has several functions defined in it I would like to use
#
# jones.hello() # Dot notation tells the interpreter where to find the 'hello()' function
#
# # Catching the returned results in the 'average' variable for use by the main application
# average = jones.getAverage2()
#
# # Main application using the results returned by the 'getAverage2()' function
# print(average)
#
# jones.countDownTimers() # Uses default value defined in the function definition
# jones.countDownTimers(10) # Uses value passed as an argument by the user
|
9bb53c56b3a389ad92646729a325fb40ad009de0 | smkbarbosa/uriJudge | /1004/prod_1004.py | 797 | 4.03125 | 4 | """
Leia dois valores inteiros. A seguir, calcule o produto entre estes dois valores e atribua esta operação à variável PROD. A seguir mostre a variável PROD com mensagem correspondente.
Entrada
O arquivo de entrada contém 2 valores inteiros.
Saída
Imprima a variável PROD conforme exemplo abaixo, com um espaço em branco antes e depois da igualdade. Não esqueça de imprimir o fim de linha após o produto, caso contrário seu programa apresentará a mensagem: “Presentation Error”.
https://www.urionlinejudge.com.br/judge/pt/problems/view/1004
"""
def prod(x, y):
PRODUTO = x * y
return PRODUTO
def main():
x = int(input())
y = int(input())
PRODUTO = prod(x, y)
print("PROD = " + format(PRODUTO))
if __name__ == "__main__":
main()
|
54bc1e3dfedf368fdee288918cd381129f093c6e | mlen1990/Coding-Challenges | /challenge2/jetstream.py | 2,514 | 3.890625 | 4 | #! /usr/bin/env python
import sys
import util
import datetime
input_file = open(sys.argv[1], 'r')
base = int(input_file.readline()) # Get the base weight
line = input_file.readline()
edges = [] # Store the edges from the input file in a list
distance = 0 # The distance the bird needs to travel
print "Begin Parsing Input File"
while line:
nums = line.split() # [start, end, weight]
num1 = int(nums[1])
distance = max(num1, distance) # Keep track of the maximum travel distance
edges.append((int(nums[0]), num1, int(nums[2])))
line = input_file.readline()
input_file.close()
print "Finished Parsing Input File"
print "Constructing Graph"
graph = []
for i in range(0, distance + 1):
graph.append(util.Vertex(i))
for edge in edges:
graph[edge[0]].add_edge(util.Edge(graph[edge[0]], graph[edge[1]], edge[2], original=True))
print "Finished Constructing Graph"
print "Finding the Optimal Sequence of Jetstreams"
solution = []
expanded = set()
frontier = util.PriorityQueue()
start = graph[0] # Start at node 0
expanded.add(start)
successors = start.get_edges()
if len(successors) == 0:
frontier.push([util.Edge(graph[0], graph[1], base)], base)
else:
for successor in successors:
frontier.push([successor], successor.weight)
while not frontier.isEmpty():
priority, l = frontier.pop()
node = l[-1]
if node.end == graph[distance]:
for item in l:
if item.original:
solution.append((item.start.name, item.end.name))
print solution
print "Minimum Total Energy: " + str(priority)
break
elif graph[node.end.name] in expanded:
print len(frontier)
continue
else:
expanded.add(graph[node.start.name])
successors = node.end.get_edges()
if not node.original:
l.pop()
if len(successors) == 0:
if graph[node.end.name + 1] not in expanded:
successor = util.Edge(graph[node.end.name], graph[node.end.name + 1], base)
new_priority = priority + successor.weight
l.append(successor)
frontier.push(l, new_priority)
elif len(successors) == 1:
if graph[successors[0].end.name] not in expanded:
successor = successors[0]
new_priority = priority + successor.weight
l.append(successor)
frontier.push(l, new_priority)
else:
for successor in successors:
if graph[successor.end.name] not in expanded:
copy = l[:]
new_priority = priority + successor.weight
copy.append(successor)
frontier.push(copy, new_priority)
|
38f13e72d5f0d6a38c7782f9c909e29ae4c022ab | liuwei0376/python3_toturial | /com/david/tutorial/6-oop/6.4-getObjectInfo.py | 3,665 | 3.984375 | 4 | #-*- coding:utf-8 -*-
'''
一、获取对象信息
'''
print('-----------------一、获取对象信息------------------')
# 1.1 使用type()获取对象的类型
print('-----------------1.使用type()获取对象的类型------------------')
print(type(123))
print(type('str'))
print(type(None))
#如果一个变量指向函数或者类,也可以用type()判断
print(type(abs))
class Animal(object):
def run(self):
print('Animal is running...')
a = Animal()
print(type(a))
#type()函数返回的是Class类型,如需要比较2个变量的type类型是否相同:
print(type(123)==type(456))
print(type(0376)==int)
print(type('abc')==type('123'))
print(type('abc')==str)
print(type('abc')==type(123))
#判断基本类型可以直接写int,str等,如果要判断一个对象是否是函数怎么办?
print('-----------------判断基本类型可以直接写int,str等,如果要判断一个对象是否是函数怎么办?------------------')
import types
def my_fn():
pass
print(type(my_fn) == types.FunctionType)
print(type(abs) == types.BuiltinFunctionType)
print(type(lambda x:x*x)==types.LambdaType)
print(type(x for x in (1,10)) == types.GeneratorType)
'''
二、使用isinstance()
'''
print('-----------------使用isinstance()------------------')
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Eat bone')
class Husky(Dog):
def run(self):
print('Husky is running...')
a = Animal()
d = Dog()
h = Husky()
print(isinstance(h,Husky))
print(isinstance(h,Dog))
print(isinstance(h,Animal))
print(isinstance(d,Dog) and isinstance(d,Animal))
print(isinstance(d,Husky))
print('-----------------能用type判断的基本类型也可以用isinstance()判断------------------')
print(isinstance('a',str))
print(isinstance(123,int))
print(isinstance(b'a',bytes))
print('-----------------还可以判断一个变量是否为某些类型中的一种------------------')
print(isinstance([1,2,3],(list, tuple)))
print(isinstance((1,2,3),(list, tuple)))
'''
三、获取对象信息
'''
print('-----------------三、获取对象信息------------------')
#如果要获取一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含
#字符串的list,比如获取一个str的所有属性和方法
print(dir('abc'))
#len()内部 ,自动调用该对象的__len__方法,以下代码等价:
print(len('abc'))
print('abc'.__len__())
#自己写的类,如果也想用len(myObj)的话,就重写__len__()方法:
class MyDog(object):
def __len__(self):
return 100
dog = MyDog()
print(len(dog))
print(len('abcde'))
print('-----------------配合getattr()/setattr()/hasattr(),'
'可以直接操作一个对象的状态------------------')
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
print('hasattr(obj,\'x\'): %s' % hasattr(obj,'x'))
print('obj.x : %s' % obj.x)
print('hasattr(obj,\'y\'): %s' % hasattr(obj,'y'))
setattr(obj,'y',20)
print('hasattr(obj,\'y\'): %s' % hasattr(obj,'y'))
print('obj.y : %s' % obj.y)
print('getattr(obj,\'y\'): %s' % getattr(obj,'y'))
#可以传入一个default参数,如果属性不存在,则返回默认值
print(getattr(obj,'z',404))
print('-----------------获取对象的方法------------------')
print(hasattr(obj,'power'))
print(getattr(obj,'power'))
#获取属性'power'并赋值到变量fn
fn = getattr(obj,'power')
print(fn)
#调用fn与调用obj.power()是一样的
print(fn()) |
5334fa0ee22d03f6dcab4296c590217e6d6ca2e7 | liuwei0376/python3_toturial | /com/david/tutorial/test.py | 2,657 | 3.796875 | 4 | #-*- coding:utf-8 -*-
if True:
print 'true'
print 'True'
else:
print 'false'
print 'False'
days = ['monday',
'tuesday','wednesday']
word = 'word'
sentense = "这是一个句子"
paragraph = """这是一个段落。
包含了多哦语句"""
# 这是一个注释
'''
多行注释
'''
"""
双引号凡是的杜航注释
"""
#raw_input('\n\nPress the entry key to exit:')
# 同一行显示多条语句
import sys; x = 'david'; sys.stdout.write(x + '\n')
x = 'a'
y = 'b'
print x
print y
# 不换行输出
print '-------------------'
print x,
print y,
print '-------------------'
age = 30
if age <15:
print 'child'
elif age >=15 and age <=35:
print 'youth'
else:
print 'older'
a=b=c=1
print a,b,c
a,b,c=1,2,'david'
print a,b,c
# python中五种标准数据类型
# Numbers(数字)
# String(字符串)
# List(列表)
# Tuple(元祖)
# Dictionary(字典)
var1=1
var2=2
del var1,var2
#python中数字有4种
#int long float complex(复数)
longtype=-0x19323L
complex_type = 4.53e-7j
#字符串
s = 'ilovepython'
print s[1:5]
print '---------------------'
str = "Hello World!"
print str
print str[0]
print str[2:5]
print str[2:]
print str * 2
print str + "TEST"
# python 列表
list = ['liujingyang',2,'2015-07-29',376,92]
tinylist = [30, 'lige']
print list
print list[0]
print list[1:3]
print tinylist *2
print list +tinylist
#python 元组
#类似于list,内部用逗号隔开,不能二次赋值,相当于只读列表
tuple = ('liujingyang',2,'2015-07-29',376,92)
tinytuple = (30, 'lige')
print tuple
print tuple[0]
print tuple[1:3]
print tinytuple * 2
print tuple + tinytuple
print '--------------'
# 字典
#类比java hashMap,无序,通过键来存取
dict = {}
dict['one'] = 'This is one'
dict[2] = 'This is two'
tinydict = {'name': 'john', 'code':3344, 'dept':'it'}
print dict['one']
print dict[2]
print tinydict
print tinydict['name']
print tinydict['dept']
print tinydict.keys()
print tinydict.values()
#python数据类型转换
print int('123')
print long('4567')
print float('4567')
print complex(2,3)
# print tuple(1,2,3)
# print list(4,2,3)
print hex(1)
print 10**20
print 9//2
print 9.0//2
a = 20
b = 20
if (a is b):
print "1 - a 和 b 有相同的标识"
else:
print "1 - a 和 b 没有相同的标识"
if (a is not b):
print "2 - a 和 b 没有相同的标识"
else:
print "2 - a 和 b 有相同的标识"
# 修改变量 b 的值
b = 30
if (a is b):
print "3 - a 和 b 有相同的标识"
else:
print "3 - a 和 b 没有相同的标识"
if (a is not b):
print "4 - a 和 b 没有相同的标识"
else:
print "4 - a 和 b 有相同的标识" |
2ff1b9d0740909e080a767a39603a6e557a98b3c | liuwei0376/python3_toturial | /com/david/tutorial/1-base/1.5-loop.py | 980 | 4.0625 | 4 | #-*- coding:utf-8 -*-
##循环
# 1. for x in ... 循环是把每个元素代入变量x,然后执行缩进块的语句
names = ['David','Lily','Lucy']
for n in names:
print(n)
# 例子:计算 1+2+3。。。。+10_1-spider
sum1 = 0
for n in (1,2,3,4,5,6,7,8,9,10):
sum1 += n
print('sum1 is: ',sum1)
sum2 = 0
for n in [1,2,3,4,5,6,7,8,9,10]:
sum2 += n
print('sum1 is: ',sum2)
print(list(range(1,101,1)))
sum3 = 0
for n in list(range(1,101,1)):
sum3 += n
print('sum3 is: ',sum3)
# 2. 使用while循环
num=99;sum4=0
while num>0:
sum4+=num
num = num -2
print('num=',num,', sum4=',sum4)
print'num=',num,', sum4=',sum4
print('sum4 = ',sum4)
# 3. break 语句可以直接退出循环,contine可以提前结束本轮循环,并直接开始下一轮循环。
# 这两个都必须配合if语句使用
n = 0
while n<10:
n+=1
if n> 3:
break;
print(n)
n = 0
while n<10:
n+=1
if n%2 == 0:
continue;
print(n)
|
603e12a667b8908776efbfef8d015c5e12b390c8 | Super1ZC/PyTricks | /PyTricks/use_dicts_to_emulate_switch_statements.py | 761 | 4.375 | 4 | def dispatch_if(operator,x,y):
"""This is similar to calculator"""
if operator == 'add':
return x+y
elif operator == 'sub':
return x-y
elif operator == 'mul':
return x*y
elif operator == 'div':
return x/y
else:
return None
def dispatch_dict(operator,x,y):
"""Using anonymous function lambda to display."""
return{
'add':lambda: x+y,
'sub':lambda: x-y,
'mul':lambda: x*y,
#dict.get function,return None when the operator
#is not key in dict
'div':lambda: x/y,}.get(operator,lambda:None)()
print(dispatch_if('mul',2,8))
print(dispatch_dict('mul',2,8))
print(dispatch_if('unknown',2,8))
print(dispatch_dict('unknown',2,8))
|
a6e335092167617a97d41e84d33dd70fe4ea81b1 | hc973591409/spider | /HTTPerro.py | 1,086 | 3.875 | 4 | # 异常错误处理
import urllib.request
import urllib.error
# 没有网络连接
# 服务器连接失败
# 找不到指定的服务器
def main1():
# 构建一个不存的站点请求
request = urllib.request.Request("http://www.ajkfhafwjqh.com")
try:
# 请求站点,设置超时时间
urllib.request.urlopen(request,timeout=5)
except urllib.error.URLError as err:
# <urlopen error timed out>
# 这样就能捕获错误类型
print(err)
def main():
# 构建一个不存的站点请求
request = urllib.request.Request("http://www.ajkfhafwjqh.com")
try:
# 请求站点,设置超时时间
urllib.request.urlopen(request)
except urllib.error.HTTPError as err:
# <urlopen error timed out>
# 这样就能捕获错误类型
print(err)
print(err.code)
# <urlopen error [WinError 10060]
# 由于连接方在一段时间后没有正确答复或连接的主机
# 没有反应,连接尝试失败。>
if __name__ == '__main__':
main() |
ee2183047032dc318e1218524722d9a0a4fe5540 | ozkansari/python_programlama | /8_1_range.py | 374 | 3.890625 | 4 | ogrenciler = [ 'Ali' , 'Ahmet', 'Ayse', 'Fatma' ]
print("Dongu Yontem-1:")
for ogrenci in ogrenciler:
print('Merhaba ', ogrenci)
print("Dongu Yontem-2:")
for i in range(len(ogrenciler)):
print((i+1) , ' -) Merhaba ', ogrenciler[i])
print("Dongu Yontem-3:")
i = 0
while i < len(ogrenciler):
print((i+1) , ' -) Merhaba ', ogrenciler[i])
i+=1
|
1af51d9ed56217484ab6060fc2f36ee38e9523df | rgvsiva/Tasks_MajorCompanies | /long_palindrome.py | 560 | 4.21875 | 4 | #This was asked by AMAZON.
#Given a string, find the longest palindromic contiguous substring.
#if there are more than one, prompt the first one.
#EX: for 'aabcdcb'-->'bcdcb'
main_St=input("Enter the main string: ")
st=main_St
palindrome=[st[0]]
while len(st)>1:
sub=''
for ch in st:
sub+=ch
if (sub==sub[::-1]) and (sub not in palindrome) and (len(sub)>len(palindrome[-1])):
palindrome=[sub]
st=st[1:]
print ('Longest palindromic substring: "',palindrome[0],'" at index-',main_St.index(palindrome[0]))
|
d5bfab7278d16ed336821acfe79d8ec77afda038 | neosoumik/pythonlab | /6c.py | 161 | 3.734375 | 4 | txt = ["hello", "hi", "welcome", "oyo", "gmail", "high", "qq"]
count = 0
for x in txt:
if len(x) >= 2 and x[0] == x[-1]:
count = count+1
print(count) |
e58852b5b427d28faddafe379e4dcd4725a4247d | AIDARXAN/Python_apps_or_games | /Turtle Race/turtle_race.py | 754 | 3.765625 | 4 | from turtle import *
from random import randint
speed(10)
penup()
goto(-140, 140)
for step in range(15):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
a = Turtle()
a.color('red')
a.shape('turtle')
a.penup()
a.goto(-160, 100)
a.pendown()
b = Turtle()
b.color('blue')
b.shape('turtle')
b.penup()
b.goto(-160, 70)
b.pendown()
c = Turtle()
c.color('green')
c.shape('turtle')
c.penup()
c.goto(-160, 40)
c.pendown()
d = Turtle()
d.color('yellow')
d.shape('turtle')
d.penup()
d.goto(-160, 10)
d.pendown()
for turn in range(100):
a.forward(randint(1,5))
b.forward(randint(1,5))
c.forward(randint(1,5))
d.forward(randint(1,5))
|
7dfdc76333497d713fe12af7de6b8ed08adcb3ef | GandT/learning | /Python/season2/p035-036/p036.py | 324 | 3.625 | 4 | # coding: UTF-8
"""
2018.5.2
CSVファイルのリスト化
"""
import csv
def csv_matrix(name):
answer = []
with open(name, 'r') as f:
rdr = csv.reader(f)
for row in rdr:
for cell in row:
answer.append(int(cell))
return answer
print(csv_matrix("small.csv")) |
407b0dd45c54a709d6e653b2bc77bd5ca306a4a2 | GandT/learning | /Python/season2/p024-025/p025.py | 384 | 3.921875 | 4 | # coding: UTF-8
"""
2018.4.20
イテレータ関数
"""
def number_generator(x):
if (x%2):
return 3*x+1
else:
return x//2
def number_generator_generator():
yield number_generator(1)
yield number_generator(2)
yield number_generator(3)
yield number_generator(4)
yield number_generator(5)
for num in number_generator_generator():
print(num) |
304537407c871035ded6d5ad316973bf1a6169b2 | GandT/learning | /Python/season2/p003-006/p005.py | 501 | 3.6875 | 4 | # coding: UTF-8
"""
2018.4.6
二次方程式 ax^2+bx+c=0 に関して判別式を求める
"""
def det(a, b, c):
return b*b - 4*a*c
print( "ax^2 + bx + c = 0" )
a = 3
b = 2
c = 1
print( "a={} b={} c={}".format(a, b, c) )
print( "判別式 D={}".format(det(a, b, c)) )
a = 1
b = 2
c = 1
print( "a={} b={} c={}".format(a, b, c) )
print( "判別式 D={}".format(det(a, b, c)) )
a = 1
b = 4
c = 1
print( "a={} b={} c={}".format(a, b, c) )
print( "判別式 D={}".format(det(a, b, c)) )
|
78c17dc8b972e01ea7641e37fdcd4d35222ae513 | GandT/learning | /Python/season2/p015-016/p016.py | 987 | 4.28125 | 4 | # coding: UTF-8
"""
2018.4.13
指定された月の日数を返す(閏年を考慮)
"""
def day_of_month(year, month):
# 不正な月が指定された場合Noneを返す
if type(year) != int or type(month) != int or not(1 <= month <= 12):
return None
# 2月を除くハッシュテーブル(辞書)の作成
table = {
1: 31, 2: -1, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
}
# 年から2月の値を確定
table[2] = 29 if (year % 400 == 0) or ((year % 100 != 0) and (year % 4 == 0)) else 28
# テーブルから結果を返す
return table[month]
print( day_of_month( 1, 1) )
print( day_of_month(87346894238473687461, 3) )
print( day_of_month(1000,13) )
print( day_of_month(2001, 2) )
print( day_of_month(2004, 2) )
print( day_of_month(2100, 2) )
print( day_of_month(2000, 2) )
print( day_of_month(100.4, 3) )
print( day_of_month(1999, "アポカリプス") )
|
33402b99fe55e4dfd871fe51b5cb51c3c5c72f84 | GandT/learning | /Python/season2/p026-027/p026.py | 403 | 3.59375 | 4 | # coding: UTF-8
"""
2018.4.20
ソート済み配列の線形探索
"""
def list_search(ilist, iitem):
seq = 0
found = False
while ilist[seq] <= iitem:
if ilist[seq] == iitem:
found = True
else:
seq += 1
return found
testlist = [-20, -7, 0, 1, 2, 8, 13, 17, 19, 32, 42, 124]
print(list_search(testlist, 3))
print(list_search(testlist, 13))
|
ccbfa98f9132324148020eeadc038cd7b426efdf | GandT/learning | /Python/season2/p028/p028.py | 292 | 3.515625 | 4 | # coding: UTF-8
"""
2018.4.20
ユークリッド距離の計算
"""
import math
from functools import reduce
def distance(list1, list2):
return math.sqrt(reduce(lambda x,y : x+y, list( map(lambda x,y : (x - y)**2, list1, list2) ) ))
d = distance([1,2,4], [3, 0, 2])
print(d, d**2) |
4a46dd08004193a35be9de64a85d95f762b37eee | ykimbiology/kim2013-positional-bias | /src/epitopemapping/mappeptides.py | 8,692 | 3.78125 | 4 | #! /usr/bin/python
import sys
import time
import os
"""
Pseudocode programming process:
GOAL: To accurately map peptides onto proteins.
If needed, takes into account homologous relationship among source and target proteins.
(1) map_peptides: Given a list of (A) peptides, (B) target proteins and (C) similarity threshold,
retrieve all peptide:protein mappings.
(2) filter_results: If needed, filter the result to those that meet homologous relationship requirement.
(3) format_results: Return results.
#== Questions:
Q: Should partial peptide mapping be considered?
#== A list of data validations:
(1) Warning: Do all source antigens contain non-empty sequences?
(2) Error: Do all peptides use valid amino acids?
(3) Stats: How many peptides were mapped? Unmapped? And which peptides?
(4) Stats: Which proteins had hits? Which didn't?
(5) Making sure full length of peptides were mapped. # see blast results.
#== Data Structures
(1) Results: A text file containing [id_peptide] [id_protein] [similarities] etc.
#== Different techniques to map peptides:
INPUT: (1) A fasta file containing a list of peptides.
(2) A fasta file containing a list of source antigens.
(3) A fasta file containing a list of target antigens.
method_brute # Goes over one by one overlapping windows of peptides. Used to create benchmark set.
method_blast
method_muscle
#== Tests ==
(1) With respect to method_brute,how many mappings are retrieved by methodA?
"""
"""
Too many input variables. Take out some variables to at most 7 total.
Ideally:
INPUT:
fname_peptide_list_fasta
fname_source_antigens_blastdb
fname_target_antigens_blastdb
d_id_to_peptide
antigen_list # Target antigen list; Not sure why this is being used.
== pseudo programming method ==
1. map peptides to antigens.
2. If true, keep only best match for each peptide.
3. If true, keep only those mapping records that involve homologous source and target antigens.
"""
from algorithm.factory_filter_mapping import filter_mapping_unique_keep_ties, filter_mapping_by_homology_protein
report_time = lambda ti,tj, description: sys.stdout.write(' %8.2f seconds ' %(tj-ti,)+'\t'+description+'\n')
def map_peptides(fname_peptide_list,
fname_antigens_source,
fname_antigens_target,
d_peptides_info,
sim_cutoff_fraction=0.80,
enforce_antigen_homology=False,
filter_mapping=False,
method='blast_a',
debug=False):
"""
This version bypasses object creation; Simplify the process of mapping. Separate assigning weights. Make it work with other programs.
Design001: (1) Each algorithm returns mapping results in same format. (2) hobj used to filter results. (3) Group, reformat results.
Design002: (1) Each algorithm uses its own mapping results. (2) Same object is used to filter results using hobj.
"""
#== 1. Map peptides onto proteins:
(d_mapping, mappingAlgo) = map_peptides_selector(fname_peptide_list,
fname_antigens_target,
method=method,
sim_cutoff_fraction=sim_cutoff_fraction)
#== 1. Filter d_mapping to address multiple matches:
if filter_mapping==True:
d_mapping = filter_mapping_unique_keep_ties(d_mapping)
#== 2. Filter based on antigen-homology.
# Calculate homologous relationship between source and target antigens;
# Then filtering mapping results based on this homology data.
ti = time.time()
hobj = None # Get homology data between source and target antigens
if enforce_antigen_homology == True:
(d_mapping, hobj) = filter_mapping_by_homology_protein(d_mapping, d_peptides_info, fname_antigens_source, fname_antigens_target)
tj = time.time(); td = tj-ti;
report_time(ti,tj, '== Map peptides: filter_mapping_by_homology_protein ==')
return d_mapping
def map_peptides_selector(fname_peptide_list,
fname_antigens_blastdb_target,
method='blast_a',
sim_cutoff_fraction=1.0):
"""
Given a peptide:protein mapping algorithm, map a list of peptides onto antigens_target.
"""
from algorithm.factory import get_mapping_algorithm
mappingAlgo = get_mapping_algorithm(method=method)
d_mapping = mappingAlgo.search(fname_peptide_list, fname_antigens_blastdb_target, sim_cutoff_fraction=sim_cutoff_fraction)
return d_mapping, mappingAlgo
def annotate_mapping(d_mapping, antigens_list_target, d_id_to_peptide, debug=False):
"""
GOAL:
For each antigen, indicate its mapping status and provide description.
(1) Whether there is a peptide mapped to the antigen.
(2) Protein description,
(3) How many peptides mapped, etc.
d_mapping # Contains mapping records.
antigens_list_target # A list of all antigens.
d_id_to_peptide # For a given peptide id, get its peptide sequence.
How about:
INPUT: d_mapping
OUTPUT: d_annotation # d[id_antigen] = {description:###, num_peptides:###, mapped:[True,False]}
"""
from algorithm.blast import parse_sequence_record
d_annotation = {} # Also include information for unmapped_orfs
for (i, record) in enumerate(antigens_list_target): # For each antigen, return a list of peptides that are found.
(id_antigen, description) = parse_sequence_record(record)
match_list = None
if d_mapping.has_key(id_antigen):
match_list_temp = d_mapping[id_antigen]
#match_list = [(sim, dic_id_to_peptide[id_peptide]['linear_peptide_seq'], pos_i,pos_j) for (sim,id_peptide,pos_i,pos_j) in match_list_temp]
#match_list = [(sim, dic_id_to_peptide[id_peptide]['linear_peptide_seq'], pos_i-1, pos_j-1) for (sim,id_peptide,pos_i,pos_j) in match_list_temp]
match_list = [(sim, id_peptide, d_id_to_peptide[id_peptide], pos_i-1, pos_j-1) for (sim, id_peptide, pos_i, pos_j) in match_list_temp]
if match_list != None:
d_annotation[id_antigen] = {'id_antigen':id_antigen, 'description':description, 'num_peptides':len(match_list), 'mapped':True}
if debug==True: print '\tmap_peptides', '\t', i, '\t', id_antigen, '\t', record.description
else:
d_annotation[id_antigen] = {'id_antigen':id_antigen, 'description':description, 'num_peptides':0, 'mapped':False}
return d_annotation
def get_d_epitope_id_to_antigen_id(d_mapping):
"""
Returns a dictionary: d[peptide_id] = a list of (similarity, target_antigen_id)
"""
d_epitope_id_to_antigen_id = {}
id_antigen_list = d_mapping.keys(); id_antigen_list.sort()
for id_antigen in id_antigen_list:
print 'debug.get_d_epitope_id_to_antigen_id', d_mapping[id_antigen].keys()
match_list = d_mapping[id_antigen]
if match_list != None:
for (similarity, id_peptide, pos_i, pos_j) in match_list:
if d_epitope_id_to_antigen_id.has_key(id_peptide)==True:
temp = d_epitope_id_to_antigen_id[id_peptide]
temp.append([similarity, id_antigen])
d_epitope_id_to_antigen_id[id_peptide] = temp
else:
temp = [similarity, id_antigen]
d_epitope_id_to_antigen_id[id_peptide] = temp
return d_epitope_id_to_antigen_id
def write_d_epitope_id_to_antigen_id(d_id_to_peptide, d_mapping, dir_prefix='./'):
"""
GOAL: For each id_peptide, return
"""
from util_blastpeptides import write_file, get_line_str
header = ['id_peptide', 'peptide', 'is_mapped']
content = [header]
id_epitope_list_all = d_id_to_peptide.keys()
id_epitope_list_all = sorted(id_epitope_list_all, key = lambda id_peptide: int(id_peptide))
dic_epitope_id_to_antigen_id = get_d_epitope_id_to_antigen_id(d_mapping)
for id_peptide in id_epitope_list_all:
line = [id_peptide, d_id_to_peptide[id_peptide], dic_epitope_id_to_antigen_id.has_key(id_peptide)]
content.append(line)
#print 'check_mapping', '\t', id_peptide, '\t', dic_epitope_id_to_antigen_id.has_key(id_peptide)
write_file([get_line_str(row,delimiter='\t') for row in content], os.path.join(dir_prefix, 'peptide_list.stats.txt'))
|
5fd7af614f4f06454bd30e67acbc845532e0bc57 | gilgga/Python-Projects | /Connect_Four.py | 6,224 | 4 | 4 | '''
Created on Dec 4, 2017
@author: austr
'''
class Board(object):
def __init__(self, width=7, height=6):
self.__width = width
self.__height = height
board = self.createBoard(self.__width, self.__height)
self.__board = board
def createOneRow(self, width):
"""Returns one row of zeros of width "width"...
You should use this in your
createBoard(width, height) function."""
row = []
for col in range(width):
row += [" "]
return row
def createBoard(self, width, height):
""" returns a 2d array with "height" rows and "width" cols """
A = []
for row in range(height):
A += [self.createOneRow(width)] # What do you need to add a whole row here?
return A
def allowsMove(self, col):
if col > self.__width:
return False
if self.__board[0][col] == " ":
return True
else:
return False
def addMove(self, col, ox):
index_of_placement = -1
for row in range(self.__height):
if self.__board[row][col] == " ":
index_of_placement += 1
else:
break
self.__board[index_of_placement][col] = ox
def setBoard(self, move_string):
""" takes in a string of columns and places
alternating checkers in those columns,
starting with 'X'
For example, call b.setBoard('012345')
to see 'X's and 'O's alternate on the
bottom row, or b.setBoard('000000') to
see them alternate in the left column.
moveString must be a string of integers
"""
nextCh = 'X' # start by playing 'X'
for colString in move_string:
col = int(colString)
if 0 <= col <= self.__width:
self.addMove(col, nextCh)
if nextCh == 'X': nextCh = 'O'
else: nextCh = 'X'
def delMove(self, col):
for row in range(self.__height):
if self.__board[row][col] == " ":
continue
else:
self.__board[row][col] = " "
def winsFor(self, ox):
"""Need to use a bunch of for loops"""
for row in range(self.__height - 3): #Vertical Downwards
for col in range(self.__width):
if self.__board[row][col] == ox and self.__board[row+1][col] == ox and self.__board[row+2][col] == ox and self.__board[row+3][col] == ox:
return True
for row in range(self.__height): #Horizontal Right
for col in range(self.__width - 3):
if self.__board[row][col] == ox and self.__board[row][col+1] == ox and self.__board[row][col+2] == ox and self.__board[row][col+3] == ox:
return True
for row in range(3, self.__height): #Up to the Right
for col in range(self.__width - 3):
if self.__board[row][col] == ox and self.__board[row-1][col+1] == ox and self.__board[row-2][col+2] == ox and self.__board[row-3][col+3] == ox:
return True
for row in range(self.__height - 3): #Down and to the Right
for col in range(self.__width - 3):
if self.__board[row][col] == ox and self.__board[row+1][col+1] == ox and self.__board[row+2][col+2] == ox and self.__board[row+3][col+3] == ox:
return True
return False
def hostGame(self):
turn = "X"
print("Welcome to Connect Four!")
lst = []
for i in range(self.__width):
lst.append(str(i))
#print(lst)
while True:
print("")
print(self)
print("")
turn = "X"
x = input("X's choice: ")
while x not in lst or not self.allowsMove(int(x)):
x = input("Error, you need to enter a valid input: ")
x=int(x)
self.addMove(x, turn)
if self.winsFor("X"):
print("")
print("")
print("X wins -- Congratulations!")
print("")
print(self)
break
turn = "O"
print("")
print(self)
print("")
x = input("O's choice: ")
while x not in lst or not self.allowsMove(int(x)):
x = input("Error, you need to enter a valid input: ")
x=int(x)
self.addMove(x, turn)
if self.winsFor("O"):
print("")
print("")
print("O wins -- Congratulations!")
print("")
print(self)
break
def __str__(self):
"""Pipe characters in between characters of 2D array
End of row has it too
End of array print dashes
Need
Need accumulator string"""
newboard = ""
num_row = len(self.__board)
for row in range(num_row):
num_cols = len(self.__board[row])
for col in range(num_cols):
newboard += "|"
newboard += self.__board[row][col]
newboard += "|"
newboard += "\n"
dashes = "-"*self.__width*2 + "-"
newboard += dashes
newboard += "\n"
num_label = 0
for number in range(self.__height + 1):
newboard += " "
newboard += str(num_label)
num_label += 1
return str(newboard)
# if __name__ == "__main__":
# b = Board(7,6)
# b.setBoard("12233434464") #Diagonal Upa nd to the Right
# print(b)
# print(b.winsFor("X"))
# b.setBoard("121211123334") #Diagonal Down and to the Left
# print(b)
# print(b.winsFor("O"))
# b.hostGame()
# b.setBoard("11223345") #Horizontal
# print(b)
# print(b.winsFor("X"))
# b.setBoard("12121213") #Vertical
# print(b)
# print(b.winsFor("X"))
# b.hostGame() |
42d614c608d6dddfeebc532148b3beea2a87e3a9 | Shamimasharmin/Python-code-practice | /playing_rock_paper_scissors.py | 1,674 | 4.03125 | 4 | activate = True
user_choices=['Yes', 'y', 'No', 'n']
while activate:
words=['Rock', 'ROCK', 'rock', 'Paper', 'PAPER', 'paper', 'Scissors', 'SCISSORS', 'scissors']
player1 = input('player1- Choose one: Rock, Paper or Scissors : ')
if player1 in words:
for word in words:
if player1==word:
pass
player2 = input('player2- Choose one: Rock, Paper or Scissors : ')
if player2 in words:
for word1 in words:
if player2==word1:
pass
if player1=='rock' and player2=='scissors':
print('Congrats, player1 win the game')
if player2=='rock' and player1=='scissors':
print('Congrats, player2 win the game')
if player1=='scissors' and player2=='paper':
print('Congrats, player1 win the game')
if player2=='scissors' and player2=='paper':
print('Congrats, player2 win the game')
if player1=='paper' and player2=='rock':
print('Congrats, player1 win the game')
if player1=='rock' and player2=='paper':
print('Congrats, player2 win the game')
user_input=input('Do you want to continue? ')
if user_input.lower() == user_choices[0].lower() or user_input.lower==user_choices[1].lower():
continue
else:
print('Thanks for playing')
activate=False
|
9550821d53972734b86957a92122fd5348889771 | Shamimasharmin/Python-code-practice | /addition_subtraction_multiplication_division.py | 431 | 3.5 | 4 | def dispatch_if(operator, x, y):
if operator=='add':
return x+y
elif operator=='sub':
return x-y
elif operator=='mul':
return x*y
elif operator=='div':
return x/y
else:
return None
def dispatch_dict(operator, x, y):
return{
'add':lambda:x+y,
'sub':lambda:x-y,
'mul':lambda:x*y,
'div':lambda:x/y,
}.get(operator,lambda:None)()
|
5b470b0cc142685511e8900a91306ea83510966d | BasantaChaulagain/cracking-codes-with-python | /caeserHacker.py | 425 | 3.75 | 4 | def main():
symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?."
length=len(symbols)
message=raw_input("Enter a string:\n")
for key in range(length):
translated=""
for letter in message:
if letter in symbols:
letterIndex=symbols.find(letter)
translated=translated+symbols[(letterIndex-key)%length]
print("key #{}: {}".format(key, translated))
if __name__=="__main__":
main() |
e07d9678ac7c45f2880e747c77d133fda8c2081f | dudnicp/compilateur_deca | /src/test/script/push_to_stack_generator_or.py | 1,011 | 3.546875 | 4 | #!usr/bin/python3
def or_recursive(n):
if n == 0:
return "(2 < 1) || (1 < 2)"
else:
return "(2 < 1) || ({})".format(or_recursive(n-1))
def main():
with open("test_too_much_registers_or.deca", 'w') as test_file:
test_file.write("// @result ok\n")
test_file.write("// @result ok\n")
test_file.write("{\n")
big_expression = or_recursive(17)
test_file.write("boolean x = " + big_expression + ";\n")
test_file.write("if ({}) ".format("x"))
test_file.write("{\n")
test_file.write("println(\"ok\");\n")
test_file.write("} else {\n")
test_file.write("println(\"ko\");\n")
test_file.write("}")
test_file.write("if ({}) \n".format(big_expression))
test_file.write("{\n")
test_file.write("println(\"ok\");\n")
test_file.write("} else {\n")
test_file.write("println(\"ko\");\n")
test_file.write("}")
test_file.write("}")
main() |
be564700d52e4d29967af461fd46da72893f838d | webclinic017/davidgoliath | /Project/modelling/03_linearalgebra.py | 10,313 | 4 | 4 | # linear algebra python
# https://www.google.com/search?q=linear+algebra+python&sxsrf=ALeKk00bAclhj18xCwEbKZ27J5UMzPRTfA%3A1621259417578&ei=mXSiYPXXItqNr7wPzoSXsAY&oq=linear+al&gs_lcp=Cgdnd3Mtd2l6EAMYATIECCMQJzIECAAQQzIECAAQQzIECC4QQzICCAAyBQgAEMsBMgUIABDLATICCAAyAggAMgIILjoHCCMQsAMQJzoHCAAQRxCwAzoHCAAQsAMQQzoFCAAQkQI6CggAELEDEIMBEEM6CwgAELEDEIMBEJECUOSkAVjptQFg5cABaAFwAngAgAHIAYgBiA2SAQUwLjkuMZgBAKABAaoBB2d3cy13aXrIAQrAAQE&sclient=gws-wiz
import numpy as np
from numpy import linalg as la
import time
'''
pinv, dot, matmul, multi_dot, arrays vs matrix vs vectors,
vdot, inner, outer, einsum/ einsum_path, matrix_power, kron,
decomposition, cond, det, solve, lstsq, inv
'''
# ---------- dot: product of two arrays -----------
m = np.arange(3) - 3
# print(m)
n = np.arange(3) - 2
# print(n)
# print(np.dot(m, n))
# print(np.dot(2, 3))
a = [[1, 0], [0, 1]]
b = [[4, 1], [2, 2]]
# print(np.dot(a, b))
a = np.arange(2*3*4).reshape((2, 3, -1))
# b = np.arange(3*4*5*6)[::-1].reshape((5, 4, 6, 3))
# print(a)
# print(b)
# ---------- multi_dot: product of two or more arrays -----------
A = np.random.random((5, 4))
B = np.random.random((4, 3))
C = np.random.random((3, 6))
D = np.random.random((6, 2))
# print(la.multi_dot([A, B, C, D]))
# ---------- vdot: product of two vectors -----------
# complex conjugate: a+bj vs a-bj
a = np.array([1+2j, 3+4j])
b = np.array([5+6j, 7+8j])
# print(np.vdot(a, b))
a = np.array([[1, 4], [5, 6], [5, 6]])
b = np.array([[4, 1], [2, 2], [5, 6]])
# print(np.vdot(a, b))
# ---------- inner: Inner product of two arrays -----------
# scalars: vô hướng
a = np.arange(3) - 1
b = np.arange(3) - 2
# print(np.inner(a, b))
a = np.arange(12).reshape((2, 3, -1))
# print(a)
b = np.arange(2)
# print(b)
# print(np.inner(a, b))
# b = 1 -> b scalar
# print(np.inner(np.eye(3), 1))
# ---------- outer : outer product of two arrays -----------
rl = np.outer(np.ones((5, )), np.linspace(-2, 2, 5))
# print(rl)
# print(np.ones((5, )))
# print(np.linspace(-2, 2, 5))
im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5, )))
# print(im)
# grid for computing a Mandelbrot set
# print(rl + im)
# dtype
x = np.array(['a', 'b', 'c'], dtype=object)
# print(np.outer(x, [1, 2, 1]))
# ---------- matmul: matrix product of two arrays -----------
a = np.ones([9, 5, 7, 4])
c = np.ones([9, 5, 4, 3])
# print(a)
# print(c)
# # using shape to get dismensions
# print(np.dot(a, c).shape)
# print(np.matmul(a, c).shape)
a = np.array([[1, 0],
[0, 1]])
b = np.array([[4, 1],
[2, 2]])
# print(np.matmul(a, b))
a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
# print(np.matmul(a, b).shape)
# print(np.matmul(a, b)[0, 1, 1])
# print(sum(a[0, 1, :]*b[0, :, 1]))
# print(np.matmul([2j, 3j], [2j, 3j]))
a = np.array([2j, 3j])
b = np.array([2j, 3j])
# print(a @ b)
# ---------- tensordot: tensor dot product along specified axes -----------
# axes = 0, 1, 2
# 2 tham số đầu tiên ảnh hưởng chính đến nhân ma trận
a = np.arange(6.).reshape(1, 2, -1)
b = np.arange(4.).reshape(2, 1, -1)
c = np.tensordot(a, b, axes=([1, 0], [0, 1]))
# c = np.tensordot(a, b, axes=([0, 1], [1, 0]))
# print(a)
# print()
# print(b)
# print()
# print(c.shape)
# d = np.zeros((3, 2))
# for i in range(3):
# for j in range(2):
# for k in range(1):
# for n in range(2):
# d[i, j] += a[k, n, i] * b[n, k, j]
# print(d)
a = np.array(range(1, 9))
a.shape = (2, 2, 2)
A = np.array(('a', 'b', 'c', 'd'), dtype=object)
A.shape = (2, 2)
# khi nào dùng axes nào = 0, 1, 2
res = np.tensordot(a, A, ((0, 1), (1, 0)))
# print(res.shape)
# ---------- einsum/ einsum_path: Einstein summation -----------
# https://numpy.org/doc/stable/reference/generated/numpy.einsum.html#numpy.einsum
a = np.arange(6.).reshape(1, 2, -1)
b = np.arange(4.).reshape(2, 1, -1)
# print(np.einsum('ijm,jik', a, b))
a = np.arange(25).reshape(5, 5)
b = np.arange(5)
c = np.arange(6).reshape(2, 3)
# print(np.einsum('ii', a))
# print(np.trace(a))
# print(np.einsum(a, [0, 0]))
# print(np.einsum('ii->i', a))
# print(np.diag(a))
# # Sum over an axis
# print(a)
# print(np.einsum('ij->i', a))
# print(np.sum(a, axis=1))
# print(np.sum(a, axis=0))
# print(np.einsum('...i->...', a))
# # matrix transpose
# print(np.einsum('ji', a))
# print(np.einsum('ij->ji', a))
# print(np.transpose(a))
# print(a.T)
# print(np.einsum(a, [1, 0]))
# # Vector inner products
# print(b)
# print(np.einsum('i,i', b, b))
# print(np.einsum(b, [0], b, [0]))
# print(np.dot(b, b.T))
# print(np.inner(b, b))
# # Matrix vector multiplication
# print(np.einsum('ij,j', a, b))
# print(np.einsum(a, [0, 1], b, [1])) # ???
# print(np.dot(a, b))
# print(np.einsum('...j,j', a, b)) # ???
# # scalar multiplication
# print(np.einsum(',ij', 3, c))
# print(np.multiply(3, c))
# # Writeable returned arrays
# a = np.zeros((3, 3))
# np.einsum('ii->i', a)[:] = 1
# print(a)
# # Chained array operations. For more complicated contractions
# a = np.ones(64).reshape(2, 4, 8)
# # print(a)
# t0 = time.time()
# path = np.einsum_path('ijk,ilm,njm,nlk,abc->', a, a,
# a, a, a, optimize='optimal')[0]
# for item in range(500):
# # _ = np.einsum('ijk,ilm,njm,nlk,abc->', a, a, a, a, a)
# # _ = np.einsum('ijk,ilm,njm,nlk,abc->', a, a, a, a, a, optimize='optimal')
# # _ = np.einsum('ijk,ilm,njm,nlk,abc->', a, a, a, a, a, optimize='greedy')
# _ = np.einsum('ijk,ilm,njm,nlk,abc->', a, a, a, a, a, optimize=path)
# t1 = time.time()
# print(t1-t0)
# # ---------------- bonus :
# a = np.arange(25).reshape(5, 5)
# # print(a)
# print(np.average(a, axis=0))
# print(np.average(a, axis=1))
# ---------- matrix_power: matrix to power -----------
i = np.array([[0, 1], [-1, 0]])
# i = np.ones((3, 3))
# print(i)
# print(la.matrix_power(i, 0))
# print(la.matrix_power(i, -3))
# q = np.zeros((4, 4))
# q[0:2, 0:2] = -i
# q[2:4, 2:4] = i
# print(la.matrix_power(q, 2))
# ---------- kron: Kronecker product of two arrays -----------
# https://math.stackexchange.com/questions/1874581/why-use-the-kronecker-product
a = np.arange(3)
b = np.arange(3) - 2
# print(a)
# print(b)
# print(np.kron(a.T, b.T))
# print(np.kron([1, 10, 100], [5, 6, 7]))
# print(np.kron([5, 6, 7], [1, 10, 100]))
# # ones, zeros, eye
# print(np.kron(np.eye(2), np.ones((2, 2))))
a = np.arange(100).reshape((2, 5, 2, 5))
b = np.arange(24).reshape((2, 3, 4))
c = np.kron(a, b)
# print(c.shape)
# ---------- cholesky: Cholesky decomposition -----------
# https://www.sciencedirect.com/topics/engineering/cholesky-decomposition
A = np.array([[1, -2j], [2j, 5]])
# print(A)
L = la.cholesky(A)
# print(L)
# print(np.dot(L, L.T.conj()))
# if array_like
A = [[1, -2j], [2j, 5]]
# print(type(la.cholesky(A)))
# print(type(la.cholesky(np.matrix(A))))
# ---------- qr: qr decomposition -----------
# https://math.stackexchange.com/questions/198479/why-is-qr-factorization-useful-and-important
# https://en.wikipedia.org/wiki/Least_squares
# https://en.wikipedia.org/wiki/Orthonormality
a = np.random.randn(3, 2)
q, r = la.qr(a)
# print(q, r)
# print(r)
# print(np.allclose(a, np.dot(q, r)))
# print(la.qr(a, mode='r'))
A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
b = np.array([1, 0, 2, 1])
q, r = la.qr(A)
p = np.dot(q.T, b)
# print(np.dot(np.linalg.inv(r), p))
# print(la.lstsq(A, b, rcond=None)[0])
# ---------- svd: svd decomposition -----------
# https://stats.stackexchange.com/questions/19607/what-is-the-point-of-singular-value-decomposition
a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
u, s, vh = np.linalg.svd(a, full_matrices=True)
# print(u, s, vh)
# print(u.shape, s.shape, vh.shape)
# print(np.allclose(a, np.dot(u[:, :6] * s, vh)))
smat = np.zeros((9, 6), dtype=complex)
smat[:6, :6] = np.diag(s)
# print(np.allclose(a, np.dot(u, np.dot(smat, vh))))
u, s, vh = np.linalg.svd(a, full_matrices=False)
# print(np.allclose(a, np.dot(u * s, vh)))
smat = np.diag(s)
# print(np.allclose(a, np.dot(u, np.dot(smat, vh))))
# ---------- eig: eigenvalues and right eigenvectors -----------
# print(np.diag((1, 2, 3)))
w, v = la.eig(np.diag((1, 2, 3)))
# # columns vector
# print(w)
# # diag matrix
# print(v)
w, v = la.eig(np.array([[1, -1], [1, 1]]))
# print(w)
# print(v)
# ---------- eigh: Hermitian eigenvalues and eigenvectors -----------
# ---------- eigvals: eigenvalues of a general matrix -----------
# ---------- eigvalsh: Hermitian eigenvalues of a general matrix ----
# ---------- norm: Matrix or vector norm 02_part -----------
# ---------- cond: condition number -----------
a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
# print(la.cond(a))
# print(la.cond(a, 'fro'))
# print(la.cond(a, np.inf))
# ---------- det: determinant -----------
a = np.array([[1, 2], [3, 4]])
# a = np.array([[[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]]])
# print(la.det(a))
# ---------- matrix_rank: matrix rank of array -----------
# ---------- slogdet: sign and logarithm determinant -----------
(sign, logdet) = la.slogdet(a)
# print(sign)
# print(logdet)
# print(sign*np.exp(logdet)) # = det
# ---------- trace: sum along diagonals -----------
# print(np.trace(a))
# ---------- solve: Solve a linear matrix equation -----------
a = np.array([[1, 2], [3, 5]])
b = np.array([1, 2])
x = la.solve(a, b)
# print(x)
# print(np.allclose(np.dot(a, x), b))
# ---------- tensorsolve: Solve the tensor equation -----------
a = np.eye(2*3*4)
a.shape = (2*3, 4, 2, 3, 4)
b = np.random.randn(2*3, 4)
x = la.tensorsolve(a, b)
# print(x.shape)
# print(np.allclose(np.tensordot(a, x, axes=3), b))
# ---------- lstsq: least-squares solution -----------
x = np.array([0, 1, 2, 3])
y = np.array([-1, 0.2, 0.9, 2.1])
A = np.vstack([x, np.ones(len(x))]).T
m, c = la.lstsq(A, y, rcond=None)[0]
# print(m, c)
# ---------- inv: inverse of a matrix -----------
a = np.array([[1., 2.], [3., 4.]])
# print(type(a))
ainv = la.inv(a)
# print(ainv)
# print(np.allclose(np.dot(a, ainv), np.eye(2)))
# print(la.inv(np.matrix(a)))
a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
# print(la.inv(a))
# ---------- pinv: pseudo inverse of a matrix -----------
a = np.random.randn(3, 2)
B = la.pinv(a)
# print(np.allclose(a, np.dot(a, np.dot(B, a))))
# print(np.allclose(B, np.dot(B, np.dot(a, B))))
|
b6aca7b55b08724d2a922f3788cc2b15c4465f8e | webclinic017/davidgoliath | /Project/modelling/17_skewness.py | 1,280 | 4.125 | 4 | # skewness python
# https://www.google.com/search?q=skewness+python&oq=Skewness+python&aqs=chrome.0.0l4j0i22i30l6.3988j0j4&sourceid=chrome&ie=UTF-8
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
# https://www.geeksforgeeks.org/scipy-stats-skew-python/
''' Statistical functions
In simple words, skewness is the measure of how much the
probability distribution of a random variable deviates
from the normal distribution.
# https://www.investopedia.com/terms/s/skewness.asp
skewness = 0 : normally distributed.
skewness > 0 : more weight in the left tail of the distribution.
skewness < 0 : more weight in the right tail of the distribution.
'''
# part 1 ----------------------------------
import numpy as np
from scipy.stats import skew
import pandas as pd
arr = np.random.randint(1, 10, 10)
arr = list(arr)
# print(arr)
# # more weight in the right when skew>0,
# # determine skew close enough to zero
# print(skew(arr))
# print(skew([1, 2, 3, 4, 5]))
# part 2 ----------------------------------
# df = pd.read_csv('Data/nba.csv')
df = pd.read_csv('Data/XAUNZD_Daily.csv')
# print(df.tail())
# skewness along the index axis
print(df.skew(axis=0, skipna=True))
# skewness of the data over the column axis
# print(df.skew(axis=1, skipna=True))
|
97f6d47ddd2ddcb59e5c5e04f7088a025f16609a | mbillingr/repotools-template-py | /pkg/mod.py | 292 | 3.765625 | 4 | """ This is a module
"""
class Number(object):
""" This is a class
"""
def __init__(self, nr=0):
self.nr = nr
def __repr__(self):
return 'Number({})'.format(self.nr)
def add(self, nr):
self.nr += nr
def mul(self, nr):
self.nr *= nr
|
920fbc4957ec799af76035cbb258f2f41392f030 | Reskal/Struktur_data_E1E119011 | /R.2.4.py | 1,096 | 4.5625 | 5 | ''' R-2.4 Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
include methods for setting the value of each type, and retrieving the value
of each type. '''
class Flower:
def __init__(self, name, petals, price):
self._name = name
self._petals = petals
self._price = price
def get_name(self):
return self._name
def get_petals(self):
return self._petals
def get_price(self):
return self._price
def set_name(self, name):
self._name = name
def set_petals(self, petals):
self._petals = petals
def set_price(self, price):
self._price = price
# f = Flower('sunflower', 24, 1.25)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
# f.set_name('rose')
# f.set_petals(32)
# f.set_price(1.45)
# print(f.get_name())
# print(f.get_petals())
# print(f.get_price())
|
a08d7543c13ca4b2d902488bbd58123bf7d80747 | Fimba-Code/algorithm-challenge | /solutions/python/challenge_4.py | 2,017 | 3.65625 | 4 | # Challenge #4 - Probabilidade
#Constantes que representam as diferentes faces da moeda
T = "T"
H = "H"
# função para calcular todas permutações possíveis
# Todas as permutações são postas num array
#limit: é o número de lançamentos e limita o
# tamanho da string. Ex: p/ limit = 2, as strings geradas são
# HT,TT,TH,HH
# perms: é o array que armazena as permutações
# current: armazena o estado da string que formará a
#próxima permutação. inicialmente é uma string vazia
#depth: controla a profundidade da recursão
def get_perms(limit,perms,current="",depth=0):
# 1. Verificar se atingimos o caso base da recursão
if depth == limit:
#se sim, a string actual é uma permutação válida
# e é adicionada ao array de permutações
perms.append(current)
return
# 2. Chamar de forma recursiva get_perms modificando
# a string actual com as variações possíveis (T e H).
get_perms(limit,perms,current+T,depth+1)
get_perms(limit,perms,current+H,depth+1)
# 1. receber o número de lançamentos do usuário
flips = int(input("input: "))
# 2. Gerar todas as permutações de 'H' e 'T' com base no número de
# lançamentos. Ex: para flips = 3 teriamos: TTT, THT, TTH ...
#o número total de resultados é sempre 2^flips
results = []
#a função get_perms gera os resultados e adiciona-os ao array
get_perms(flips,results)
# 3. Contar o número de resultados com dois 'H's
#seguidos
count = 0
for result in results:
#verifica cada resultado
# e procura pelo padrão 'HH' em qualquer
# posição na string
if "HH" in result:
count +=1
# 4. Calcular e mostrar a probabilidade para o usuário
# Lembrando que a probabilidade = x/y
# onde x -> acontecimentos favoráveis (quantidade de resultados sem 'HH') = tamanho(resultados) - quantidade_de_res_com_HH
# onde y -> todos acontecimentos possíveis (quantidade de resultados) = tamanho(resultados)
print(f"ouput: {(len(results)-count)/len(results)}")
|
c0e7b3a5e7fe3c4d7f47c246b7f2873194520ee7 | fuckualreadytaken/ctf | /crypto/little_tools.py | 2,357 | 3.59375 | 4 | #! /usr/bin/env python
# coding=utf-8
import sys
def input_int(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
try:
n = int(raw_input())
return n
except:
return 0
def egcd(a, b):
if b == 0:
return 1, 0, a
(x, y, r) = egcd(b, a % b)
tmp = x
x = y
y = tmp - (a / b) * y
return x, y, r
def Invert():
print "+" * 10 + "Invert" + "+" * 10
print "Input your e (only number):"
e = int(raw_input())
print "Input your modulus (only number):"
modulus = int(raw_input())
x, y, r = egcd(e, modulus)
if r != 1:
print "E and modulus is not coprime!"
exit()
if x < 0:
x = x + modulus
print "The Invert result is %d" % x
def Railfence():
print "+" * 10 + "Railfence" + "+" * 10
print "Input your cipher:"
e = raw_input()
e = e.strip()
print "Input your key:"
key = int(raw_input())
length = len(e)
filling_bit = key - length % key
num = length / key
if filling_bit != 0:
num += 1
new_e = list(e)
k = filling_bit
while k > 0:
new_e.insert(len(e) + filling_bit - (k - 1) * num - 1, " ")
k -= 1
e = ""
for i in new_e:
e += i
i = 0
result = ""
while i < num:
j = 0
while j < key:
result = result + e[i + j * num]
j += 1
i += 1
print "Result : " + result.strip(" ")
def ModExp():
print "+" * 10 + "ModExp" + "+" * 10
print "Input your n (only number):"
n = int(raw_input())
print "Input your k (only number):"
k = int(raw_input())
print "Input your m (only number):"
m = int(raw_input())
a = list(bin(k))[2:]
a.reverse()
s = 1
for i in a:
if i == '1':
s = (s * n) % m
n = (n * n) % m
print "The ModExp result is %d" % s
def menu():
print "+" * 10 + "Welcome to little tools!" + "+" * 10
while True:
print "1. ModExp"
print "2. Invert"
print "3. Railfence"
print "4. exit"
sys.stdout.flush()
choice = input_int("Command: ")
{
1: ModExp,
2: Invert,
3: Railfence,
4: exit,
}.get(choice, lambda *args: 1)()
if __name__ == "__main__":
menu()
|
2ea32f404f15439516fcb5678bcffb3e0f323683 | ghldbssla/Python | /자료구조/day02/연결리스트.py | 1,761 | 3.90625 | 4 | #연결리스트.py
class Node:
def __init__(self,data):
self.data = data
self.next = None#모든 타입의 초기값
class LinkedList:
def __init__(self):
self.head=Node('head')
self.count=0
#추가
def append(self,data):
newNode = Node(data)
curr=self.head
for i in range(self.count):
curr=curr.next
curr.next=newNode
self.count+=1
#삽입
def insert(self,idx,data):
newNode = Node(data)
curr=self.head
for i in range(idx):
curr=curr.next
if curr.next is not None:
#curr.next가 None이 아닌 상태(중간에 삽입)
newNode.next=curr.next
curr.next=newNode
else:
#curr.next가 None인 상태(가장 마지막에 삽입)
curr.next=newNode
self.count+=1
#수정
def update(self,idx,data):
curr=self.head
for i in range(idx+1):
curr=curr.next
curr.data=data
#삭제
def delete(self,idx):
curr=self.head
for i in range(idx):
curr=curr.next
curr.next=curr.next.next
self.count-=1
#조회
def get(self,idx):
curr=self.head
for i in range(idx+1):
curr=curr.next
return curr.data
#목록
def show(self):
curr=self.head
for i in range(self.count):
print(curr.data,end='->')
curr=curr.next
print(curr.data)
li = LinkedList()
li.append('A')
li.append('B')
li.append('C')
li.insert(1,'D')
li.show()
li.update(1,'E')
li.show()
li.delete(1)
li.show()
print(li.get(1))
li2 = LinkedList()
li2.append(10)
li2.show()
|
955dd219de741389736060249815d9ce80092f36 | ghldbssla/Python | /개념 배우기/day05/method.py | 517 | 3.859375 | 4 | #method.py
'''
#f(x)=2x+1
def f(x):
return 2*x+1
'''
'''
#내 이름 10번 출력하는 메소드
def function(name):
result=""
for i in range(10):
# print(name)
result+=name+"\n"
return result
while True:
name = input("이름 : ")
print(function(name))
'''
'''
def login(userid,userpw):
if userid==db_userid:
if userpw==db_userpw:
print("로그인 성공")
return True
return False
if login("apple","abcd1234"):
#구현
'''
|
e5df21812c6c5107ce39ea43d4221dab17d66ca8 | ghldbssla/Python | /개념 배우기/day06/Comprehention.py | 388 | 3.765625 | 4 | #comprehention.py
#0~9가 담긴 리스트
#arData=[i for i in range(10)]
#print(arData)
#1~1000중 짝수만 담긴 리스트
#arData=[i for i in range(1,1000,1) if i%2==0]
#print(arData)
#(1,2),(1,4),(1,6),(2,2),(2,4),(2,6),(3,2),(3,4),(3,6)--1
#arData=[(i,j) for i in range(1,4,1) for j in range(2,8,2)]
#print(arData)
#arData=[(i//3+1,(i%3+1)*2) for i in range(9)]
#print(arData)
|
e491133990c74943fd62559ab513a3c3f9e9d2b2 | ghldbssla/Python | /자료구조/day04/후위표기법.py | 2,324 | 3.59375 | 4 | #후위표기법.py
#'문자열'.isdigit()
#'문자열'[0] : 문자열의 0번째 글자
#from 연결스택 import *
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedStack:
def __init__(self):
self.head=Node('head')
self.top=self.head
def push(self,data):
newNode = Node(data)
self.top.next=newNode
self.top = newNode
def pop(self):
if not self.is_empty():
curr = self.head
while curr.next.next is not None:
curr = curr.next
data = curr.next.data
curr.next = None
self.top=curr
return data
def is_empty(self):
return self.head.next is None
def getPriority(oper):
if oper == '+' or oper == '-':
return 1
elif oper == '*' or oper == '/':
return 2
else:
return 0
operList = LinkedStack()
#괄호 없는 수식
'''
while True:
eq = input('수식 입력 : ')
for i in range(len(eq)):
if eq[i].isdigit():
print(eq[i],end='')
else:
if operList.is_empty():
operList.push(eq[i])
else:
while getPriority(operList.top.data)>=getPriority(eq[i]):
operList.pop()
if operList.is_empty():
break
operList.push(eq[i])
while not operList.is_empty():
operList.pop()
print()
'''
#괄호 있는 수식
while True:
eq = input('수식 입력 : ')
for i in range(len(eq)):
if eq[i].isdigit():
print(eq[i],end='')
else:
if operList.is_empty() or eq[i] == '(':
operList.push(eq[i])
else:
if eq[i]==')':
while not operList.top.data == '(':
print(operList.pop(),end="")
operList.pop()
else:
while getPriority(operList.top.data)>=getPriority(eq[i]):
print(operList.pop(),end="")
if operList.is_empty():
break
operList.push(eq[i])
while not operList.is_empty():
print(operList.pop(),end="")
print()
|
2678840b71b80ee2b72750732fd68dac63db7b66 | Cogdof/OCR_backup | /CRAFT-pytorch-master/CRAFT-pytorch-master/problem.py | 234 | 3.546875 | 4 | line1 = input()
n = int(line1.split(" ")[0])
h = int(line1.split(" ")[1])
line2 = input()
line2 = line2.split(" ")
count=0
for i in range(0, n):
if int(line2[i]) <= h:
count+=1
else:
count+=2
print(count) |
de037860649e57eab88dc9fd8ae4cdab26fcb47a | sahilqur/python_projects | /Classes/inventory.py | 1,720 | 4.28125 | 4 | """
Simple python application for maintaining the product list in the inventory
"""
class product:
price, id, quantity = None, None, None
"""
constructor for product class
"""
def __init__(self, price, id, quantity):
self.price = price
self.id = id
self.quantity = quantity
"""
update price function
"""
def update_price(self, price):
self.price = price
"""
update quantity function
"""
def update_quantity(self,quantity):
self.quantity = quantity
"""
print product function
"""
def print_product(self):
print "id is %d\nprice is %.2f\nquantity is %d\n" % (self.id, self.price, self.quantity)
class Inventory:
"""
constructor for inventory class
"""
def __init__(self):
self.product_list = []
"""
add product function
"""
def add_product(self,product):
self.product_list.append(product)
"""
remove product function
"""
def remove_product(self,product):
self.product_list.remove(product)
"""
print inventory function
"""
def print_inventory(self):
total= 0.0
for p in self.product_list:
total+= p.quantity * p.price
print p.print_product()
print "total is %.2f" % total
"""
main function
"""
if __name__ == '__main__':
p1 = product(1.4, 123, 5)
p2 = product(1, 3432, 100)
p3 = product(100.4, 2342, 99)
I = Inventory()
I.add_product(p1)
I.add_product(p2)
I.add_product(p3)
I.print_inventory()
|
da64527b7b97a55f411a80cd31402b7fa78db6c8 | rocheers/algorithms | /tree/tree.py | 2,180 | 3.734375 | 4 | class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, arr=[]):
self.arr = arr
self.root = self.generate_tree()
def __repr__(self):
return "Tree's root = {}".format(self.root.val)
def pprint(self):
stack = [(0, self.root)]
while stack:
level, node = stack.pop(-1)
if node.right:
stack.append((level + 1, node.right))
if node.left:
stack.append((level + 1, node.left))
print("{}TreeNode(val={})".format('\t' * level, node.val))
def generate_tree(self):
try:
root = TreeNode(int(self.arr[0]))
except ValueError:
return TreeNode(val=None)
current_level, child_level = [root], []
i = 1
while True:
if i >= len(self.arr):
break
shift = 0
while i + shift < len(self.arr) and shift < 2 * len(current_level):
child_level.append(self.arr[i+shift])
shift += 1
i += shift
for _ in range(len(current_level)):
current_node = current_level.pop(0)
try: # Left child
value = int(child_level[0])
node = TreeNode(value)
current_node.left = node
current_level.append(node)
except:
pass
if not child_level:
break
child_level.pop(0)
try: # Right child
value = int(child_level[0])
node = TreeNode(value)
current_node.right = node
current_level.append(node)
except:
pass
if child_level:
child_level.pop(0)
return root
if __name__ == '__main__':
import sys
input_arr_string = sys.argv[1]
input_arr = input_arr_string.split(',')
t = Tree(input_arr)
t.pprint()
|
7279f2f62f5fab795ab14c5eaa8959fc8b1a1226 | gdgupta11/100dayCodingChallenge | /hr_nestedlist.py | 2,031 | 4.28125 | 4 | """
# 100daysCodingChallenge
Level: Easy
Goal:
Given the names and grades for each student in a Physics class of
students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
[["Gaurav",36], ["GG", 37.1], ["Rob", 42], ["Jack", 42]]
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
The first line contains an integer,
, the number of students.
The subsequent lines describe each student over
lines; the first line contains a student's name, and the second line contains their grade.
Constraints: 2 <= N <= 5
There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
"""
if __name__ == "__main__":
main_list = []
for _ in range(int(input())):
name = input()
score = float(input())
main_list.append([name, score])
# using lambda function here to sort the list of lists by second value
main_list.sort(key = lambda main_list: main_list[1])
tmpList = [lst[1] for lst in main_list]
# Taking the all the scores and making set of it to get unique values
tmpList = set(tmpList)
name_list = []
testList = []
for l in tmpList:
testList.append(l)
# sorting that unique list to get second lowest score
testList.sort()
# checking in main list for all the students who matches the second lowest score (Note: There might be more than 1 students with second lowest score)
for lst in main_list:
if lst[1] == testList[1]:
name_list.append(lst[0])
# sorting those names by alphabetically and printing them
name_list.sort()
for name in name_list:
print(name)
"""
Learnings:
using lambda Function to sort the list of list using value at second [1] position.
"""
|
b27f06f4d8286d4933eec47a344ae421bc9b3857 | nighthalllo/PS | /1765.py | 1,687 | 3.859375 | 4 | # union-find의 향기가 짙게 난다.
# 친구는 그냥 find해서 같으면 무조건 친구고,
# 적은 find를 했는데 같으면 친구임 -> 근데 또 본인은 아니어야 함
import sys
def find(parent, u) :
if parent[u] == u :
return u
parent[u] = find(parent, parent[u])
return parent[u]
def union(parent, u, v) :
u, v = find(parent, u), find(parent, v)
if u == v :
return
parent[v] = u
if __name__ == "__main__" :
n = int(sys.stdin.readline().rstrip())
m = int(sys.stdin.readline().rstrip())
f_parent, e_parent = [i for i in range(n + 1)], dict()
#friend는 그냥 root만 알면 되고
#딕셔너리로 자기 적이 누군지를 다 담아두면 됨
for _ in range(m) :
temp = sys.stdin.readline().rstrip().split()
u, v = int(temp[1]), int(temp[2])
if temp[0] == 'E' :
if e_parent.get(u) :
e_parent[u].append(v)
else :
e_parent[u] = [v]
if e_parent.get(v) :
e_parent[v].append(u)
else :
e_parent[v] = [u]
else :
union(f_parent, u, v)
#적의 적은 친구랬으니까 얘네 업데이트
for root in e_parent :
for i in range(len(e_parent[root])) :
for j in range(i + 1, len(e_parent[root])) :
union(f_parent, e_parent[root][i], e_parent[root][j])
#총 몇 팀 나왔는지 -> 루트가 몇개인지 세면 됨
team = set()
for i in range(1, n+1) :
team.add(find(f_parent, i))
print(len(team)) |
b18c889179c63aa43f5935b00fd8a14e3e95b148 | neehartpt/coding_problems | /nonRepeatingCharacter.py | 274 | 3.65625 | 4 | if __name__ == "__main__":
print "Enter number of test cases:"
n = int(raw_input())
for _ in range(n):
print "Enter the string:"
s = raw_input().strip()
l = 0
for i in s:
if (s.count(i) == 1):
print i
break
l += 1
if (l == len(s)):
print "-1"
|
be3901b4d26c4b5f31b62d02642e7c4eba2d8d16 | MadhavMalhotra89/ObjectOrientedDesign | /HashTable.py | 3,241 | 3.78125 | 4 | class Item:
def __init__(self, key, value):
self.key = key
self.value = value
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 10000
self.table = [[] for _ in range(self.size)]
def _hash_function(self, key):
return key % self.size
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hash_result = self._hash_function(key)
for item in self.table[hash_result]:
if item.key == key:
item.value = value
return
self.table[hash_result].append(Item(key, value))
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
hash_index = self._hash_function(key)
for item in self.table[hash_index]:
if item.key == key:
return item.value
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
hash_index = self._hash_function(key)
for index, item in enumerate(self.table[hash_index]):
if item.key == key:
del self.table[hash_index][index]
return
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)class Item:
def __init__(self, key, value):
self.key = key
self.value = value
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 10000
self.table = [[] for _ in range(self.size)]
def _hash_function(self, key):
return key % self.size
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hash_result = self._hash_function(key)
for item in self.table[hash_result]:
if item.key == key:
item.value = value
return
self.table[hash_result].append(Item(key, value))
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
hash_index = self._hash_function(key)
for item in self.table[hash_index]:
if item.key == key:
return item.value
return -1
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
hash_index = self._hash_function(key)
for index, item in enumerate(self.table[hash_index]):
if item.key == key:
del self.table[hash_index][index]
return
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
|
ccfe5b8b02a41a1f1625305e019754844ff84fee | ConnorHz/PythonBankAndPollAnalysis | /PyPoll/main.py | 1,806 | 3.640625 | 4 | import os
import csv
# The total number of votes cast
# A complete list of candidates who received votes
# The percentage of votes each candidate won
# The total number of votes each candidate won
# The winner of the election based on popular vote.
totalVotes = 0
candidates = {}
winnerVotes = 0
winnerName = ''
candidateResults = ''
with open(os.path.join("PyPoll", "Resources", "election_data.csv")) as csvFile:
csvreader = csv.reader(csvFile, delimiter=',')
# Skip First Row
next(csvreader)
# Headers: Voter ID, County, Candidate
for row in csvreader:
totalVotes += 1
if row[2] in candidates:
candidates[row[2]]['Votes'] += 1
else:
candidates[row[2]] = {'Votes': 0, 'Percentage': 0}
# '%.3f'%
for candidate in candidates:
# Calculate percentage of votes for each candidate
candidates[candidate]['Percentage'] = (candidates[candidate]['Votes']/totalVotes)*100
outPercentage = '{:.3f}'.format(round(candidates[candidate]['Percentage']))
outVotes = candidates[candidate]['Votes']
candidateResults = f'{candidateResults}{candidate}: {outPercentage}% ({outVotes})\n'
# TODO Figure this out. Still unsure how to effectivly loop through a dictionary
if candidates[candidate]['Votes'] > winnerVotes:
winnerVotes = candidates[candidate]['Votes']
winnerName = candidate
output = ("Election Results\n"
"----------------------------\n"
f"Total Votes: {totalVotes}\n"
"----------------------------\n"
f"{candidateResults}"
"----------------------------\n"
f"Winner: {winnerName}\n"
"----------------------------"
)
print(output)
f = open(r"PyPoll\analysis\ElectionResults.txt", "w")
f.write(output)
f.close()
|
9e8a9994f6c5b4b600a688251b2b7aa853ba4ac2 | alexksikes/interviews | /extra/lucidchart/othello.py | 7,732 | 4.1875 | 4 | # Implement the board game Othello/Reversi on the following board.
# Alternate black and white turns, and don't allow illegal moves.
#
# Extra credit: Have one human play against a computer that always
# makes a legal move.
#
# Extra extra credit: Have the computer make at least somewhat
# strategic moves rather than just some legal move.
# TODO:
# - improve on the corner / sides strategy
# - clean up generate_valid_moves func
# - random selection of who starts first
# - pygame interface
# - evolve a computer player by making it play against itself
import random
import string
from collections import defaultdict
class Player(object):
NONE = 0
BLACK = 1
WHITE = 2
class Othello(object):
ALPHA = string.ascii_letters
def __init__(self, dim=8):
self._dim = dim
self._board = [[0] * dim for x in range(dim)]
# place first four pieces
self._place_first_pieces()
# we start with the player with black pieces
self._player = Player.BLACK
self._valid_moves = {}
self._prev_can_play = True
self._computer_mode = False
self._computer_strategy = 'random'
self._self_playing = False
def _place_first_pieces(self):
mid = self._dim / 2
self._board[mid-1][mid] = self._board[mid][mid-1] = Player.WHITE
self._board[mid-1][mid-1] = self._board[mid][mid] = Player.BLACK
def _generate_valid_moves(self):
self._valid_moves = {}
for x in range(self._dim):
for y in range(self._dim):
moves = self._generate_valid_moves_at(x, y)
if moves:
self._valid_moves[(x, y)] = moves
def _generate_valid_moves_at(self, x, y):
def in_bound(x, y):
return 0 <= x < self._dim and 0 <= y < self._dim
def is_occupied(x, y):
return self._board[x][y] != Player.NONE
def opposite_color():
return Player.BLACK if self._player != Player.BLACK else Player.WHITE
def valid_in_direction(x, y, dirc, path):
path.append((x, y))
next_x, next_y = x + dirc[0], y + dirc[1]
if not in_bound(next_x, next_y):
return []
if self._board[next_x][next_y] == self._player:
return path
if self._board[next_x][next_y] == opposite_color():
return valid_in_direction(next_x, next_y, dirc, path)
return []
if not in_bound(x, y) or is_occupied(x, y):
return []
paths = []
for direction in [(-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1)]:
next_x, next_y = x + direction[0], y + direction[1]
if in_bound(next_x, next_y) and self._board[next_x][next_y] == opposite_color():
path = valid_in_direction(next_x, next_y, direction, [])
if path:
paths.append(path)
return paths
def _end_game(self):
return not self._prev_can_play and not self._can_play()
def _render(self):
spacer = len(str(self._dim-1))
print " " * spacer + " " + " ".join(a for a in Othello.ALPHA[:self._dim])
for x in range(self._dim):
row = "%*d" % (spacer, x)
for y in range(self._dim):
row += " " + self._render_space(x, y)
print row
def _render_space(self, x, y):
if self._board[x][y] == Player.BLACK:
return "B"
elif self._board[x][y] == Player.WHITE:
return "W"
return " "
def _can_play(self):
return self._valid_moves != {}
def _get_player_input(self):
print "Player %s plays ..." % self._player
x = y = -1
try:
row, col = raw_input('')
x = ord(row) - ord('0')
y = ord(col) - ord('a')
except ValueError:
print "Please enter a row and a column, for example: 'b3'"
if not self._is_valid_move(x, y):
return self._get_player_input()
return x, y
def _is_computer_turn(self):
if self._self_playing:
return True
return self._player != Player.BLACK and self._computer_mode
def _get_computer_input(self):
def distance((x1, y1), (x2, y2)):
return abs(x1 - x2) + abs(y1 - y2)
def close_to_corner(moves):
corners = [(0, 0), (0, self._dim-1), (self._dim-1, 0), (self._dim-1, self._dim-1)]
# compute the dist to each corner of every valid move
dist = [((x1, y1), distance((x1, y1), (x2, y2))) for x1, y1 in moves for x2, y2 in corners]
# and return the coordinate with min distance
return min(dist, key=lambda x: x[1])[0]
# greedily attempts to capture corners
# only attempt to do so randomly to make it a bit harder
# to guess the computer strategy
if random.choice((True, False)) and self._computer_strategy == 'corners':
move = close_to_corner(self._valid_moves.keys())
# or just select a random valid move
else:
move = random.choice(self._valid_moves.keys())
print "Computer plays ..."
print str(move[0]) + Othello.ALPHA[move[1]]
return move
def _is_valid_move(self, x, y):
return (x, y) in self._valid_moves
def _place_piece(self, x, y):
self._board[x][y] = self._player
def _update_board(self, x, y):
for path in self._valid_moves[(x, y)]:
for i, j in path:
self._board[i][j] = self._player
def _next_player(self):
self._prev_can_play = self._can_play()
self._player = Player.BLACK if self._player == Player.WHITE else Player.WHITE
def _who_won(self):
counts = defaultdict(int)
for row in self._board:
for val in row:
counts[val] += 1
if counts[Player.BLACK] > counts[Player.WHITE]:
print "Color black won!"
elif counts[Player.BLACK] < counts[Player.WHITE]:
print "Color white won!"
else:
print "Draw!"
def set_computer_mode(self):
self._computer_mode = True
def set_computer_strategy(self, strategy):
self._computer_strategy = strategy
def set_self_playing(self):
self._self_playing = True
def play(self):
# generate all valid moves for first player
self._generate_valid_moves()
# the game ends when no player can play
while not self._end_game():
# render the board
self._render()
# if the current player can play
if self._can_play():
# get the user or computer input
if self._is_computer_turn():
x, y = self._get_computer_input()
else:
x, y = self._get_player_input()
# place the piece on the board
self._place_piece(x, y)
# update the board
self._update_board(x, y)
# next player round
self._next_player()
# update all valid moves for that player
self._generate_valid_moves()
# determine who has won
self._who_won()
def main():
othello = Othello(8)
othello.set_computer_mode()
othello.set_computer_strategy('corners')
othello.play()
def test():
othello = Othello(50)
othello.set_self_playing()
othello.set_computer_strategy(random.choice(('corners', 'random')))
othello.play()
if __name__ == "__main__":
test()
# main()
|
0d3419443d936fae99a6d9a550c775f9d017dc8a | Lucian-N/funBits | /timeconversion.py | 907 | 3.953125 | 4 | '''
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock.
Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
'''
#!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
time_hours = int(s[:2])
time_minutes = int(s[3:5])
time_seconds = int(s[6:8])
if s[8] == 'P' and s[:2] !='12':
time_hours += 12
elif s[8] == 'A' and s[:2] == '12':
time_hours -= 12
else:
return s[:8]
result = str(time_hours).zfill(2) +':' + str(time_minutes).zfill(2)+ ':' + str(time_seconds).zfill(2)
return result
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = timeConversion(s)
f.write(result + '\n')
f.close()
|
f2ace74ebde816086a2f0a5d43f3dd977640f447 | sam-malanchuk/Algorithms | /eating_cookies/eating_cookies.py | 1,039 | 4.03125 | 4 | #!/usr/bin/python
import sys
# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(n, cache=dict()):
# check if the n has already been calculate
if n in cache:
return cache[n]
# base case, he cannot eat anymore cookies
if n <= 0:
return 1
total_ways = 0
for i in range(1, 4):
if i < n:
total_ways += eating_cookies(n - i)
elif i == n:
total_ways += 1
# save the result of n into cache for reuse
cache[n] = total_ways
return total_ways
# print(eating_cookies(30, {}))
if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(ways=eating_cookies(num_cookies), n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]')
# Understand
# Take a number of cookies 'n' and calculate all the possible ways 3, 2, and 1 can go into it.
# If 'n' is 0 then return 0
# Plan
# |
44f73780e812feef54ce64aefe473784bd5f19b8 | mediastore93/network | /time.py | 362 | 3.8125 | 4 | import time as t
import datetime
time = t.time()
date = datetime.datetime.now()
print(time)
print(date)
now = datetime.datetime.now()
print(now)
print (now.strftime("%H:%M:%S"))
t.sleep(10)
date_two = datetime.datetime.now()
time_elapsed = date_two - date
print(time_elapsed)
if time_elapsed > 20:
print('more than 20')
else:
print('less than 20')
|
bb6335b1d30f53f5fb046a8049d6353d54f352cc | CorentinBrtx/modvice | /server/src/models/user.py | 605 | 3.65625 | 4 | """
Define the User model
"""
from . import db
from .abc import BaseModel, MetaBaseModel
class User(db.Model, BaseModel, metaclass=MetaBaseModel):
""" The User model """
__tablename__ = "user"
username = db.Column(db.String(300), primary_key=True)
age = db.Column(db.Integer, nullable=True)
password = db.Column(db.String(300))
notation = db.relationship("Notation", back_populates="user")
def __init__(self, username, age=None, password=""):
""" Create a new User """
self.username = username
self.age = age
self.password = password
|
c93d362cfdbb5d7ff952181b68dda9d2b378d0c5 | Berucha/adventureland | /places.py | 2,813 | 4.375 | 4 | import time
class Places:
def __init__(self, life):
'''
returns print statements based on the user's input (car color)
and adds or takes away life points accordingly
'''
#testing purposes:
# print('''In this minigame, the user has been walking along to Adventurland.
# However, the user has stumbled across three cars. This car will take you to a mysterious location!
# The user must select a car. Which color car do you choose.. Red, Blue, or Green?
time.sleep(3)
print('')
self.life = life
print("* Some time later *...") #introduction to the game of places
time.sleep(2)
print()
print('You have been walking through Adventurland trying to reach the castle. It seems forever away.')
time.sleep(2.75)
print()
print("Luckily you have stumbled across three cars. Each car will take you to a mysterious location!")
self.car_colors()
time.sleep(2.5)
def car_colors(self):
'''
evaluates which color the user picks and returns the according print statements and life points
:param self: object of the places class
:return:none
'''
print()
time.sleep(2)
self.user_color = input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ").lower() #user must select a car
while self.user_color != ("red") and self.user_color != ("green") and self.user_color != ("blue"):
self.user_color = (input("You must select a car. Which color car do you choose.. Red, Blue, or Green? ")).lower()
if self.user_color == "red":
print() #if user chooses red then it is a bad choice and they lose life points
time.sleep(1.75)
print('''Uh-Oh! Your car takes you to the home of a troll who is one of the wicked ruler's minions!
You are forced to become his prisoner.''')
self.life -= 3
print('* 2 years later you escape and continue on with your journey *')
elif self.user_color == "blue":
print() #if user chooses blue then it is a good choice and they gain life points
time.sleep(1.75)
print(
"Yayyy! Your car takes you to the home of the Leaders of the Adventurer Revolution, where they feed and shelter you for the night.")
self.life += 2
elif self.user_color == "green": #if user chooses green then it is a okay choice and they dont gain life points nor lose them
print()
time.sleep(1.75)
print(
"Your car takes you to Adventureland's forest and then breaks down, you must continue your journey from here.")
#
# Places()
|
5f3ce5f268c3d457aacf496a4f69527b30087d1e | LockGit/Py | /avl_tree.py | 5,648 | 3.65625 | 4 | #!/usr/bin/env python
# encoding: utf-8
# author: Lock
# Created by Vim
"""
平衡二叉搜索树
1、若它的左子树不为空,则左子树上所有的节点值都小于它的根节点值。
2、若它的右子树不为空,则右子树上所有的节点值均大于它的根节点值。
3、它的左右子树也分别可以充当为二叉查找树。
4、每个节点的左子树和右子树的高度差至多等于1。
"""
class Node(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 0
class AvlTree(object):
def __init__(self):
self.root = None
def find(self, key):
if self.root is None:
return None
else:
return self._find(key, self.root)
def _find(self, key, node):
if node is None:
return None
elif key < node.key:
return self._find(key, self.left)
elif key > node.key:
return self._find(key, self.right)
else:
return node
def find_min(self):
if self.root is None:
return None
else:
return self._find_min(self.root)
def _find_min(self, node):
if node.left:
return self._find_min(node.left)
else:
return node
def find_max(self):
if self.root is None:
return None
else:
return self._find_max(self.root)
def _find_max(self, node):
if node.right:
return self._find_max(node.right)
else:
return node
def height(self, node):
if node is None:
return -1
else:
return node.height
def single_left_rotate(self, node):
k1 = node.left
node.left = k1.right
k1.right = node
node.height = max(self.height(node.right), self.height(node.left)) + 1
k1.height = max(self.height(k1.left), node.height) + 1
return k1
def single_right_rotate(self, node):
k1 = node.right
node.right = k1.left
k1.left = node
node.height = max(self.height(node.right), self.height(node.left)) + 1
k1.height = max(self.height(k1.right), node.height) + 1
return k1
def double_left_rotate(self, node):
node.left = self.single_right_rotate(node.left)
return self.single_left_rotate(node)
def double_right_rotate(self, node):
node.right = self.single_left_rotate(node.right)
return self.single_right_rotate(node)
def put(self, key):
if not self.root:
self.root = Node(key)
else:
self.root = self._put(key, self.root)
def _put(self, key, node):
if node is None:
node = Node(key)
elif key < node.key:
node.left = self._put(key, node.left)
if (self.height(node.left) - self.height(node.right)) == 2:
if key < node.left.key:
node = self.single_left_rotate(node)
else:
node = self.double_left_rotate(node)
elif key > node.key:
node.right = self._put(key, node.right)
if (self.height(node.right) - self.height(node.left)) == 2:
if key < node.right.key:
node = self.double_right_rotate(node)
else:
node = self.single_right_rotate(node)
node.height = max(self.height(node.right), self.height(node.left)) + 1
return node
def delete(self, key):
self.root = self.remove(key, self.root)
def remove(self, key, node):
if node is None:
raise KeyError, 'Error,key not in tree'
elif key < node.key:
node.left = self.remove(key, node.left)
if (self.height(node.right) - self.height(node.left)) == 2:
if self.height(node.right.right) >= self.height(node.right.left):
node = self.single_right_rotate(node)
else:
node = self.double_right_rotate(node)
node.height = max(self.height(node.left), self.height(node.right)) + 1
elif key > node.key:
node.right = self.remove(key, node.right)
if (self.height(node.left) - self.height(node.right)) == 2:
if self.height(node.left.left) >= self.height(node.left.right):
node = self.single_left_rotate(node)
else:
node = self.double_left_rotate(node)
node.height = max(self.height(node.left), self.height(node.right)) + 1
elif node.left and node.right:
if node.left.height <= node.right.height:
min_node = self._find_min(node.right)
node.key = min_node.key
node.right = self.remove(node.key, node.right)
else:
max_node = self._find_max(node.left)
node.key = max_node.key
node.left = self.remove(node.key, node.left)
node.height = max(self.height(node.left), self.height(node.right)) + 1
else:
if node.right:
node = node.right
else:
node = node.left
return node
if __name__ == '__main__':
avlTree = AvlTree()
avlTree.put(1)
avlTree.put(2)
avlTree.put(3)
avlTree.put(4)
avlTree.put(5)
avlTree.put(6)
avlTree.put(7)
avlTree.put(8)
print avlTree.find_max().key
avlTree.put(9)
print avlTree.find_max().key
print avlTree.find_min().key
|
40415732f901a2e44483c61ea3592665dc10f9bf | unupingu/CM6_control_software | /Robot_Program/get_send_data.py | 7,359 | 3.53125 | 4 | """ It can send to individual motors by adding joint prefix over commands:
Modes and commands available:
#### Commands need to be sent correctly or else it will be ignored. ####
#### replace words with numbers.Kp and speed can be float values!
1 - Go to position and hold:
h(position),speed,Kp,current_threshold
example: h100,20,3.1,12
2 - Speed to position and sent flag
s(position),speed
3 - Gravitiy compensation mode
g(current_threshold),compliance_speed
4 - Position hold mode
p(Kp),current_threshold
5 - Speed mode with direction
o(direction 0 or 1),speed
6 - Jump to position
j(position),Kp,current_threshold
7 - Voltage mode
v(direction 0 or 1),voltage(0-1000)
8 - Disable motor
d
9 - Enable motor
e
10 - Clear error
c
11 - Change motor data
i(Error_temperature),Error_current,Serial_data_outpu_interval
12 - teleoperation mode
x(position),speed,K1_t,K2_t,K3_t,K4_t
// K1_t is most important, K2_t is for speed while
// K3_t and K4_t are for current but they tend to make whole system unstable so be carefull
// TO disable K3_t enter value 0, to disable K4_t enter value !!!!LARGER!!!! then short circuit current!!!
Now if no commands is to be sent to motors, Joint level data sender needs to send dummy code.
If dummy code is not sent controller will report error and probably send motors to gravity compensation. """
import serial as sr
import time
import numpy as np
import axes_robot as rbt
s = sr.Serial(timeout = None)
s.baudrate = 10e6
s.port = '/dev/ttyACM0'
# If there is no serial device available on '/dev/ttyACM0' software will not run
s.open() #Comment this out if you want to run the software without device connected
print(s.name)
def send_dummy_data():
s.write(b'#')
s.write(b'\n')
def GOTO_position_HOLD(Joint_, Position_, Speed_, Kp_, Current_):
s.write(b'h')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(Position_)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Speed_,4)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Kp_,2)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Current_)), encoding="ascii"))
s.write(b'\n')
def Speed_Flag(Joint_, Position_, Speed_):
s.write(b's')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(Position_)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Speed_,4)), encoding="ascii"))
s.write(b'\n')
def Gravity_compensation(Joint_, Current_, Comp_):
s.write(b'g')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(Current_)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Comp_)), encoding="ascii"))
s.write(b'\n')
def Disable(Joint_):
s.write(b'd')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(b'\n')
def Enable(Joint_):
s.write(b'e')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(b'\n')
def Strong_position_hold(Joint_, Kp_, Current_):
s.write(b'p')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(round(Kp_,3)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Current_)), encoding="ascii"))
s.write(b'\n')
def Speed_Dir(Joint_, Dir_, Speed_):
s.write(b'o')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(Dir_), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Speed_,4)), encoding="ascii"))
s.write(b'\n')
def Voltage_Mode(Joint_, Dir_, Voltage_):
s.write(b'v')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(Dir_), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Voltage_)), encoding="ascii"))
s.write(b'\n')
def Clear_Error(Joint_):
s.write(b'c')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(b'\n')
def Jump_position(Joint_, Position_, Kp_, Current_):
s.write(b'j')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(Position_)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Kp_,3)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Current_)), encoding="ascii"))
s.write(b'\n')
def Change_data(Joint_, E_temp, E_Current, Serial_data_output_interval):
s.write(b'i')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(E_temp)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(E_Current)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(int(Serial_data_output_interval)), encoding="ascii"))
s.write(b'\n')
def teleop_mode(Joint_,Position_,Speed_,K1_t,K2_t,K3_t,K4_t):
s.write(b'x')
s.write(bytes(str(Joint_), encoding="ascii"))
s.write(bytes(str(int(Position_)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(Speed_,2)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(K1_t,3)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(K2_t,3)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(K3_t,3)), encoding="ascii"))
s.write(b',')
s.write(bytes(str(round(K4_t,3)), encoding="ascii"))
s.write(b'\n')
#initiate arrays
position_var = [None] * rbt.Joint_num
position_var_RADS = [None] * rbt.Joint_num
speed_var = [None] * rbt.Joint_num
current_var = [None] * rbt.Joint_num
temperature_var = [None] * rbt.Joint_num
speed_var_RADS = [None] * rbt.Joint_num
def get_data(data_rec_):
''' data gets received in this order: position,current,speed,temperature,voltage,error '''
data_split = data_rec_.split(b',') # Data split splits all data on "," and places it in array
# Fill arrays with data points received
for x in range(rbt.Joint_num):
position_var[x] = int(data_split[x].decode("utf-8"))
position_var_RADS[x] = rbt.E2RAD(position_var[x],x)
current_var[x] = int(data_split[x + rbt.Joint_num].decode("utf-8"))
speed_var[x] = int(data_split[x + rbt.Joint_num * 2].decode("utf-8"))
speed_var_RADS[x] = rbt.RPM2RADS(speed_var[x],x)
temperature_var[x] = int(data_split[x + rbt.Joint_num * 3].decode("utf-8"))
voltage_var = int(data_split[4 * rbt.Joint_num].decode("utf-8"))
error_var = int(data_split[4 * rbt.Joint_num + 1].decode("utf-8"))
return position_var, position_var_RADS, current_var, speed_var, speed_var_RADS, temperature_var, voltage_var, error_var
def main_comms_func():
data_rec = s.readline()
#print(data_rec)
d1,d2,d3,d4,d5,d6,d7,d8 = get_data(data_rec)
return d1,d2,d3,d4,d5,d6,d7,d8
def try_reconnect():
try:
s.close()
time.sleep(0.01)
s.open()
time.sleep(0.01)
except:
print("no serial available")
if __name__ == "__main__":
#Enable(2)
#Clear_Error(2)
while(1):
try:
#bg = time.time()
a1,a2,a3,a4,a5,a6,a7,a8 = main_comms_func()
#print(time.time() - bg)
#print(a1)
#print(a2)
#print(a3)
#time.sleep(0.01)
#teleop_mode(2,2000,0,18,0,0.7,1000) # 0.7, 1000
#Disable(2)
except:
try_reconnect()
|
cef780a6d5137fc6b1d676a160e27a65f7d05760 | renyuntao/Levenshtein_Distance | /LevenshteinDistance.py | 977 | 3.671875 | 4 | #!/usr/bin/env python
def LevenshteinDistance(s,t): #要进行比较的两个字符串s,t
m,n = len(s),len(t) #m,n分别为字符串s,t的长度
#创建一个二维数组d,d[i][j]表示字符串s的前i位与字符串t的前j位之间的Leventeish Distance
#注意二维数组的元素个数是(m+1)*(n+1)
d = [[0 for j in range(n+1)] for i in range(m+1)]
for i in range(1,m+1):
d[i][0] = i
for j in range(1,n+1):
d[0][j] = j
for i in range(1,m+1):
for j in range(1,n+1):
if s[i-1] == t[j-1]:
d[i][j] = d[i-1][j-1]
else:
d[i][j] = min(d[i-1][j]+1, #t delete a char
d[i][j-1]+1, #t insert a char
d[i-1][j-1]+1) #t substitute a char
return d[m][n]
############### DEMO ################
#s:WOMAN
#t:WOMEN
s = 'WOMAN'
t = 'WOMEN'
dis = LevenshteinDistance(s,t)
print('Levenshtei Distance:',dis)
|
153b6bb8076ee436c6bb7828c85f3bc629733389 | HHorge/ITGK | /ITGK Øving 1/Tetraeder.py | 493 | 3.765625 | 4 | import math
hoyde = float(input("Velg høyden til tetraeden: "))
areal = hoyde*(3/math.sqrt(6))
volum = (math.sqrt(2)*areal**3)/12
overflateAreal = math.sqrt(3)*areal**2
print("Overflatearealet er: ", format(overflateAreal, ".2f"))
#print("Volumet er: ", format(volum, ".2f"))
#print("Arealet er: ", format(areal, ".2f"))
print("Et tetraheder med høyde ", hoyde, " har volum ", format(volum, ".2f"), " og areal ", format(areal, ".2f"), ".", sep="")
|
0ce4e939333927d007649ce44b520d9b4a009225 | HHorge/ITGK | /ITGK Øving 2/Billettpriser og rabatter.py | 2,152 | 3.640625 | 4 | #Oppgave a)
fullpris = 440
minipris = 199
miniprisDager = 14
femtiProsent = fullpris / 2
tjuefemProsent = fullpris * 0.75
alderBarn = 16
alderSenior = 60
alderSvar = 0
miniprisSvar = ""
uniformStudent = ""
dagerTilReise = int(input("Hvor mange dager er det til du skal reise? "))
if dagerTilReise >= miniprisDager:
print("Du kan få minipris til ", minipris, ",- Disse billettene kan ikke endres/refunderes", sep="")
svar = input("Ønsker du fortsatt minipris (j/n)")
if svar == "j" or svar == "J":
print("Takk for pengene, god reise!")
elif svar == "n" or svar == "N":
alderSvar = int(input("Skriv inn alderen din: "))
if alderSvar < alderBarn:
print("Prisen på biletten blir: ", femtiProsent, ",-", sep="")
elif alderSvar >= alderSenior:
print("Prisen på biletten blir: ", tjuefemProsent, ",-", sep="")
else:
uniformStudent = input("Er du student, eller militær personell som kommer til å bruke uniform under reisen (j/n)?")
if uniformStudent == "j" or uniformStudent == "J":
print("Prisen på biletten blir: ", tjuefemProsent, ",-", sep="")
elif uniformStudent == "n" or uniformStudent == "N":
print("Prisen på biletten blir: ", fullpris, ",-", sep="")
elif dagerTilReise < miniprisDager:
print("Det er for sent for minipris, men du har kanskje rett på rabatt")
alderSvar = int(input("Skriv inn alderen din: "))
if alderSvar < alderBarn:
print("Prisen på biletten blir: ", femtiProsent, ",-", sep="")
elif alderSvar >= alderSenior:
print("Prisen på biletten blir: ", tjuefemProsent, ",-", sep="")
else:
uniformStudent = input("Er du student, eller militær personell som kommer til å bruke uniform under reisen (j/n)?")
if uniformStudent == "j" or uniformStudent == "J":
print("Prisen på biletten blir: ", tjuefemProsent, ",-", sep="")
elif uniformStudent == "n" or uniformStudent == "N":
print("Prisen på biletten blir: ", fullpris, ",-", sep="")
|
85df4c8d7444e70e9fd51b440689dcd40e847c71 | HHorge/ITGK | /ITGK Øving 6/Lotto.py | 1,371 | 3.65625 | 4 | import random
numbers = list(range(1,35))
myGuess = [4, 7, 15, 33, 17, 29, 19]
lottoNum = 7
antallTilleggstall = 3
tilleggstall = []
result = []
myGuess.sort()
def compList(guess, result):
result.sort()
guess.sort()
correct = 0
for a in range(len(guess)):
for i in range(len(result)):
if guess[a] == result[i]:
correct += 1
return correct
#returnerer hvilke tall som er like
#return set(guess).intersection(result)
def lottoNumbers(num):
lottoResult = []
for x in range(num):
#Lager lottorekke ved å velge "num" tall fra "numbers" og setter de i en ny "lottoresult"-array
lottoResult.append(numbers.pop(random.randint(0, len(numbers) - 1)))
return lottoResult
#Tilfeldige hovedtall
lottoResult = lottoNumbers(lottoNum)
#Tilfeldige tilleggstall
tilleggResult = lottoNumbers(antallTilleggstall)
#Sammenligner lottotallene og tilleggstallene med "myGuess"
correctHoved = compList(myGuess, lottoResult)
correctTillegg = compList(myGuess, tilleggResult)
print("Du har ", correctHoved, " riktig(e) hovedtall, og ", correctTillegg," riktig(e) tilleggstall.", sep="")
#Setter sammen hoved og tilleggstallene
result = lottoResult + tilleggResult
print("Din lottorekke:\n", myGuess)
print("Lottorekke med tilleggstall:\n", result)
|
6b914a2b5fed89bdc6636df808b2455b0177fae8 | HHorge/ITGK | /ITGK Øving 2/Generelt om betingelser.py | 581 | 3.90625 | 4 | tallA = int(input("Skriv inn et heltall: "))
tallB = int(input("Skriv inn et nytt heltall: "))
tallX = 3
tallY = 4
#Oppgave a)
sumAB = tallA + tallB
produktAB = tallA * tallB
produktXY = tallX * tallY
if sumAB < produktAB:
print(sumAB)
elif sumAB > produktAB:
print(produktAB)
elif sumAB == produktAB:
print("Summen og produktet er det samme.")
#Oppgave b)
print("Hva er ",tallX,"*",tallY,"? ", end="")
inputProdukt = int(input("Svar: "))
if inputProdukt == produktXY:
print("Det stemmer!")
else:
print("Svaret er dessverre feil.")
|
c37571ee0c33942b085042ce422d67a5f9ccec0e | Taral-Patoliya/asssignment-1 | /asn3.py | 1,474 | 3.578125 | 4 | def readFile(filename):
from itertools import islice
data = []
with open(filename, 'r') as infile:
while True:
next_n_lines = list(islice(infile, 3))
if not next_n_lines:
break
raw = []
for line in next_n_lines:
line = line.strip("\n")
line = line.strip('[').strip(']').strip('{').strip('}').split("\n")
if line[0] == "":
continue
raw.append(line)
data.append(raw)
returnData = []
for line in data:
returnRaw = []
for tupple in line:
returnRaw+=tupple[0].split(";")
returnData.append(returnRaw)
return returnData
def writeCsv(data):
import csv
with open("leafs.csv","w") as csvFile:
fieldNames = data[0]
del data[0]
writer = csv.DictWriter(csvFile,fieldNames)
writer.writeheader()
for row in data:
#Some problem with data being written in csv`#
writable = dict(zip(fieldNames,row))
writer.writerow(writable)
def correctDate(row):
import datetime
#Need to correct the date by comparing the date column from row and todays date#
#check http://stackoverflow.com/questions/2217488/age-from-birthdate-in-python#
return row
data = [["#","NAME","POSITION","AGE","HEIGHT","WEIGHT","BIRTHDAY"]]
data+=readFile("leafs.dmbfmt")
writeCsv(data)
|
d0d009499f6dd7f4194f560545d12f82f2b73db8 | starlinw5995/cti110 | /P4HW1_Expenses_WilliamStarling.py | 1,358 | 4.1875 | 4 | # CTI-110
# P4HW1 - Expenses
# William Starling
# 10/17/2019
#
# This program calculates the users expenses.
# Initialize a counter for the number of expenses entered.
number_of_expenses = 1
# Make a variable to control loop.
expenses = 'y'
# Enter the starting amount in your account.
account = float(input('Enter starting amount in account? '))
print()
#Make a variable for the total of the expenses.
total_expenses = 0
# Begin the loop.
while expenses == 'y':
# Get the expenses.
expenses = float(input('Enter expense ' + str(number_of_expenses) + ' : '))
#Calculate the total of expenses.
total_expenses = total_expenses + expenses
# Add 1 to the expense line everytime.
number_of_expenses = number_of_expenses + 1
# Ask if you want another expense.
expenses = input('Do you want to enter another expense? (y/n) ')
print()
# Display amount in account to begin with.
if expenses == 'n':
print('Amount in account before expense subtraction $',
format(account,'.0f'))
# Display number of expenses used.
print('Number of expenses entered:', number_of_expenses - 1 ,'')
print()
#Calculate and display amount left in account.
print('Amount in account AFTER expenses subtracted is $',
format(account - total_expenses,'.0f'))
|
1c1c74935df679ea35ad9b7bc962963c085e453a | morrigan-dev/python-examples | /Py4ePlus/examples/chapter12/ExercisePy4eC12.py | 5,172 | 3.671875 | 4 | '''
Created on 17.03.2020
Hier werden die Aufgaben aus dem Kurs 'Python for everbody - Kapitel 12' gelöst.
@author: morrigan
@see: https://www.py4e.com/html3/12-network
'''
import socket
import urllib.request
from examples import print_exercise
from examples import print_header
print_header("Python for everybody - Kapitel 12 - Exercises")
# Exercise 1
task = """Exercise 1: Change the socket program 'socket1.py' to prompt the user for the URL so it can read any web page.
You can use 'split('/')' to break the URL into its component parts so you can extract the host name for the socket
'connect' call. Add error checking using 'try' and 'except' to handle the condition where the user enters an improperly
formatted or non-existent URL."""
print_exercise(task)
domain = None
url = input("Enter a url: ")
if len(url) < 1:
url = "http://data.pr4e.org/romeo.txt"
domain = "data.pr4e.org"
else:
url_parts = url.split("/")
if len(url_parts) >= 2 and len(url_parts[2]) > 0:
domain = url_parts[2]
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
mysock.connect((domain, 80))
cmd = "GET {} HTTP/1.0\r\n\r\n".format(url).encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(), end='')
except InterruptedError as e:
print(e)
print()
# Exercise 2
task = """Exercise 2: Change your socket program so that it counts the number of characters it has received and stops
displaying any text after it has shown 3000 characters. The program should retrieve the entire document and count
the total number of characters and display the count of the number of characters at the end of the document."""
print_exercise(task)
content = ""
char_counter = 0
domain = None
url = input("Enter a url: ")
if len(url) < 1:
url = "http://data.pr4e.org/romeo.txt"
domain = "data.pr4e.org"
else:
url_parts = url.split("/")
if len(url_parts) >= 2 and len(url_parts[2]) > 0:
domain = url_parts[2]
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
mysock.connect((domain, 80))
cmd = "GET {} HTTP/1.0\r\n\r\n".format(url).encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
content = "".join([content, data.decode()])
except InterruptedError as e:
print(e)
content_len = len(content)
max_output_len = 3000
if content_len < max_output_len:
max_output_len = content_len
print(content[:max_output_len])
print("Gesamtanzahl an Zeichen:", content_len)
print()
# Exercise 3
task = """Exercise 3: Use urllib to replicate the previous exercise of
(1) retrieving the document from a URL,
(2) displaying up to 3000 characters, and
(3) counting the overall number of characters in the document.
Don't worry about the headers for this exercise, simply show the first 3000 characters of the document contents."""
print_exercise(task)
content = ""
with urllib.request.urlopen("http://data.pr4e.org/romeo.txt") as response:
print(response)
for line in response:
content = "".join([content, line.decode()])
content_len = len(content)
max_output_len = 3000
if content_len < max_output_len:
max_output_len = content_len
print(content[:max_output_len])
print("Gesamtanzahl an Zeichen:", content_len)
print()
# Exercise 4
task = """Exercise 4: Change the urllinks.py program to extract and count paragraph (p) tags from the retrieved
HTML document and display the count of the paragraphs as the output of your program.
Do not display the paragraph text, only count them. Test your program on several small web pages as well as some
larger web pages."""
print_exercise(task)
print("Nicht möglich ohne BeautifulSoup Lib!")
print()
# Exercise 5
task = """Exercise 5: (Advanced) Change the socket program so that it only shows data after the headers
and a blank line have been received. Remember that recv receives characters (newlines and all), not lines."""
print_exercise(task)
print_content = False
domain = None
url = input("Enter a url: ")
if len(url) < 1:
url = "http://data.pr4e.org/romeo.txt"
domain = "data.pr4e.org"
else:
url_parts = url.split("/")
if len(url_parts) >= 2 and len(url_parts[2]) > 0:
domain = url_parts[2]
content = ""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
mysock.connect((domain, 80))
cmd = "GET {} HTTP/1.0\r\n\r\n".format(url).encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
recv_content = data.decode()
index = recv_content.find("\r\n\r\n")
if print_content:
content = "".join([content, recv_content])
if index >= 0 and not print_content:
print("Header Ende gefunden:", index)
print_content = True
content = "".join([content, recv_content[index + 4:]])
except InterruptedError as e:
print(e)
print(content) |
6c111c506883556c342d5961c06eea7eae5c5554 | morrigan-dev/python-examples | /Py4ePlus/examples/chapter10/ExercisePy4eC10.py | 3,808 | 3.90625 | 4 | '''
Created on 12.03.2020
Hier werden die Aufgaben aus dem Kurs 'Python for everbody - Kapitel 10' gelöst.
@author: morrigan
@see: https://www.py4e.com/html3/10-tuples
'''
import string
from examples import DATA_PATH
from examples import print_exercise
from examples import print_header
print_header("Python for everybody - Kapitel 10 - Exercises")
# Exercise 1
task = "Exercise 1: Revise a previous program as follows: Read and parse the 'From' lines and pull out the addresses \
from the line. Count the number of messages from each person using a dictionary. \
After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples \
from the dictionary. Then sort the list in reverse order and print out the person who has the most commits."
code = """Sample Line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Enter a file name: mbox-short.txt
cwen@iupui.edu 5
Enter a file name: mbox.txt
zqian@umich.edu 195"""
print_exercise(task, code)
filenames = ["mbox-short.txt", "mbox.txt"]
for fname in filenames:
counter_dict = dict()
with open(DATA_PATH / fname) as file_handle:
for line in file_handle:
if line.startswith("From "):
words = line.split()
if len(words) >= 2:
address = words[1]
counter_dict[address] = counter_dict.get(address, 0) + 1
# print("counter_dict =", counter_dict)
counter_list = []
for (address, amount) in counter_dict.items():
counter_list.append((amount, address))
# print("counter_list =", counter_list)
counter_list.sort(reverse=True)
print(counter_list[0][1], counter_list[0][0])
# Exercise 2
task = "Exercise 2: This program counts the distribution of the hour of the day for each of the messages. \
You can pull the hour from the 'From' line by finding the time string and then splitting that string into parts \
using the colon character. Once you have accumulated the counts for each hour, print out the counts, one per line, \
sorted by hour as shown below."
code = """python timeofday.py
Enter a file name: mbox-short.txt
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1"""
print_exercise(task, code)
counter_dict = dict()
with open(DATA_PATH / "mbox-short.txt") as file_handle:
for line in file_handle:
if line.startswith("From "):
words = line.split()
if len(words) >= 6:
date = words[5]
hour = date.split(":")[0]
counter_dict[hour] = counter_dict.get(hour, 0) + 1
print("counter_dict =", counter_dict)
counter_list = list(counter_dict.items())
print("counter_list =", counter_list)
counter_list.sort()
for (hour, amount) in counter_list:
print(hour, amount)
# Exercise 4:
task = "Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency. \
Your program should convert all the input to lower case and only count the letters a-z. Your program should not \
count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from several different \
languages and see how letter frequency varies between languages. Compare your results with the tables at \
https://wikipedia.org/wiki/Letter_frequencies."
print_exercise(task)
counter_dict = dict()
total = 0
with open(DATA_PATH / "silmarillion.txt") as file_handle:
for line in file_handle:
line = line.translate(line.maketrans("", "", string.punctuation)).strip().lower()
for letter in line:
if "a" <= letter <= "z":
counter_dict[letter] = counter_dict.get(letter, 0) + 1
total += 1
counter_list = list(counter_dict.items())
counter_list.sort()
for (letter, amount) in counter_list:
print(letter, amount * 100 / total) |
640dfdc924e53dc061f44234db31c183ee705db0 | morrigan-dev/python-examples | /Py4ePlus/examples/threads/LocksAndSyncLowApi.py | 1,342 | 3.78125 | 4 | import _thread
import time
from examples import print_header
class LocksAndSyncLowApi:
def __init__(self):
self.__daten = 0
# Lock-Objekt für die Synchronisation
self.lock = _thread.allocate_lock()
def getTitle(self):
return "Threads - Locks und Synchronisation mit 'Low Level API'"
# Funktion, die als Thred ausgeführt werden soll
def synced_ausgabe(self, thread_name, delay):
count = 0
while count < 10:
self.lock.acquire()
count += 1 # nicht atomar!
self.__daten += 1 # nicht atomar!
print("Thread: {}, globale Daten: {}".format(thread_name, self.__daten)) # nicht atomar!
self.lock.release()
def main(self):
print("Enter Drücken, um Beispiel abzubrechen")
# Erstellung eines Threads
try:
_thread.start_new_thread(self.synced_ausgabe, ("Mein-Thread-1", 1, ))
_thread.start_new_thread(self.synced_ausgabe, ("Mein-Thread-2", 2, ))
_thread.start_new_thread(self.synced_ausgabe, ("Mein-Thread-3", 5, ))
except:
print("Fehler beim Start eines Threads")
print("Enter Drücken, um Beispiel abzubrechen")
while True:
if not input(): break
print("Beispiel wurde abgebrochen")
print()
|
4bf380a2ccd68ec238cc4442211ae172aa74bc49 | morrigan-dev/python-examples | /Py4ePlus/examples/chapter14/ExamplesC14.py | 2,019 | 3.609375 | 4 | '''
Created on 19.03.2020
In diesem Modul sind Beispiele zu folgenden Themen enthalten:
- Objektorientierte Programmierung
@author: morrigan
@see: https://www.py4e.com/html3/14-objects
@see: https://www.linkedin.com/learning/oop-mit-python/willkommen-zu-oop-mit-python
'''
from examples.chapter14.konto.Bankenprogramm import Bankenprogramm
from examples.chapter14.konto.Konto import Konto
from examples.chapter14.konto.KontoMitSlots import KontoMitSlots
from examples.chapter14.tiere.Tierprogramm import Tierprogramm
from examples.chapter14.tiere.Tier import Tier
from copy import copy
from copy import deepcopy
class PartyAnimal:
x = 0
def party(self):
self.x = self.x + 1
print("So far", self.x)
animal = PartyAnimal()
animal.party()
animal.party()
animal.party()
PartyAnimal.party(animal)
Tierprogramm()
prog = Bankenprogramm()
prog.main()
konto = Konto(1000, "Girokonto")
print("Das Dictionary __dict___:", konto.getKontostand(), konto.__dict__)
konto.eigentuemer = "Thomas"
print("Das Dictionary __dict___:", konto.getKontostand(), konto.__dict__)
konto.zuruecksetzen = Bankenprogramm.konto_zuruecksetzen
print("Das Dictionary __dict___:", konto.getKontostand(), konto.__dict__)
konto.zuruecksetzen(konto)
print("Das Dictionary __dict___:", konto.getKontostand(), konto.__dict__)
konto.getTyp = lambda: konto.kontotyp
print("Das Dictionary __dict___:", konto.getTyp(), konto.__dict__)
unveraenderlichesKonto = KontoMitSlots(1000, "Girokonto")
try:
print("__dict___:", unveraenderlichesKonto.__dict__)
except AttributeError as e:
print(e)
print("__slots__", unveraenderlichesKonto.__slots__)
# Dynamisch erzeugte Klassen zur Laufzeit
DynamicClassTier = type("Tier", (), {"alter": 3})
tier = DynamicClassTier()
print("Typ der Klasse: {}, Alter: {}".format(type(tier), tier.alter))
# Kopieren / Klonen von Objekten
t1 = Tier(2)
print(t1.alter)
t2 = t1
t3 = copy(t1)
t4 = deepcopy(t1)
t2.alter = 3
print(t1.alter)
t3.alter = 4
print(t1.alter)
t4.alter = 5
print(t1.alter)
|
c47e419fdebe6e8968e8ab4d0ae68a7cc0a40443 | RohanGautam/My_applications | /meritnation_getanswer.py | 838 | 3.65625 | 4 | '''With this, one can get all the answers to a given question on a site called meritnation.
Meritnation is a student-oriented site where teachers answer questions and stuff.
You need to "log in"(not with facebook, google or anything), and need to give your phone number to access the full answer(s).
This is just a really simple workaround that gets the answer and saves it in an html file and can thus be viewed, including all the mathml formulae.'''
import requests,re
link=raw_input('Enter meritnation answer link:')
pagesrc=requests.get(link)
pattern=r'<div class="ans_text">.*?<\/div>' #non-greedy selection
f=open(r'answer.html','w+')
f.write('\n-------------------------------------------------------------------------------'.join(re.findall(pattern,pagesrc.text)))
print '\n\nAnswer saved in "answer.html" !!'
f.close() |
758b7d6b57bee60d06202439bfc5d1ceec2f70da | ManchesterMakerspace/RSServer | /RSServer.py | 2,164 | 3.53125 | 4 | #!/usr/bin/env python
import web
import schedule
import time
import threading
from threading import Thread
#This is a server meant to handle http request, web-hooks, ect. as well as trigger http requests, and run local scripts on response or schedules.
#======== -- CLASSES -- ============================================================================================================================================================
class schedules:
def job(self):
print("Scheduled job executed.")
def run(self):
print("Setup and run scheduled jobs.")
job = schedules().job
schedule.every(5).seconds.do(job)
schedule.every(1).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
while True:
schedule.run_pending()
time.sleep(1)
class httprequest:
def GET(self):
print "redirect_GET"
#======== -- MAIN -- ============================================================================================================================================================
#When the Python interpreter reads a source file, it executes all of the code found in it.
#Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
if __name__ == '__main__':
#app will listen for requests/hooks, then interpret how/if to execute a response.
print("Setup and run app request listener.")
#urls = capture that piece of the matched data, the second part is the name of a class to send the request to
urls = (
'/test', 'httprequest',
)
app = web.application(urls, globals())
Thread(target = app.run()).start()
#Schedules runs in parrellel with app
sch = schedules()
Thread(target = sch .run()).start()
|
31006ce19aff9efb52bd4dc999ccb0ec0f54f4d5 | Laith967/hangman | /hangman.py | 1,410 | 3.921875 | 4 | import random
words = ('python', 'java', 'kotlin', 'javascript')
random_word = list(random.choice(words))
# help_word = random_word[:3] + (len(random_word) - 3) * '-'
word = list(len(random_word) * '-')
old_letter = set()
print("H A N G M A N")
tries = 8
while True:
play_exit = input('Type "play" to play the game, "exit" to quit:')
if play_exit == 'exit':
break
elif play_exit == 'play':
while tries and '-' in word:
print('\n' + ''.join(word))
letter = input("Input a letter: ")
if len(letter) > 1:
print("You should input a single letter")
elif letter.istitle() or not letter.isalpha():
print("It is not an ASCII lowercase letter")
elif letter in old_letter:
print("You already typed this letter")
else:
old_letter.add(letter)
while random_word.count(letter):
word[random_word.index(letter)] = letter
random_word[random_word.index(letter)] = '-'
if not random_word.count(letter):
break
print()
else:
print("No such letter in the word")
tries -= 1
print(f"\n{''.join(word)}\nYou guessed the word!\nYou survived!" if '-' not in word else "You are hanged!")
|
3a0f1e27326226da336ceb45290f89e83bb1f781 | dosatos/LeetCode | /Easy/arr_single_number.py | 2,254 | 4.125 | 4 | """
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Clarification questions:
How big is N?
Solution:
The easiest solution would be to use a dictionary:
- add to the dict each value seen with a value of 1
- and set the value to zero if the integer was seen twice
- after looping once, find a value with a value of 1
"""
import collections
class Solution:
def singleNumber(self, nums):
"""
using XOR operator
:type nums: List[int]
:rtype: int
"""
res = 0
for num in nums:
res ^= num
return res
# def singleNumber(self, nums):
# """
# using Counter instead
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = collections.Counter(nums)
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 1:
# return k # Total complexity is O(N) in the worst case
# return 0 # in case the list is empty
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# # use a container to look up value at a constant cost
# # worst complexity O(N)
# container = {}
# for num in nums:
# try: # increase by one if seen already
# container[num] += 1
# except: # add the number to the container otherwise
# container[num] = 0
# # find the value that was seen only once
# # worst complexity O((N-1)/2 + 1) => O(N) if N is very large
# for k, v in container.items():
# if v == 0:
# return k
# return 0
# # total complexity is O(N)
|
2fc808a248480a8840944c8e927ebdb2f23e854a | dosatos/LeetCode | /Easy/ll_merge_two_sorted_lists.py | 2,574 | 4.125 | 4 | """
Percentile: 97.38%
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
Change "pointers" as in merge sort algorithm.
Time Complexity = O(N+M)
Space complexity = O(1)
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# node1, node2 = l1, l2
# head = ListNode(0)
# node = head
# while node1 and node2:
# if node1.val <= node2.val:
# tmp = node1.next # save tmp
# node.next = node1 # append
# node = node.next # increment
# node.next = None # clean up node
# node1 = tmp # use tmp
# else:
# tmp = node2.next
# node.next = node2
# node = node.next
# node.next = None
# node2 = tmp
# if node1:
# node.next = node1
# else:
# node.next = node2
# return head.next
# def mergeTwoLists(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# if not l1:
# return l2
# if not l2:
# return l1
# if l1.val < l2.val:
# l1.next = self.mergeTwoLists(l1.next, l2)
# return l1
# else:
# l2.next = self.mergeTwoLists(l2.next, l1)
# return l2
# def mergeTwoLists(self, a, b):
# if not a or b and a.val > b.val:
# a, b = b, a
# if a:
# a.next = self.mergeTwoLists(a.next, b)
# return a
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1: return l2
if not l2: return l1
if l1.val < l2.val:
l3, l1 = l1, l1.next
else:
l3, l2 = l2, l2.next
cur = l3
while l1 and l2:
if l1.val < l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return l3 |
a5538a51d2b55f585e3acdf24a637d8264c469e1 | dosatos/LeetCode | /Easy/twoSum.py | 550 | 3.671875 | 4 | class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
storage = {} # where I will save difference and position; space complexity O(N)
for idx, num in enumerate(nums): # time complexity O(N)
lookup_diff = target - num # looking for this difference
if lookup_diff in storage:
return [storage[lookup_diff], idx];
else:
storage[num] = idx
return "Not found"; |
90487aa711f5127e6bd404f80014d900255f0606 | jhein1511/WD1_Homework | /Python/Guess_the_secret_number/guess_the_secret_number_1.1.py | 484 | 3.859375 | 4 | import random
def main():
secret = random.randint(1, 51)
while True:
guess = int(raw_input("Guess the secret number which is between 1 and 50: "))
if secret == guess:
print "Congratulations, you're right!"
break
elif guess < secret:
print "Sorry, your guess is too low. Try again!"
elif guess > secret:
print "Sorry, your guess is too high. Try again!"
if __name__ == "__main__":
main()
|
e57878ba5db521e72f2db5bd5883c6f7abc13ec2 | t-ah/adventofcode-2019 | /day6.py | 1,071 | 3.703125 | 4 | from collections import defaultdict
def count_orbits(is_orbiting, o_counts, name):
if name in o_counts:
return o_counts[name]
else:
return 1 + count_orbits(is_orbiting, o_counts, is_orbiting[name])
def path_to_com(name, is_orbiting):
path = set()
node = name
while(True):
path.add(node)
if node == "COM":
return path
node = is_orbiting[node]
with open("input6") as f:
lines = f.readlines()
is_orbiting = {}
o_counts = defaultdict(int)
o_counts["COM"] = 0
for line in lines:
orbits = line.strip().split(")")
is_orbiting[orbits[1]] = orbits[0]
result = 0
for orbiter in is_orbiting:
o_counts[orbiter] = count_orbits(is_orbiting, o_counts, orbiter)
result += o_counts[orbiter]
print(result)
start = is_orbiting["YOU"]
end = is_orbiting["SAN"]
path1 = path_to_com(start, is_orbiting)
path2 = path_to_com(end, is_orbiting)
inters = path1.intersection(path2)
nodes1 = path1.difference(inters)
nodes2 = path2.difference(inters)
result = len(nodes1) + len(nodes2)
print(result) |
91da2f554b9005de8297cfc33a5556b9dc2d82e4 | rpgiridharan/Ullas_Class | /Day11/email.py | 225 | 3.53125 | 4 | # email: alphanumeric chars followed by @ followed by alphabets followed by . followed by alphabets
a = ["sfsekf@segns", "sefsef", "hkopesri@sgoisg.sf"]
import re
print(list(filter(lambda x: re.match(r'\w+@[a-zA-Z]+\.[a-zA-Z]' , x), a)))
|
e0db93a72ccb67d3884507448fd15ac90622215c | rpgiridharan/Ullas_Class | /Day4/p1.py | 163 | 3.734375 | 4 | # Find sum of digits of a number
n = 12345
''' # TERRIBLE!!!
s = 0
while n:
s += n%10
n = n//10
print(s)
'''
# get all the digits of the number
# sum them up
|
2511dd499dc76d75b3c8fb7edea49c59fe8c5f3e | rpgiridharan/Ullas_Class | /Day7/quirky_for.py | 836 | 3.90625 | 4 | '''
x = 0
y = 5
for i in range(x, y):
print(i)
y = 10
print(i)
print (y)
'''
#-------------------
'''
for i in range(5):
print(i)
i = 10
print(i)
#-----------------------
'''
'''
x = [10, 20, 30]
for i in x:
print(i)
i += 100
print(i)
print(x)
'''
#-------------------------
'''
x = [[10], [20], [30]]
for i in x:
print(i)
i = i + [100]
print(i)
print(x)
'''
#--------------------------
'''
x = [[10], [20], [30]]
for i in x:
print(i)
i += [100]
print(i)
print(x)
'''
#-----------------------------
'''
x = [[10], [20], [30]]
for i in x:
print(i)
i = [200, 300]
print(x)
'''
#-----------------------------
'''
x = [10, 20, 30]
for i in x:
print(i)
x.append(40)
print(x)
'''
#--------------------------
'''
x = [10, 20, 30]
for i in x:
print(i)
x.append(40)
x = [50, 60]
print(x)
'''
#--------------------
|
f789bca691b4a9ccddb2214149f19381d7a27fff | SomaKorada07/EPAi | /session13-SomaKorada07/polygon.py | 2,153 | 3.734375 | 4 | """
polygon.py
"""
import math
class Polygon():
def __init__(self, num_edges, circumradius):
self.circumradius = circumradius
self.num_edges = num_edges
@property
def circumradius(self):
return self._circumradius
@circumradius.setter
def circumradius(self, circumradius):
self._circumradius = circumradius
@property
def num_edges(self):
return self._num_vertices
@property
def num_vertices(self):
return self._num_vertices
@property
def int_angle(self):
return self._int_angle
@property
def edge_len(self):
return self._edge_len
@property
def apothem(self):
return self._apothem
@property
def area(self):
return self._area
@property
def perimeter(self):
return self._perimeter
@num_edges.setter
def num_edges(self, num_edges):
self._num_edges = num_edges
self._num_vertices = num_edges
self._int_angle = (self._num_edges - 2) * (180 / self._num_edges)
self._edge_len = 2 * self._circumradius * math.sin(math.pi/self._num_edges)
self._apothem = self._circumradius * math.cos(math.pi/self._num_edges)
self._area = 0.5 * self._edge_len * self._apothem
self._perimeter = self._num_edges * self._edge_len
def __repr__(self):
return f"Polygon class with {self._num_edges} edges, {self._circumradius} circumradius, {self._int_angle} interior angle, {self._edge_len} edge length, {self._apothem} apothem, {self._area} area and {self._perimeter} perimeter"
def __eq__(self, polygon2):
if type(polygon2) is not Polygon:
raise TypeError("Expected type of Polygon.")
return (self._num_vertices == polygon2._num_vertices and self._circumradius == polygon2._circumradius)
def __gt__(self, polygon2):
if type(polygon2) is not Polygon:
raise TypeError("Expected type of Polygon.")
return (self._num_vertices > polygon2._num_vertices) |
066769bf25ea46c40333a8ddf2b87c35bfed4fae | arvindsankar/RockPaperScissors | /rockpaperscissors.py | 1,646 | 4.46875 | 4 | import random
def correct_input(choice):
while choice != "Rock" and choice != "Scissors" and choice != "Paper":
# corrects rock
if choice == "rock" or choice == "R" or choice == "r":
choice = "Rock"
# corrects scissors
elif choice == "scissors" or choice == "S" or choice == "s":
choice = "Scissors"
# corrects paper
elif choice == "paper" or choice == "P" or choice == "p":
choice = "Paper"
else:
print ("Sorry, didn't get that.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
return choice
print ("\nTo play, select one of the following choices: Rock, Paper, or Scissors.\n")
print ("Rock beats Scissors and loses to Paper.")
print ("Paper beats Rock and loses to Scissors")
print ("Scissors beats Paper and loses to Rock\n")
# prompt player for choice
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
# CPU randomly selects from this list of choices
CPUChoices = ["Rock", "Paper", "Scissors"]
# CPU
CPU = CPUChoices[random.randrange(0,3)]
while choice == CPU:
print ("You and the Computer both picked " + CPU + " so we'll try again.\n")
choice = input("Do you chose Rock, Paper, or Scissors? ")
choice = correct_input(choice)
CPU = CPUChoices[random.randrange(0,3)]
print ("\nYou chose: " + choice)
print ("Computer choses: " + CPU + "\n")
# Player choses Rock
if ( choice == "Rock" and CPU == "Paper"
or choice == "Paper" and CPU == "Scissors"
or choice == "Scissors" and CPU == "Rock"
):
print (CPU + " beats " + choice + ". You lose!")
else:
print (choice + " beats " + CPU + ". You win!")
print ("\nThanks for playing!")
|
47a08ff18de948da3b1e1913ad30b58d84498d52 | FabioHelmer/projeto-integrador | /Adjacente.py | 541 | 3.96875 | 4 | # DESENVOLVIDO POR:
# CARLOS BARAQUIEL STEIN DE MEDEIROS
# FABIO HELMER KUHN
# GABRIEL FELIX MENEZES DA SILVA
# JOÃO BATISTA MUYLAERT DE ARAUJO JUNIOR
# WESLEY MARQUES PIZETA
class Adjacente:
def __init__(self, escola, distancia):
# objeto criado para guardar a escola que é adjascente
# e guardar a distancia
self.escola = escola
self.distanciaAdjacencia = distancia
def setDistanciaAdjacencia(self, distancia):
self.distanciaAdjacencia = float(distancia)
def getDistanciaAdjacencia(self):
return self.distanciaAdjacencia
def getEscola(self):
return self.escola
|
704d49e1c41e8757fe1ee4f2f7fe9d961b8ec811 | pigzaza/TOTO-game | /Game1-About10 | 996 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 16 20:19:08 2018
@author: pigzaza
"""
import random
import tkinter
import os
def clear():os.system('clear')
print('\n\n____Hello everyone, this is a game for ToTo____')
name=input('\nwhat\'s your name:')
print('Now I know You are',name,'\n')
x=0
for i in range(10):
a= random.randint(1,10)
print(a,'+ ? = 10\n')
b=int(input('\033[0;30;31m\tPLease input the answer ^.^ -->\033[0m'))
ans=10-b
if ans==a:
clear()
print('\n\nvery good!!!!!')
print('__________________\n\n\n')
x+=10
print('\033[1;31;46m\t总分\033[0m',x)
print('还有',9-i,'个题目\n\n')
else:
clear()
print('\n\nIt is not right ~.~')
print('\033[1;31;46m\t总分\033[0m',x)
print('还有',9-i,'个题目\n\n')
i+=1
print('\n\n###恭喜,得到了',x,'!!!###\n\n\n bye bye~%s!\n\n\n',name)
|
bb9d03050b10c79aec9ba7cd4c881bca7bb9fe03 | riteshsharma29/Pandas_tips | /set1.py | 448 | 3.546875 | 4 | import pandas as pd
'''
Splitting delimeter(, ; | etc) separated values into multiple rows with only 2 columns data
'''
df = pd.read_excel("data.xlsx",sheet_name='setI')
df_new = df['Annual Budget'].str.split(',',expand=True).set_index(df['Department']).stack().reset_index(level=0,name='Annual Budget')
df_new = df_new.reset_index(drop=True)[['Department','Annual Budget']]
print(df_new)
df_new.to_excel("setI_Output.xlsx",index=False) |
5b3e55cfa06ac909731f5188ee737e93e1613559 | 18harsh/PythonBlog | /post_funct.py | 2,599 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 21:10:36 2020
@author: Harsh
"""
import sqlite3
from tkinter import *
import smtplib
from tkinter import messagebox
def post(author,title,content,date_posted):
args=[author,title,content,date_posted]
try:
conn = sqlite3.connect("lite.db")
cursor=conn.cursor()
add_user = ("INSERT INTO posts "
"(author,title,content,date_posted) "
"VALUES (?,?,?,?)")
cursor.execute(add_user,args) # executing the
conn.commit() # commiting the connection then closing it.
conn.close() # closing the connection of the database
messagebox.showwarning(' Success ',' Your blog has been posted')
return True
except pymysql.Error as error:
messagebox.showerror(' error ',"Failed inserting BLOB data into MySQL table {}".format(error))
def fetch_post():
try:
conn = sqlite3.connect("lite.db")
print("connection successful")
cursor=conn.cursor()
select_query = "SELECT * FROM posts"
cursor.execute(select_query) # executing the queries
posts= cursor.fetchall()
conn.commit() # commiting the connection then closing it.
conn.close()
if posts:
return(posts)
else:
messagebox.showerror("Error", "technical error")
except :
messagebox.showerror( "technical error","Try again later")
def update_post(user_name,new_title,new_content,post):
try:
conn = sqlite3.connect("lite.db")
print("connection successful")
cursor=conn.cursor()
select_query = "UPDATE posts SET title =?, content=? WHERE id=?"
val=(new_title,new_content,post[0])
cursor.execute(select_query,val)
conn.commit() # commiting the connection then closing it.
conn.close()
messagebox.showinfo(' success ',"post updated")
return True
except pymysql.Error as error:
messagebox.showerror(' Error ',"techninal error {}".format(error))
def search_name(x):
posts=fetch_post()
post=[]
for i in posts:
if i[1]==x:
post.append(i)
return post
def search_title(x):
posts=fetch_post()
print(x)
post=[]
for i in posts:
print (i)
if i[2]==x:
post.append(i)
return (post)
|
e8aea765d7af7dcd37ead5358ea403a33194ed88 | AHKerrigan/Coursera-Machine-Learning | /Assignment-1/Assignment1.py | 4,937 | 3.84375 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def loadData(file):
data = pd.read_csv(file, sep = ",", header=None)
return data
def createX(data):
"""Constructs the X matrix for our data based on the dataframe
provided
"""
X = []
for index, row in data.iterrows():
# We always consider x0 to be 1
new_row = [1]
for column in range(len(row) - 1):
new_row.append(row[column])
X.append(new_row)
return np.asmatrix(X)
def scatterPlot2D(data, m , b):
"""Takes in data, a slope, and a y intercept, and displays a scatterplot
with a predicted regression line
"""
dataframe = pd.DataFrame(data)
dfp = dataframe.plot(x=0, y=1, kind='scatter')
dfp.set_xlabel("Population")
dfp.set_ylabel("Profit")
# For the time being, the start values are hard coded
plt.plot([5, 25], [(5 * m + b), (25 * m + b)], 'k-', lw=2)
plt.show()
def computeCost(theta, X, y):
"""Takes in a hypothesis matrix and the feature vector, then computes
the current cost of the hypothesis
"""
sum = 0
m = len(X)
# Creates the matrix of predictions for the given theta
predictions = X * theta
for i in range(m):
sum = sum + (predictions[i] - y[i])**2
J = sum / (2 * m)
return J
def vectorize(features):
"""Takes in a set of features and returns a single column vector matrix
"""
y = []
for item in features:
y.append([item])
return np.asmatrix(y)
def gradientDescent(theta, X, y, alpha, iterations):
"""Takes an intial hypothesis theta, a set of features X, and a result
vector y and performs gradient descent to find a optimal theta
"""
# The number of iterations we'll be using
m = len(y)
for interation in range(iterations):
tempTheta = []
predictions = X * theta
# Performs the gradient descent algorithm on each feature
for j in range(len(theta)):
sum = 0
# The summation for the partial derivative with respect to theta-j
# The sum of the difference between the prediction and actual value
# times the corresponding x value
for i in range(m):
sum = sum + ((predictions.item(i) - y.item(i)) * X.item(i, j))
pDev = sum / m
# Multiplies the partial derivative by the learning rate
# Then subtracts that value from the current theta and updates the
# theta vector
tempTheta.append([theta.item(j) - (alpha * pDev)])
theta = np.asmatrix(tempTheta)
return theta
def normalEquation(X, y):
"""Computes the theta matrix using the normal Equation
"""
xTx = np.transpose(X).dot(X)
XtX = np.linalg.inv(xTx)
XtX_xT = XtX.dot(np.transpose(X))
theta = XtX_xT.dot(y)
return theta
def featureScale(features):
"""Scales the features such that each feature percentage of the maximum value
"""
maxes = []
new_matrix = []
# Finds the maximum value in each feature by iterating through the transpose of the
# matrix
for column in np.transpose(features):
maxes.append(np.amax(column))
for row in features:
new_column = []
for x in range(row.size):
new_column.append(row.item(x) / maxes[x])
new_matrix.append(new_column)
return np.asmatrix(new_matrix), maxes
def scaledGradientDescent(theta, X, y, alpha, iterations):
"""Scales each parameter before running it through gradient descent.
The fifth parameter is iterations
"""
scaledX, maxes = featureScale(X)
scaled_theta = gradientDescent(theta, scaledX, y, alpha, iterations)
return_theta = []
for i in range(len(maxes)):
return_theta.append([scaled_theta.item(i) / maxes[i]])
return np.asmatrix(return_theta)
if __name__ == "__main__":
data = loadData("data/ex1data1.txt")
X = createX(data)
y = vectorize(data[1])
# The initial learning rate and initial paremeters (for )
alpha = 0.01
theta = np.matrix([[0], [1]])
"""
perfect_theta = normalEquation(X, y)
new_theta = gradientDescent(theta, X, y, alpha, 10000)
scaled_new_theta = scaledGradientDescent(theta, X, y, alpha, 10000)
print("Perfect Theta: ", perfect_theta)
print("Gradient Descent: ", new_theta)
print("Scaled Gradient Descent: ", scaled_new_theta)
scatterPlot2D(data, theta.item(1), theta.item(0))
scatterPlot2D(data, new_theta.item(1), new_theta.item(0))
"""
print("Now doing multivariate")
# The initial learning rate and initial paremeters (for )
alpha = 0.01
theta = np.matrix([[0], [0], [0]])
data = loadData("data/ex1data2.txt")
X = createX(data)
y = vectorize(data[2])
print("Original Cost:", computeCost(theta, X, y))
scaled_new_theta = scaledGradientDescent(theta, X, y, alpha, 100000)
perfect_theta = normalEquation(X, y)
# Interesting result to note here
# When gradient descent has 10000 iterations, the z value swings wildly
# in the wrong direction, but with 100000 iterations it seems to pull itself
# back toward the optimal value
print("Gradient Descent: ", scaled_new_theta)
print("Normal Equation ", perfect_theta)
print("New Cost:", computeCost(scaled_new_theta, X, y))
|
655e89ab96f3338a7e3a94f09f06012008c4e232 | aditya2799/MovieDB | /test.py | 512 | 3.609375 | 4 | import sqlite3
conn = sqlite3.connect('temp.db')
c = conn.cursor()
c.execute("""Select * from MOVIE""")
res = c.fetchall()
movie = res[0]
aid = res[0][5]
actorname = ""
c.execute(""" SELECT FIRST_NAME,LAST_NAME FROM ACTOR WHERE AID=(?);""", (aid,))
print(c.fetchall()[0][0])
mid=res[0][0]
c.execute(""" SELECT GENRE FROM GENRE WHERE MID=(?);""", (mid,))
temp = c.fetchall()
genrefull = temp[0][0]
for i in range(1, len(temp)):
genrefull+=", "
genrefull+=temp[i][0]
print(genrefull)
|
fd2236eaf9f68b84c79bc5ea679231c8d1678210 | charuvashist/python-assignments | /assigment10.py | 2,992 | 4.34375 | 4 | '''Ques 1. Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is
inheriting Animal and access the base class method.'''
class Animal:
def animal_attribute(self):
print("This is an Animal Class")
class Tiger(Animal):
def display(self):
print("This is the Lion Class")
a= Tiger()
a.animal_attribute()
a.display()
#Mr.Hacker
'''Ques 2. What will be the output of following code.'''
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print a.f(), b.f()
print a.g(), b.g()'''
# Solution
class A:
def f(self):
return self.g()
def g(self):
return 'A'
class B(A):
def g(self):
return 'B'
a = A()
b = B()
print(a.f(), b.f())
print(a.g(), b.g())
#Mr.SINGH
'''Ques 3. Create a class Cop. Initialize its name, age , work experience and designation. Define methods to add,
display and update the following details. Create another class Mission which extends the class Cop. Define method
add_mission _details. Select an object of Cop and access methods of base class to get information for a particular
cop and make it available for mission.'''
class Cop:
def add(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
def display(self):
print("\n\nDetails Will be:")
print("\nName is: ",self.name)
print("\nAge is: ",self.age)
print("\nWork_Experience: ",self.work_experience)
print("\nDestination: ",self.designation)
def update(self,name,age,work_experience,designation):
self.name = name
self.age = age
self.work_experience = work_experience
self.designation = designation
class Mission(Cop):
def add_mission_details(self,mission):
self.mission=mission
print(self.mission)
m=Mission()
m.add_mission_details("Mission detail Assigned to HP :")
m.add("Bikram",18,8,"Hacker\n")
m.display()
m.update("Faizal",21,2,"Hacker")
m.display()
#Hacker
#MR.SINGH@
'''Ques 4. Create a class Shape.Initialize it with length and breadth Create the method Area.
Create class rectangle and square which inherits shape and access the method Area.'''
class Shape:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
self.area = self.length * self.breadth
class Rectangle(Shape):
def area_rectangle(self):
print("Area of Rectangle is :", self.area)
class Square(Shape):
def area_square(self):
print("Area of Square is :", self.area)
length = int(input("Enter the Length:"))
breadth = int(input("Enter the Breadth:"))
a = Rectangle(length,breadth)
b = Square(length,breadth)
if length == breadth:
b.area()
b.area_square()
else:
a.area()
a.area_rectangle() |
b9ab6da7d8da7faa28a764558af191e50ae6c513 | charuvashist/python-assignments | /assigment5.py | 861 | 3.71875 | 4 | if(year%400==0)or(year%4==0)and(year%100!=0):
print("year is leap")
else
print("year is not leap yaer")
l=int(input("enter any length"))
b=int(input("enter any breadth"))
if(l==t):
print("dimension are of square")
else:
print("dimension are of rectangle")
x=int(input("enter your age"))
y=int(input("enter your age"))
z=int(input("enter your age"))
if(x>y):
print("x is older")
else:
print("z is older")
else:
if(y>x):
print("y is older")
else:
print("z is older")
a=int(input("enter the points:"))
f=1
if a<200:
if 1<a<50:
f=0
print("No Prize")
elif 50<a<150:
prize="Wooden Box"
elif150<a<180:
prize="Book"
elif180<a<200:
prize="Chocolate"
if f!=0:
print("Congratulations you won a {}".format(prize))
n=int(input("enter the cost:"))
p=n*100
if p>1000:
disc=P*.1
r=p-disc
print('total.cost= ',r) |
034ad7eaf850bb1d97eb32a1d0306501e5951a82 | vatanabe/lesson1 | /scores.py | 824 | 3.71875 | 4 | scores_line = [{'school_class': '4a', 'scores': [2,4,2,4]}, {'school_class': '5b', 'scores': [3,5,3,5,3, 5]}, {'school_class': '6c', 'scores': [1,3,1,3,1,3,1,3]}]
#line1 = [2,4,2,4]
def average(list):
numbers_score = len(list)
clas_evaluation = 0
for scores in range(numbers_score):
clas_evaluation = clas_evaluation + list[scores]
clas_evaluation_average = (clas_evaluation / numbers_score)
return str(clas_evaluation_average)
#print(average(line1))
numbers=len(scores_line)
school_evaluation = 0
for clas in range (numbers):
clas_score_dictionary=(scores_line[clas])
clas_score = clas_score_dictionary['scores']
name_clas = clas_score_dictionary['school_class']
print(school_evaluation + int(average(clas_score))
# print('средняя оценка в классе ' + name_clas + ': ' + average(clas_score)) |
8bf6f2146b253774179f0dee4f448929b8d7a50a | Madrant/python_snippets | /static_var/class.py | 396 | 3.515625 | 4 | #!/usr/bin/python3
class Test():
def func(self):
if not hasattr(self, "counter"):
self.counter = 0
if hasattr(self, "counter"):
print("Counter: %u" % (self.counter))
self.counter += 1
if __name__ == "__main__":
test1 = Test()
test2 = Test()
test1.func()
test1.func()
test1.func()
test2.func()
test2.func()
|
001b5cc2e19857211728ce19e6353116860fd60e | averittk4249/cti110 | /m3hw1AgeClassifier_Averitte.py | 325 | 4 | 4 | # M3H1 Age Classifier
# 11/19/17
# Ken Averitte
# Age Classifier Python
userAge = int( input( "Please enter your age: " ) )
if userAge <= 1:
print( "You are an infant" )
elif userAge < 13:
print( "You are a child" )
elif userAge < 20:
print( "You are a teenager" )
elif userAge >= 20:
print( "You are an adult" )
|
41369f8fe9a88217707165a1bfd3b102202e1414 | IKHINtech/kumpulan_koding_python | /aplikasi sederhana hitung mahasiswa.py | 438 | 3.921875 | 4 | matakuliah = input ("Masukkan nama Matakuliah=")
nama = input ("Masukkan Nama Anda=")
nim = input ("Masukakn NIM anda=")
jawaban = "ya"
hitung = 0
while(jawaban == "ya"):
hitung += 1
jawaban = input ("ulangi lagi tidak?")
if jawaban =="ya":
matakuliah = input ("Masukkan nama Matakuliah=")
nama = input ("Masukkan Nama Anda=")
nim = input ("Masukakn NIM anda=")
continue
print ("total mahasiswa : " + str(hitung))
|
b772bfe164a2f6c2cbc16db1e164ce6fe6b8359e | IKHINtech/kumpulan_koding_python | /kelipatan 3.py | 291 | 3.828125 | 4 | n = int(input('masukkan angka= '))
i = 1
a = 0
for i in range(1, n+1):
if i%3 == 0:
print(i,end=' ')
print('merupakan bilangan kelipatan 3')
for i in range(1, n+1):
if i%3 == 0:
a = a + 1
print ('jumlah angka kelipatan 3 ada = ',a)
|
84a8a72ba5d37194e26fd69680fa7eb342687221 | simont1/softdev | /03_occupation/azrael_tungJ-tsuiS.py | 1,769 | 3.828125 | 4 | # azrael - Jason Tung and Simon Tsui
# SoftDev1 pd8
# K06 -- StI/O: Divine your Destiny!
# 2018-09-13
import csv
import random
def convert(filename):
'''converts a two column csv file with table headers and footers into a key value pair dictionary'''
#open file and parse it into a generator using csv reader
#convert the generator into a list exluding the job and percentage table headers and footers
#read values two at a time as tuples and use those to create a key value pair
f = {k:float(v) for k,v in list(csv.reader(open(filename)))[1:-1]}
return f
def pickRandom(f):
'''takes a dictionary of key value pairs and returns a random key using the values as the percent chance of selecting the corresponding key'''
#pick a number, any number (as long as it's an element of [0,99.8))
rand = random.uniform(0, 99.8)
#go through key value pairs in f
for k,v in f.items():
rand -= v
#when the cumulative total is greater than the random value, return that key
if rand <= 0:
return k
print("uh oh... something has gone awry!")
def main():
f = convert("occupations.csv")
print("appropriate dictionary: ", f)
# print(reduce(lambda x,y: x+y, ([v for k,v in f.items()])))
print("weighted random pick: ", pickRandom(f))
print("--testing--")
test()
def test():
f = convert("occupations.csv")
g = {k:0 for k in f}
for x in range(10000):
g[pickRandom(f)]+=1
h = {k: v/100. for k,v in g.items()}
print("generated dictionary from my weighted avg code: ", h)
bool = True
for k in h:
if (f[k] - h[k])/f[k] >= .2:
bool = False
print("meets 20% margin for error" if bool else "does not meet 20% margin for error")
main() |
a336d3cc2a6067b7716b502025456667631106d5 | joemmooney/search-text-for-words | /setup.py | 1,437 | 4.5625 | 5 | # This file is the main file for running this program.
import argparse
from fileReader import read_file
# The main function that is run when starting the program.
# It sets up argument parsing for the file name to read, the number of most common words to print,
# whether to return a json file, and the name for the json file that is being returned.
# Then it sends these arguments to the function that reads and processes the file.
def main():
parser = argparse.ArgumentParser(description="Arguments being passed to the word count program")
parser.add_argument("file_name", help="Name of the .txt file to count words in")
parser.add_argument("--number_of_words_to_print", type=int, default=10, help="The number of words to print " +
"when showing the top n most common words (defaults to 10)")
parser.add_argument("--return_json", action="store_true", help="If this flag is present, " +
"a json file with word counts will be returned")
parser.add_argument("--json_name", type=str, default="word_counts", help="Part of the name of the json file " +
"that the word counts will be saved to (naming convention is \"{file_name}_{json_name}.json\") " +
"(defaults to word_counts)")
args = parser.parse_args()
read_file(args.file_name, args.number_of_words_to_print, args.return_json, args.json_name)
if __name__ == "__main__":
main() |
f41b73b93bac460fc2b885eb62208f5e144a1352 | jason121301/Battleship-AI- | /Project/game_tree.py | 13,435 | 3.609375 | 4 | """The file that keeps track of the Game Trees that could be used.
COPYRIGHT 2021: JASON SASTRA AND MARTON KOVACS UNIVERSITY OF TORONTO."""
from __future__ import annotations
from typing import Optional
import game_code
import random
import copy
class WinningGameTree:
"""A gametree for battleship moves, intended to teach an AI an efficient way to play battleship
ideally, being able to learn as much as at least intermediate bot or even more
Instance Attributes
- move: The current battleship move, based on tile shot
- win_probability: the chance to win when making this move
"""
move: str
win_probability: float
_subtrees: list[WinningGameTree]
def __init__(self, move: str = 'first_move', win_probability: float = 0.0):
self.move = move
self.win_probability = win_probability
self._subtrees = []
def get_subtrees(self) -> list:
"""Get the subtrees of the Game Tree"""
return self._subtrees
def find_subtree_by_move(self, move: str) -> Optional[WinningGameTree]:
"""Return the subtree corresponding to the given move.
Return None if no subtree corresponds to that move.
"""
for subtree in self._subtrees:
if subtree.move == move:
return subtree
return None
def add_subtree(self, subtree: WinningGameTree) -> None:
"""Add a subtree to this game tree."""
self._subtrees.append(subtree)
self._update_win_probability()
def insert_move_sequence(self, moves: list[str], win_probability: Optional[float]) -> None:
"""Inserts a sequence of moving that leads to either winning or losing in the Battleship
Game"""
self.insert_move_helper(moves, 0, win_probability)
self._update_win_probability()
return None
def insert_move_helper(self, moves: list[str], index: int,
win_probability: Optional[float]) -> None:
"""Helper function for insert_move_sequence"""
if index == len(moves):
return None
if self.find_subtree_by_move(moves[index]) is not None:
return self.find_subtree_by_move(moves[index]). \
insert_move_helper(moves, index + 1, win_probability)
else:
new_subtree = WinningGameTree(moves[index], win_probability)
self.add_subtree(new_subtree)
return new_subtree.insert_move_helper(moves, index + 1, win_probability)
def _update_win_probability(self) -> None:
"""Update the win probability of this game tree. Updates it into the average
of all the subtrees below it"""
if self._subtrees == []:
return None
else:
win_probability_so_far = []
for subtree in self._subtrees:
subtree._update_win_probability()
win_probability_so_far.append(subtree.win_probability)
self.win_probability = sum(win_probability_so_far) / len(win_probability_so_far)
return None
class WinningGameTreePlayer(game_code.Player):
"""A player that chooses the best play from the game tree only. It chooses the play with
the highest probability of winning"""
game_tree: Optional[WinningGameTree]
def __init__(self, game_tree: WinningGameTree) -> None:
self.game_tree = game_tree
def make_move(self, game: game_code.BattleshipGame, previous_move: str) -> str:
"""Make a move that chooses the move with the highest probability"""
valid_moves = game.get_valid_moves()
if self.game_tree is None:
return random.choice(valid_moves)
elif self.game_tree.get_subtrees() == []:
self.game_tree = None
return random.choice(valid_moves)
elif self.game_tree.find_subtree_by_move(previous_move) is None:
self.game_tree = None
return random.choice(valid_moves)
else:
self.game_tree = self.game_tree.find_subtree_by_move(previous_move)
move = self.game_tree.get_subtrees()[0].move
highest = -1.0
for subtree in self.game_tree.get_subtrees():
if subtree.win_probability > highest:
highest = subtree.win_probability
move = subtree.move
return move
class TileGameTree:
"""A game tree made to figure out the probability of a tile having a ship based on its
previous moves instead of just the winning chance. Something specific like this
will more likely learn effectively. In this Game Tree, whenever a shot that lands on a ship
hits, it will then go to the subtree in order to find tiles near that which has the highest
chance to also have a ship. The first _subtrees of the main root will contain all the tile
along with its probabilities. Basically, the logic is that it will only go down the tree if it
hits a ship. So that the GameTree is used to decide what the AI should do after hitting the ship
while the original subtrees are used to see which tiles to specifically hit first
to have the highest odds of hitting a ship.
The goal of this TileGameTree
- Teach the AI that middle tiles are most likely to have ships
- Teach the AI that whenever a ship is hit, it needs to explore its surroundings
to find other parts of the ship
"""
move: str
ship_probability: list[int, int]
_subtrees: list[Optional[TileGameTree]]
def __init__(self, move: str = 'first_move', ship_probability=None, subtrees=None):
if subtrees is None:
subtrees = []
if ship_probability is None:
ship_probability = [1, 1]
self.move = move
self.ship_probability = ship_probability
if subtrees is None:
self._subtrees = []
else:
self._subtrees = subtrees
def add_subtree(self, subtree: TileGameTree) -> None:
"""Add a subtree to this TileGameTree."""
self._subtrees.append(subtree)
def get_subtrees(self) -> list:
"""Get the subtrees of the TileGameTree"""
return self._subtrees
def find_subtree_by_move(self, move: str) -> Optional[TileGameTree]:
"""Return the subtree corresponding to the given move.
Return None if no subtree corresponds to that move.
"""
for subtree in self._subtrees:
if subtree.move == move:
return subtree
return None
def ship_locator_fill(self, ship_locator: game_code.ShipLocatingPlayer) -> None:
"""Fills the Tile Game Tree with the probabilities obtained through the Ship Locator
Player"""
for position in ship_locator.tile_probability:
new_subtree = TileGameTree(position, [ship_locator.tile_probability[position][0],
ship_locator.tile_probability[position][1]])
self.add_subtree(new_subtree)
return None
def update_tile_probability(self, previous_move: list[str],
depth: int, final_hit: bool) -> None:
"""Update the tile probability of the tree, along with adding new subtrees
if needed. Only recurse through a subtree and update the subtrees of the original 64
if a hit is confirmed, otherwise, just update the tile probability of the initial 64
moves"""
if depth == 0:
if self.find_subtree_by_move(previous_move[len(previous_move) - 1]) is None:
if final_hit is True:
subtree = TileGameTree(previous_move[len(previous_move) - 1], [2, 2])
self.add_subtree(subtree)
return None
else:
subtree = TileGameTree(previous_move[len(previous_move) - 1], [1, 2])
self.add_subtree(subtree)
return None
else:
updated_subtree = self.find_subtree_by_move(previous_move[len(previous_move) - 1])
if final_hit is True:
updated_subtree.ship_probability[0] += 1
updated_subtree.ship_probability[1] += 1
return None
else:
updated_subtree.ship_probability[1] += 1
return None
else:
if self.find_subtree_by_move(previous_move[len(previous_move) - 1 - depth]) is None:
subtree = TileGameTree(previous_move[len(previous_move) - 1 - depth], [2, 2])
self.add_subtree(subtree)
subtree.update_tile_probability(previous_move, depth - 1, final_hit)
return None
else:
subtree = self.find_subtree_by_move(previous_move[len(previous_move) - 1 - depth])
subtree.ship_probability[0] += 1
subtree.ship_probability[1] += 1
subtree.update_tile_probability(previous_move, depth - 1, final_hit)
return None
def print_string(self) -> str:
"""Function used to print out the string representation of this Game Tree"""
i = 0
print_so_far = 'game_tree.TileGameTree(' + self.move + ',' + str(
self.ship_probability) + ', ['
if self._subtrees != []:
for subtrees in self._subtrees:
print_so_far += subtrees.print_string()
i += 1
if i != len(self._subtrees):
print_so_far += ','
print_so_far += '])'
return print_so_far
class TileTreePlayer(game_code.Player):
"""A player that chooses the best play from the game tree only. It chooses the play with
the highest probability of finding a ship. The depth variable is the amount of time it has
succesfully hit a ship, in which case the length of it represents how far into the subtree
it should recurse to find the next succesful move."""
game_tree: Optional[TileGameTree]
depth: [str]
ship_shot: int
def __init__(self, game_tree: TileGameTree = TileGameTree()) -> None:
self.game_tree = game_tree
self.depth = []
self.ship_shot = 0
def update_depth(self, move: Optional[str], board: game_code.BattleshipGame) -> None:
"""Update the depth of this particular move combination. If the shot misses, then
reset the depth counter into an empty list, otherwise, add the move into the
depth list in order to recurse through the game tree properly. Additionally, update
the game tree accordingly whenever it misses such that the previous move sequence
is added into the game tree"""
if self.ship_shot < board.ship_shot:
self.ship_shot += 1
self.depth.append(move)
return None
else:
if move is not None:
if self.depth == []:
self.game_tree.update_tile_probability([move], 0, False)
else:
self.depth.append(move)
self.game_tree.update_tile_probability(self.depth, len(self.depth) - 1, False)
self.depth = []
return None
def make_move(self, board: game_code.BattleshipGame, previous_move: Optional[str]):
"""Make move that is ideal considering the board state and the game tree
along with the current depth"""
self.update_depth(previous_move, board)
possible_moves = board.get_valid_moves()
if self.depth == []:
highest_probability = 0
best_move = random.choice(possible_moves)
for subtree in self.game_tree.get_subtrees():
if subtree.move in possible_moves and subtree.ship_probability[1] > 3:
if subtree.ship_probability[0] / \
subtree.ship_probability[1] > highest_probability:
highest_probability = \
subtree.ship_probability[0] / subtree.ship_probability[1]
best_move = subtree.move
return best_move
else:
new_subtree = copy.deepcopy(self.game_tree)
for move in self.depth:
if new_subtree.find_subtree_by_move(move) is None:
return random.choice(possible_moves)
else:
new_subtree = new_subtree.find_subtree_by_move(move)
highest_probability = 0
best_move = random.choice(possible_moves)
for subtree in new_subtree.get_subtrees():
if subtree.move in possible_moves and subtree.ship_probability[1] > 3:
if subtree.ship_probability[0] / \
subtree.ship_probability[1] > highest_probability:
highest_probability = \
subtree.ship_probability[0] / subtree.ship_probability[1]
best_move = subtree.move
return best_move
|
0a5a2a20d7b2a8a4f71de1a098508a6a24610ec6 | GaoLiaoLiao/Crawler | /Python3WebSpiderTest/07-csv文件.py | 1,412 | 3.75 | 4 | import csv
import pandas as pd #利用pandas读取csv数据文件
#csv,其文件以纯文本的形式存储表格数据,相当于一个结构化表的纯文本形式
#写入
with open('data.csv','w') as csvfile: #打开csv文件,获得文件句柄
writer=csv.writer(csvfile) #初始化传入对象,传入该句柄
writer=csv.writer(csvfile,delimiter=' ') #可以修改数据之间的分隔符,默认是逗号
writer.writerow(['id','name','age']) #以writerow()传入每行的数据
writer.writerow(['1','job','20'])
writer.writerow(['2','jack','22'])
#写入字典格式的数据
with open('data1.csv','w',encoding='utf-8') as csvfile:
fieldnames=['id','name','age'] #先定义三个字段,用filenames表示
writer=csv.DictWriter(csvfile,fieldnames=fieldnames) #将字段传入给Dictwriter来初始化一个字典写入对象
writer.writeheader() #写入头信息
writer.writerow({'id':'100','name':'job','age':22}) #传入相应字段
writer.writerow({'id':'101','name':'tom','age':32})
writer.writerow({'id':'102','name':'mary','age':25})
#读取
with open('data1.csv','r',encoding='utf-8') as csvfile:
reader=csv.reader(csvfile)
for row in reader:
print(row)
df=pd.read_csv('data1.csv')
print(df)
|
68704578ee04cab63e82224bb1ef7c78f0ccf3c1 | JWhacheng/hangman | /main.py | 1,594 | 3.859375 | 4 | import os
import random
from sys import platform
from functools import reduce
def get_words_from_file():
words = []
with open("./data.txt", "r", encoding="utf-8") as f:
for line in f:
words.append(line.strip("\n"))
return words
def replace_accent_mark_letters(word):
replacements = (("á", "a"), ("é", "e"), ("í", "i"), ("ó", "o"), ("ú", "u"))
for replacement in replacements:
word = str(word).replace(replacement[0], replacement[1])
return word
def get_random_word():
words = get_words_from_file()
return replace_accent_mark_letters(random.choice(words))
def run():
won = False
opportunities = 11
word_to_guess = str(get_random_word()).upper()
guessed_word = ["_" for i in range(0, len(word_to_guess))]
while reduce(lambda a, b: a + b, guessed_word) != word_to_guess and opportunities > 0:
print("¡Adivina la palabra!")
for letter_in_guessed_word in guessed_word:
print(letter_in_guessed_word, end=" ")
letter = input("\n\nIngresa una letra: ").upper()
if letter in word_to_guess:
for i in range(0, len(word_to_guess)):
if letter == word_to_guess[i]:
guessed_word[i] = letter
else:
opportunities -= 1
if reduce(lambda a, b: a + b, guessed_word) == word_to_guess:
won = True
if platform == "linux" or platform == "linux2":
os.system("clear")
else:
os.system("cls")
if won:
print("¡Ganaste! La palabra era " + word_to_guess)
else:
print("Se te acabaron las oportunidades. La palabra era " + word_to_guess)
if __name__ == "__main__":
run()
|
dd980648aa9a0b04a6cdd9b0ec62f7d1e2c69f42 | sniemi/SamPy | /astronomy/conversions.py | 13,242 | 3.640625 | 4 | """
Functions to do Astronomy related unit conversions.
:requires: astLib
:requires: NumPy
:requires: cosmocalc (http://cxc.harvard.edu/contrib/cosmocalc/)
:version: 0.4
:author: Sami-Matias Niemi
:contact: sammy@sammyniemi.com
"""
import math
import numpy as np
from cosmocalc import cosmocalc
import astLib.astCoords as Coords
C = 2.99792458e18 # speed of light in Angstrom/sec
H = 6.62620E-27 # Planck's constant in ergs * sec
HC = H * C
ABZERO = -48.60 # magnitude zero points
STZERO = -21.10
DEGTOARCSEC = 0.000277777778 # degree to arcsecond
def squareDegFromArcSecSquared(arcsecsq):
"""
Converts arc second squared to square degrees.
:param arcsecsq: arc seconds squared
:type arcsecsq: float or ndarray
:return: square degrees
:rtype: float or ndarray
"""
return arcsecsq * 7.71604938e-8
def angularSeparationToPhysical(separation, diameterDistance):
"""
Converts angular separation on the sky [degrees] to physical [kpc].
:param separation: separation on the sky [degrees]
:type separation: float or ndarray
:param diameterDistance: diameter distance [kpc / arcsecond]
:type diameterDistance: float or ndarray
:return: physical distance [kpc]
:rtype: float or ndarray
"""
pd = separation * diameterDistance / DEGTOARCSEC
return pd
def physicalSeparation(inputdata, redshift, H0=71.0, OmegaM=0.28):
"""
Calculates the physical distances between objects of given RAs and DECs at a given redshift.
:param inputdata: coordinates (RA and DEC) of the objects. The input data should
consist of four keys value pairs::
RA1: RA of the object from which to calculate the distance (float)
DEC1: DEC of the object from which to calculate the distance (float)
RA2: RAs of the objects (float or numpy array)
DEC2: DECs of the objects (float or numpy array)
:type inputdata: dict
:param redshift: cosmological redshift of the object
:type redshift: float
:param H0: Hubble value [71/km/s/Mpc]
:type H0: float
:param OmegaM: Matter density
:type OmegaM: float [0.28]
:return: physical distance [distance], scale at a given redshift 1 arcsec = kpc [scale],
separation on the sky in arcseconds [separation], cosmological parameters [cosmology]
:rtype: dict
"""
sep = Coords.calcAngSepDeg(inputdata['RA1'], inputdata['DEC1'],
inputdata['RA2'], inputdata['DEC2'])
d = cosmocalc(redshift, H0, OmegaM)
dd = d['PS_kpc']
pd = angularSeparationToPhysical(sep, dd)
return dict(distance=pd, scale=dd, separation=sep/DEGTOARCSEC, redshift=redshift,
cosmology=d)
def FnutoFlambda(Fnu, wavelength):
"""
Converts F_nu to F_lambda.
:param Fnu: Fnu [ers/s/cm**2/Hz]
:type Fnu: float or ndarray
:param wavelength: wavelength [AA]
:type wavelength: float or ndarray
:return: Flambda [ergs/s/cm**2/AA]
"""
return Fnu / wavelength / wavelength * C
def ergsperSecondtoLsun(ergss):
"""
Converts ergs per second to solar luminosity in L_sun.
:param ergss: ergs per second
:type ergss: float or ndarray
:return: luminosity in L_sun
:rtype: float or ndarray
"""
return ergss / 3.839e33
def wattsperHertztoErgsperArcsecond(data):
"""
Converts Watts per Hertz to ergs per arcsecond.
1 watt per hertz = 48.4813681 ergs per arcsecond.
:param data: data to be converted
:type data: float or ndarray
:return: converted value
:rtype: float or ndarray
"""
return data * 48.4813681
def angstromToHertz(A):
"""
Converts Angstroms to Hertz.
:param A: wavelength in angstroms
:type A: float or ndarray
:return: Hertz
:rtype: float or ndarray, depending on the input
"""
return 2.99792458e18 / A
def nanomaggiesToJansky(nanomaggie):
"""
Converts nanomaggies, used for example in SDSS imaging, to Janskys.
:param nanomaggie: nanomaggie of the object
:type nanomaggie: float or ndarray
:return: Janskys
:rtype: either a float or ndarray
"""
return nanomaggie * 3.631e-6
def janskyToMagnitude(jansky):
"""
Converts Janskys to AB magnitudes.
:note: Can be used with SQLite3 database.
:param jansky: janskys of the object
:type jansky: float or ndarray
:return: either a float or NumPy array
"""
return 8.9 - 2.5 * np.log10(jansky)
def ABMagnitudeToJansky(ABmagnitude):
"""
Converts AB magnitudes to Janskys.
:note: Can be used with SQLite3 database.
:param ABmagnitude: AB-magnitude of the object
:type ABmagnitude: float or ndarray
:return: either a float or NumPy array
"""
return 10 ** ((23.9 - ABmagnitude) / 2.5) / 1e6
def arcminSquaredToSteradians(arcmin2):
"""
Converts :math:`arcmin^{2}` to steradians.
:param arcmin2: :math:`arcmin^{2}`
:type arcmin2: float or ndarray
:return: steradians
"""
return arcmin2 / ((180 / np.pi) ** 2 * 60 * 60)
def arcminSquaredToSolidAnge(arcmin2):
"""
Converts :math:`arcmin^{2}` to solid angle.
Calls arcminSqauredToSteradians to convert :math:`arcmin^{2}`
to steradians and then divides this with :math:`4\\Pi`.
:param arcmin2: :math:`arcmin^{2}`
:type arcmin2: float or ndarray
:return: solid angle
"""
return arcminSquaredToSteradians(arcmin2) / 4. / np.pi
def comovingVolume(arcmin2, zmin, zmax,
H0=70, WM=0.28):
"""
Calculates the comoving volume between two redshifts when
the sky survey has covered :math:`arcmin^{2}` region.
:param arcmin2: area on the sky in :math:`arcmin^{2}`
:param zmin: redshift of the front part of the volume
:param zmax: redshift of the back part of the volume
:param H0: Value of the Hubble constant
:param WM: Value of the mass density
:return: comoving volume between zmin and zmax of arcmin2
solid angle in Mpc**3
"""
front = cosmocalc(zmin, H0, WM)['VCM_Gpc3']
back = cosmocalc(zmax, H0, WM)['VCM_Gpc3']
volume = (back - front) * 1e9 * arcminSquaredToSolidAnge(arcmin2)
return volume
def Luminosity(abs_mag):
"""
Converts AB magnitudes to luminosities in :math:`L_{sun}`
:param abs_mag: AB magnitude of the object
:type abs_mag: float or ndarray
:return: luminosity
:rtype: float or ndarray
"""
return 10.0 ** ((4.85 - abs_mag) / 2.5)
def get_flat_flambda_dmag(plambda, plambda_ref):
"""
Compute the differential AB-mag for an object flat in f_lambda.
:param plambda: value of the plambda
:param plambda_ref: reference value
:return: magnitude difference
"""
# compute mag_AB for an object at the desired wavelength
mag1 = get_magAB_from_flambda(1.0e-17, plambda)
# compute mag_AB for an object at the reference wavelength
mag2 = get_magAB_from_flambda(1.0e-17, plambda_ref)
# return the mag difference
return mag1 - mag2
def get_magAB_from_flambda(flambda, wlength):
"""
Converts a mag_AB value at a wavelength to f_lambda.
:param flambda: mag_AB value
:type flambda: float
:param wlength: wavelength value [nm]
:type wlength: float
:return: the mag_AB value
:rtype: float
"""
# transform from flambda to fnue
fnu = (wlength * wlength) / 2.99792458e+16 * flambda
# compute mag_AB
mag_AB = -2.5 * math.log10(fnu) - 48.6
# return the mag_AB
return mag_AB
def redshiftFromScale(scale):
"""
Converts a scale factor to redshift.
:param scale: scale factor
:type scale: float or ndarray
:return: redshift
:rtype: float or ndarray
"""
return 1. / scale - 1.
def scaleFromRedshift(redshift):
"""
Converts a redshift to a scale factor.
:param redshift: redshift of the object
:type redshift: float or ndarray
:return: scale factor
:rtype: float or ndarray
"""
return 1. / (redshift + 1.)
def convertSphericalToCartesian(r, theta, phi):
"""
Converts Spherical coordinates to Cartesian ones.
http://mathworld.wolfram.com/SphericalCoordinates.html
:param r: radius
:type r: float or ndarray
:param theta: :math:`\\theta`
:type theta: float or ndarray
:param phi: :math:`\\phi`
:type phi: float or ndarray
:return: x, y, z
:rtype: dictionary
"""
x = r * np.sin(phi) * np.cos(theta)
y = r * np.sin(phi) * np.sin(theta)
z = r * np.cos(phi)
return {'x': x,
'y': y,
'z': z}
def RAandDECfromStandardCoordinates(data):
"""
Converts Standard Coordinates on tangent plane to RA and DEC on the sky.
data dictionary must also contain the CD matrix.
Full equations:
.. math::
\\xi & = cdmatrix(0,0) * (x - crpix(0)) + cdmatrix(0,1) * (y - crpix(1)) \\\\
\\eta & = cdmatrix(1,0) * (x - crpix(0)) + cdmatrix(1,1) * (y - crpix(1))
then
.. math::
ra &= atan2(\\xi, \\cos(dec0) - \\eta * \\sin(dec0)) + ra0 \\\\
dec &= atan2(\\eta * \\cos(dec0) + \\sin(dec0),
\\sqrt{((\\cos(dec0) - \\eta * \\sin(dec0))^{2} + \\xi^{2})})
:param data: should contain standard coordinates X, Y, RA and DEC of the centre point, and the CD matrix.
:type data: dictionary
:return: RA and DEC
:rtype: dictionary
"""
out = {}
xi = (data['CD'][0, 0] * data['X']) + (data['CD'][0, 1] * data['Y'])
eta = (data['CD'][1, 0] * data['X']) + (data['CD'][1, 1] * data['Y'])
xi = np.deg2rad(xi)
eta = np.deg2rad(eta)
ra0 = np.deg2rad(data['RA'])
dec0 = np.deg2rad(data['DEC'])
ra = np.arctan2(xi, np.cos(dec0) - eta * np.sin(dec0)) + ra0
dec = np.arctan2(eta * np.cos(dec0) + np.sin(dec0),
np.sqrt((np.cos(dec0) - eta * np.sin(dec0)) ** 2 + xi ** 2))
ra = np.rad2deg(ra)
ra = np.mod(ra, 360.0)
out['RA'] = ra
out['DEC'] = np.rad2deg(dec)
return out
def angularDiameterDistance(z,
H0=70,
WM=0.28):
"""
The angular diameter distance DA is defined as the ratio of
an object's physical transverse size to its angular size
(in radians). It is used to convert angular separations in
telescope images into proper separations at the source. It
is famous for not increasing indefinitely as z to inf; it turns
over at z about 1 and thereafter more distant objects actually
appear larger in angular size.
:param z: redshift
:type z: float
:param H0: value of the Hubble constant
:type H0: float
:param WM: :math:`\\Omega_{\\mathrm{matter}}`
:type WM: float
:return: angular diameter distance
:rtype: float
"""
return cosmocalc(z, H0, WM)['DA']
def degTodms(ideg):
"""
Converts degrees to degrees:minutes:seconds
:param ideg: objects coordinate in degrees
:type ideg: float
:return: degrees:minutes:seconds
:rtype: string
"""
if (ideg < 0):
s = -1
else:
s = 1
ideg = abs(ideg)
deg = int(ideg) + 0.
m = 60. * (ideg - deg)
minutes = int(m) + 0.
seconds = 60. * (m - minutes)
if s < 0:
dms = "-%02d:%02d:%06.3f" % (deg, minutes, seconds)
else:
dms = "%02d:%02d:%06.3f" % (deg, minutes, seconds)
return dms
def degTohms(ideg):
"""
Converts degrees to hours:minutes:seconds
:param ideg: objects coordinates in degrees
:type ideg: float
:return: hours:minutes:seconds
:rtype: string
"""
ihours = ideg / 15.
hours = int(ihours) + 0.
m = 60. * (ihours - hours)
minutes = int(m) + 0.
seconds = 60. * (m - minutes)
hms = "%02d:%02d:%06.3f" % (hours, minutes, seconds)
return hms
def cot(x):
"""
.. math::
\\frac{1}{\\tan (x)}
:param x: value
:type x: float or ndarray
:return: cotangent
:rtype: float or ndarray
"""
return 1. / np.tan(x)
def arccot(x):
"""
.. math::
arctan \\left ( \\frac{1}{x} \\right )
:param x: value
:type x: float or ndarray
:return: arcuscotangent
:rtype: float or ndarray
"""
return np.arctan(1. / x) |
ed96ec767162ac072948a1ccf04da851ee748729 | sniemi/SamPy | /resolve/kinematics/processVelocities.py | 7,887 | 3.59375 | 4 | """
Class to process emsao output and combine information to generate a velocity field.
Parses the input data and outputs reformatted data to a file.
Combines velocity information with the coordinate information
to generate a velocity field and outputs this information to
a comma separated ascii file.
Will also generate a plot showing the parsed velocities.
This plot is meant for quick visual inspection only. Note
that all three slices are in the same plot so the x axis
values are rather arbitrary.
:requires: NumPy
:requires: SamPy
:requires: matplotlib (for plotting)
:author: Sami-Matias Niemi
:contact: sniemi@unc.edu
:version: 0.6
"""
import csv
import numpy as np
from matplotlib import pyplot as plt
import SamPy.smnIO.write as write
import SamPy.smnIO.read as read
import SamPy.sandbox.odict as o
class emsaoVelocity():
"""
Class to parse emsao velocity information and to combine it with coordinate information.
Can be used to generate a velocity field.
"""
def __init__(self, file='emsao.log'):
"""
Class constructor.
:param file: file name of the emsao log file
:type file: string
"""
self.file = file
def parseInformation(self):
"""
Parses the file given in the class constructor for velocity information.
Assumes that the input is in the emsao log file format.
:return: velocity information
:rtype: dictionary
"""
out = []
#read in data and loop over it
data = open(self.file, 'r').readlines()
for line in data:
if len(line) > 1:
tmp = line.split()
if line.startswith('File:'):
file = tmp[1]
pixel = tmp[2]
if line.startswith('Object:'):
object = tmp[1]
if line.startswith('Combined'):
cvel = tmp[3]
cvelerr = tmp[5]
cz = tmp[8]
if line.startswith('Emission'):
evel = tmp[3]
evelerr = tmp[5]
ez = tmp[8]
else:
out.append([file, pixel, cvel, cvelerr, cz, evel, evelerr, ez, object])
#dumps to a file
write.cPickleDumpDictionary(out, 'velocity.pk')
self.velocityInfo = out
return self.velocityInfo
def getValues(self, data=None):
"""
Massages data to a different format that is easier to deal with and plot.
:param data: input data if None taken from the parseInformation method
:type data: ndarray
:return: reformatted data
:rtype: dictionary
"""
if data == None:
data = self.velocityInfo
file = []
pix = []
cvel = []
cvelerr = []
evel = []
evelerr = []
for line in data:
file.append(line[0])
pix.append(int(line[1]))
cvel.append(float(line[2]))
cvelerr.append(float(line[3]))
evel.append(float(line[5]))
evelerr.append(float(line[6]))
out = o.OrderedDict()
out['file'] = file
out['pixels'] = np.asarray(pix)
out['cvelocities'] = np.asarray(cvel)
out['cerrors'] = np.asarray(cvelerr)
out['evelocities'] = np.asarray(evel)
out['eerrors'] = np.asarray(evelerr)
self.velocityInfo2 = out
return self.velocityInfo2
def combineVelocityCoordinates(self,
vel='velocity.pk',
coord='coordinates.pk'):
"""
Combine velocity and coordinate information.
Takes the data from pickled files.
:param vel: pickled velocity information
:type vel: string
:param coord: pickled coordinate information
:type coord: string
"""
#load in data
coords = read.cPickledData(coord)
vel = read.cPickledData(vel)
#output
out = []
#loop over all time and space...
for file in coords.keys():
for coordline in coords[file]:
for velline in vel:
if velline[0] == file.replace('.fits', '') and int(velline[1]) == coordline[1]:
#this is match but need to test if there's any useful veocity info
if float(velline[2]) > 0.0 or float(velline[5]) > 0.0:
tmp = coordline + [float(velline[2]), float(velline[3]),
float(velline[4]), float(velline[5]),
float(velline[6]), float(velline[7]), file]
out.append(tmp)
info = {'coordinates': coords,
'velocities': vel,
'data': out}
self.velocityField = info
write.cPickleDumpDictionary(self.velocityField, 'velocityField.pk')
def generatePlot(self):
"""
Makes a quick plot of parsed data for visualization.
This plot is only so useful given that the x-axis is in pixels,
thus the centre of the galaxy is not aligned for different slices.
"""
data = self.velocityInfo2
minim = np.min(data['evelocities'][data['evelocities'] > 0]) * 0.99
maxim = np.max(data['evelocities']) * 1.01
fig = plt.figure()
ax = fig.add_subplot(111)
ax.errorbar(data['pixels'], data['cvelocities'], yerr=data['cerrors'],
marker='o', ms=4, ls='None', label='Combined Velocities')
ax.errorbar(data['pixels'], data['evelocities'], yerr=data['eerrors'],
marker='s', ms=4, ls='None', label='Emission Velocities')
ax.set_ylim(minim, maxim)
ax.set_xlabel('Pixels')
ax.set_ylabel('Velocity [km/s]')
plt.legend(shadow=True, fancybox=True, numpoints=1)
plt.savefig('velocity.pdf')
def output(self, outfile='velocityField.csv'):
"""
Outputs data to a pickled file and to a comma separated ascii file.
For ascii file, the method will combine the coordinate and velocity
information. Will set velocities to -99.99 if did not find information.
Note, however, that emsao sets velocities to 0.0 if it was not able
to derive a velocity.
:param outfile: name of the ascii output file
:type outfile: string
"""
fh = open(outfile, 'w')
fh.write('#file x_coord y_crood ra dec combine_vel error cz emission_vel error ez\n')
#combine information
for file in sorted(self.velocityField['coordinates'].keys()):
for line in self.velocityField['coordinates'][file]:
found = False
for x in self.velocityField['data']:
if line[1] == x[1] and x[12] == file:
#found velocity information
found = True
output = x[12] + ', ' + str(int(x[0])) + ', ' + str(x[1]) + ', ' + str(x[4]) + ', ' + str(x[5])
output += ', ' + str(x[6]) + ', ' + str(x[7]) + ', ' + str(x[8]) + ', ' + str(x[9])
output += ', ' + str(x[10]) + ', ' + str(x[11])
fh.write(output + '\n')
break
if not found:
output = file +', 1, ' + str(line[1]) + ', ' + str(line[4]) + ', ' + str(line[5])
output += ', -99.99' * 6
fh.write(output + '\n')
fh.close()
if __name__ == '__main__':
velocity = emsaoVelocity()
velocity.parseInformation()
velocity.getValues()
velocity.combineVelocityCoordinates()
velocity.output()
#make a plot
velocity.generatePlot() |
df3b8e4f79c14872f724d2b24a972f79f16f5e83 | sniemi/SamPy | /sandbox/src1/avg.py | 2,094 | 4.03125 | 4 | #!/usr/bin/python
# avg.py
# Program to calculate the average and standard deviations
# of columns in a rectangle of numbers
print "\n avg.py Written by Enno Middelberg 2002\n"
print " Calculates the average and standard errors of"
print " columns and lines in a rectangle of numbers\n"
import math
import string
import sys
# Function to work out avg, sx and sigmax from a list of numbers
def stat(numbers):
sum=0
if len(numbers)>1:
for i in numbers:
sum=sum+i
avg=sum/len(numbers)
sum=0
for i in numbers:
sum=sum+(i-avg)**2
sx=math.sqrt(sum/(len(numbers)-1))
sigmax=math.sqrt(sum/len(numbers))
else:
avg=numbers[0]
sx=1
sigmax=0
return avg, sx, sigmax
# Get numbers from stdin
list=[]
for line in sys.stdin.readlines():
list.append(string.split(line))
ncols=len(list[0])
nlines=len(list)
print "\nNumber of columns: %i, number of lines: %i" % (ncols, nlines)
# Sort columns into 1D-lists and pass them to stat()
colstats=[]
for i in range(ncols):
colnumbers=[]
for j in range(nlines):
colnumbers.append(float(list[j][i]))
colstats.append(stat(colnumbers))
print "\n",
# Sort lines into 1D-lists and pass them to stat()
linestats=[]
for i in range(nlines):
linenumbers=[]
for j in range(ncols):
linenumbers.append(float(list[i][j]))
linestats.append(stat(linenumbers))
# Print results
print " ",
for i in range(ncols):
print "%i " %i,
print
for i in range(nlines):
print "%i - " %i,
for j in range(ncols):
print "% 5.4e" %(float(list[i][j])),
print
print "\nColumn statistics:"
print "\nAvg: ",
for i in colstats:
print "% 5.4e" %i[0],
print "\nsx: ",
for i in colstats:
print "% 5.4e" %i[1],
print "\nsigmax: ",
for i in colstats:
print "% 5.4e" %i[2],
print "\n\nLine statistics: Avg sx sigmax \n"
for i in range(nlines):
print " Line %i - % 5.4e % 5.4e % 5.4e" % (i,linestats[i][0], linestats[i][1], linestats[i][2])
print "\n\nsx = sqrt( 1/(n-1) * sum ( x_i - x )^2 )"
print "sigmax = sqrt( 1/n * sum ( x_i - x )^2 )\n"
|
2f089d961ae1edad6803c40977a7ea4fe609b184 | sniemi/SamPy | /astronomy/randomizers.py | 1,042 | 3.9375 | 4 | """
This module can be used to randomize for example galaxy positions.
:depends: NumPy
:author: Sami-Matias Niemi
:date: 21 May, 2011
:version: 0.1
"""
import numpy as np
__author__ = 'Sami-Matias Niemi'
def randomUnitSphere(points=1):
"""
This function returns random positions on a unit sphere. The number of random
points returned can be controlled with the optional points keyword argument.
:param points: the number of random points drawn
:type points: int
:return: random theta and phi angles
:rtype: dictionary
"""
#get random values u and v
u = np.random.rand(points)
v = np.random.rand(points)
#Convert to spherical coordinates
#Note that one cannot randomize theta and phi
#directly because the values would
#be packed on the poles due to the fact that
#the area element has sin(phi)!
theta = 2. * np.pi * u
phi = np.arccos(2. * v - 1)
#pack all the results to a dictionary
out = {'theta': theta,
'phi': phi,
'points': points}
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.