blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4da9a78205d4aab5a7b5cb88611d636e92fcca91 | nishizumi-lab/sample | /python/basic/re/finditer.py | 522 | 3.75 | 4 | # -*- coding: utf-8 -*-
import re
data = 'abcdefghijklmnabcdefghijklmn'
pattern = re.compile(r'd.*?g') # パターン式の定義(dで始まりgで終わる最短の文字列)
match_datas = pattern.finditer(data)# パターン式との一致判定
for match in match_datas:
print( match.group() ) # 一致したデータを表示
print( match.start() ) # 一致した開始位置を表示
print( match.end() ) # 一致した終了位置を表示
print( match.span() ) # 一致した位置を表示
|
c3fcceea355dbdbf410a608f38ee84c343ed0239 | nishizumi-lab/sample | /python/opencv/opencv-old/zoom.py | 640 | 3.53125 | 4 | # -*- coding:utf-8 -*-
import cv2
import numpy as np
def main():
# 画像の取得
im = cv2.imread("fubuki.png")
# 画像の拡大・縮小
h = im.shape[0] # 画像の高さ
w = im.shape[1] # 画像の幅
resize1 = cv2.resize(im,(w*2,h*2)) # 画像を2倍に拡大
resize2 = cv2.resize(im,(w/2,h/2)) # 画像を1/2に縮小
# 結果表示
cv2.imshow("Resize1",resize1)
cv2.imshow("Resize2",resize2)
cv2.waitKey(0) # キー入力待機
cv2.destroyAllWindows() # ウィンドウ破棄
if __name__ == "__main__":
main()
|
f32b7b9b2923ef4b2f4bf2fa7acf96c6f79fb4b6 | nishizumi-lab/sample | /python/basic/List/itertools.py | 1,869 | 3.9375 | 4 | import itertools
# 3P2の順列:1, 2, 3の玉が入った袋から2つの玉を取り出す
# 第2引数を省略すると3P3 (= 3!)になる
num_list = [1, 2, 3]
new_list = []
for num in itertools.permutations(num_list, 2):
new_list.append(num)
print(new_list)
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# 1, 2, 3と書かれた玉が入った袋から、2つの玉を区別なく同時に取り出す (3C2の組み合わせ)
num_list = [1, 2, 3]
new_list = []
for num in itertools.combinations(num_list, 2):
new_list.append(num)
print(new_list)
# [(1, 2), (1, 3), (2, 3)]
# 重複順列:1, 2, 3と書かれた玉が入った袋から、2つの玉を取り出す(ただし取り出した玉はまた袋に戻す)
num_list = [1, 2, 3]
new_list = []
for num in itertools.product(num_list, repeat=2):
new_list.append(num)
print(new_list)
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
# 重複組合せ:1, 2, 3と書かれた玉が2セット入った袋から、2つの玉を区別なく同時に取り出す
num_list = [1, 2, 3]
new_list = []
for num in itertools.combinations_with_replacement(num_list, 2):
new_list.append(num)
print(new_list)
# [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
# 2つの集合の直積
sign_list = ['a', 'b', 'c']
num_list = [1, 2, 3]
new_list = []
for pairs in itertools.product(sign_list, num_list):
new_list.append(pairs)
print(new_list)
# [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
num_list = [1, 2, 3]
new_list = []
for i in range(1, len(num_list)+1):
els = [list(x) for x in itertools.combinations(num_list, i)]
new_list.extend(els)
print(new_list)
# [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
new_sum_list = [sum(x) for x in new_list]
print(new_sum_list)
# [1, 2, 3, 3, 4, 5, 6] |
58d34b965e55dc57480d62718a6de206ae68bb37 | nishizumi-lab/sample | /python/basic/Class/constructor.py | 382 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# クラスの定義
class MyClass():
# コンストラクタ(初期化メソッド)
def __init__(self, text):
self.text = text
def main():
# コンストラクタでインストラクタ変数を初期化
my = MyClass("Nyan Pass!")
# インストラクタ変数を表示
print(my.text)
if __name__ == "__main__":
main()
|
63ac3c0052490de621f8596e8d52f51e3aea3312 | nishizumi-lab/sample | /python/scraping/02_bs4/sample03.py | 1,130 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
def table_to_csv(file_path, url, selecter):
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
# セレクタ(タグ:table、クラス:test)
table = soup.findAll("table", selecter)[0]
trs = table.findAll("tr")
# ファイルオープン
csv_file = open(file_path, 'wt', newline = '', encoding = 'utf-8')
csv_write = csv.writer(csv_file)
for tr in trs:
csv_data = []
# 1行ごとにtd, tr要素のデータを取得してCSVに書き込み
for cell in tr.findAll(['td', 'th']):
csv_data.append(cell.get_text())
csv_write.writerow(csv_data)
# ファイルクローズド
csv_file.close()
# URLの指定
url = 'https://raw.githubusercontent.com/nishizumi-lab/sample/master/python/scraping/00_sample_data/sample02/index.html'
# セレクタ
selecter = {"class":"test"}
# 指定したURL・セレクタの表のデータをCSVに保存
table_to_csv("/Users/github/sample/python/scraping/02_bs4/sample03.csv", url, selecter)
|
b2eb47334a63860d472823f9a3bc5814ee3780e7 | mariagarciau/EjAmpliacionPython | /ejEscalera.py | 795 | 4.375 | 4 | """Esta es una escalera de tamaño n= 4:
#
##
###
####
Su base y altura son iguales a n. Se dibuja mediante #símbolos y espacios. La última línea no está precedida por espacios.
Escribe un programa que imprima una escalera de tamaño n .
Función descriptiva
Complete la función de staircase. staircase tiene los siguientes parámetros:
int n : un número entero
Impresión
Imprima una escalera como se describe arriba.
Formato de entrada
Un solo entero, n , que denota el tamaño de la escalera.
Formato de salida
Imprime una escalera de tamaño utilizando #símbolos y espacios.
Salida de muestra
#
##
###
####
#####
######
"""
n = int(input("Introduce un número: "))
for altura in range(n):
for ancho in range(altura+1):
print(end="#")
print()
|
3522927ed8c6e794396706ec5f5c8779c73fa383 | cloudersjun/python_pro | /hello_world.py | 367 | 3.75 | 4 | # a = [5, 3, 45, 3, 4]
#
#
# def quicksort(a):
# if len(a) <= 1:
# return a
# l = [x for x in a[1:] if x <= a[0]]
# r = [x for x in a[1:] if x > a[0]]
# return quicksort(l) + [a[0]] + quicksort(r)
#
#
# print str(a)
# a = quicksort(a)
# print str(a)
import datetime
print datetime.datetime.strptime("2017-07-21","%Y-%m-%d").strftime("%Y%m%d") |
983a91b383f63fedd4ba16a2cb8f2eaceaffc57a | rlugojr/FSND_P01_Movie_Trailers | /media.py | 926 | 4.3125 | 4 |
'''The media.Movie Class provides a data structure to store
movie related information'''
class Movie():
'''The media.Movie constructor is used to instantiate a movie object.
Inputs (required):
movie_title --> Title of the movie.
movie_year --> The year the movie was released.
movie_storyline --> Tagline or Storyline of the movie.
poster_image --> The url to the image file for the movie poster.
trailer_youtube --> The url to the YouTube video for
the movie trailer.
Outputs: Movie Object'''
def __init__(self, movie_title, movie_year, movie_storyline,
poster_image, trailer_youtube):
self.title = movie_title
self.year = movie_year
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
|
69bc1a768917c8545ec939fc1f931eaf488d05fa | EmillyLopes/Projetos_python | /area.py | 507 | 3.65625 | 4 | A,B,C = input().split(" ")
A = float(A)
B = float(B)
C = float(C)
Atri = A * C / 2
Acir = 3.14159 * C ** 2
Atrap = (A + B) * C / 2
Aquad = B ** 2
Aret = A * B
print("TRIANGULO: {:.3f}\nCIRCULO: {:.3f}\nTRAPEZIO: {:.3f}\nQUADRADO: {:.3f}\nRETANGULO: {:.3f}".format(Atri, Acir,
Atrap, Aquad,
Aret))
|
52b63c5cced274b037fd2aaaf67f28e71f8d90df | EmillyLopes/Projetos_python | /funcao.py | 416 | 3.734375 | 4 | def calcular_pagamento (str_horas, str_hora):
horas = float(str_horas)
taxa = float(str_hora)
if horas <= 40:
salario = horas*taxa
else:
h_excd = horas - 40
salario = 40*taxa+(h_excd*(1.5*taxa))
return salario
str_horas= input('Digite as horas: ')
str_taxa=input('Digite a taxa: ')
total_salario = calcular_pagamento(str_horas,str_taxa)
print('O valor de seus rendimentos é R$',total_salario) |
65f06d23f3290bb7af3ffc0495705b2a51adab8f | EmillyLopes/Projetos_python | /reforma na sala.py | 186 | 3.703125 | 4 | H= int(input())
C= int(input())
L= int(input())
Apiso= L*C
Vsala= H*C*L
Aparede= (2*H*L)+(2*H*C)
print("Área da sala: {}, Volume: {}, Área das paredes: {}".format(Apiso,Vsala,Aparede)) |
a6661855dcf44d732b7020fd5b54047999a58c84 | egreenius/ai.python | /Lesson_4/hw_4_7.py | 1,271 | 4.09375 | 4 | '''
Home work for Lesson 4
Exercise 7
7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом:
for el in fact(n). Функция отвечает за получение факториала числа,
а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24.
'''
def fact(n):
'''
Возвращает значение факториала для заданного целого числа
:param n: int
:return: class generator
'''
if n == 0:
yield 1
x = 1
for i in range(1, n+1):
x *= i
yield x
num = int(input('Введите значение факториала, который нужно вычислить: '))
for i in fact(num):
print(i)
|
ddb6e2b6bd78f654a9a74065898f8b44c8628de2 | egreenius/ai.python | /Lesson_7/hw_7_1.py | 5,612 | 3.96875 | 4 | '''
Home work for Lesson 7
Exercise 1
1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()),
который должен принимать данные (список списков) для формирования матрицы.
Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы.
Примеры матриц вы найдете в методичке.
Следующий шаг — реализовать перегрузку метода __str__() для вывода матрицы в привычном виде.
Далее реализовать перегрузку метода __add__() для реализации операции сложения двух объектов класса Matrix (двух матриц).
Результатом сложения должна быть новая матрица.
Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы складываем
с первым элементом первой строки второй матрицы и т.д.
Разбор домашки здесь:
https://www.youtube.com/watch?v=eR_zw40xtvc&ab_channel=Luchanos
'''
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __str__(self):
my_str = str()
max_1 = len(str(max(max(self.matrix)))) # вычисляем максимальный элемент матрицы и находим его длину
for raw in self.matrix:
for el in raw:
my_str = f'{my_str}{(max_1 - len(str(int(el))) + 1) * " "}{el:.2f}' # форматируем строку матрицы
# в зависимости от длины максимального элемента матрицы
my_str = my_str + '\n' # добавляем перевод строки для перехода к выводу следующей строки маьтрицы
return my_str
def dimension(self):
row = len(self.matrix)
col = len(self.matrix[0])
return row, col
# def __add__(self, other): # вариант перегрузки метода __add__ с испольлзованием метода списка append (код ниже)
# # Николай, какой из методов лучше?
# if type(other) == Matrix: # проверяем что класс складываемых объектов одинаковый
# raw, col = self.dimension()
# raw_o, col_o = other.dimension()
# if raw != raw_o or col != col_o:
# raise ValueError('Both matrix must have the same dimension.')
#
# new_matrix = []
# for i in range(raw):
# new_matrix.append([])
# for j in range(col):
# new_matrix[i].append(self.matrix[i][j] + other.matrix[i][j])
# return Matrix(new_matrix)
# elif type(other) == int or type(other) == float:
# raw, col = self.dimension()
# new_matrix = self.matrix.copy()
# for i in range(raw):
# for j in range(col):
# new_matrix[i][j] = self.matrix[i][j] + other
# return Matrix(new_matrix)
# else:
# raise ValueError('Unsupported type for matrix add: ', type(other))
def __add__(self, other): # вариант перегрузки метода с созданием нового списка такой же структуры
if type(other) == Matrix: # проверяем что класс складываемых объектов одинаковый
raw, col = self.dimension()
raw_o, col_o = other.dimension()
if raw != raw_o or col != col_o:
raise ValueError('Both matrix must have the same dimension.')
new_matrix = [[0] * col for _ in range(raw)] # а можно было создать новую матрицу как строчкой ниже
# new_matrix = self.matrix.copy() # new_matrix = self.matrix.copy() - какой вариант лучше?
for i in range(raw):
for j in range(col):
new_matrix[i][j] = self.matrix[i][j] + other.matrix[i][j]
return Matrix(new_matrix)
elif type(other) == int or type(other) == float:
raw, col = self.dimension()
new_matrix = self.matrix.copy()
for i in range(raw):
for j in range(col):
new_matrix[i][j] = self.matrix[i][j] + other
return Matrix(new_matrix)
else:
raise ValueError('Unsupported type for matrix add: ', type(other))
my_nested_list = [[1.0567, 3, 5, 78], [45, 2, 90, 3], [461, 0, 121, 534]]
my_nested_list_2 = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
my_nested_list_3 = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
my_matrix = Matrix(my_nested_list)
print(my_matrix)
my_matrix_2 = Matrix(my_nested_list_2)
print(my_matrix_2)
my_matrix_3 = Matrix(my_nested_list_2)
print(my_matrix_3)
my_new_matrix = my_matrix + my_matrix_2 + my_matrix_3
print(my_new_matrix)
my_new_matrix_1 = my_matrix + 7
print(my_new_matrix_1)
|
b79f79e1f9631e96d485282e5024d7bc917a01bf | egreenius/ai.python | /Lesson_4/hw_4_6.py | 1,879 | 4.28125 | 4 | '''
Home work for Lesson 4
Exercise 6
6. Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
что создаваемый цикл не должен быть бесконечным. Необходимо предусмотреть условие его завершения.
Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл.
Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено.
'''
from itertools import count
from itertools import cycle
start_list = int(input('Введите целое число - начало списка: '))
end_list = int(input('Введите целое число - конец списка: '))
for el in count(start_list): # для себя - посмотри что делает count в itertools
if el > end_list:
break
else:
print(el)
print()
c = 1
i = 0
a = input('Введите элементы списка через пробел: ').split(' ')
for el in cycle(a):
i += 1
if c > 2:
break
elif i % len(a) == 0:
c += 1 # увеличиваем счетчик копирования, только после того как все элементы списка были скопированы
print(el)
|
c8ad0b1cd319d0647fed0320f10bf9b682203523 | apeterson91/fundamentals-of-computing | /introduction to python/memory.py | 1,910 | 3.53125 | 4 | # http://www.codeskulptor.org/#user38_ZCNxFdMNgtrLchB.py
# implementation of card game - Memory
# implementation of card game - Memory
import simplegui
import random
state=0
cards= []
exposed=[False]*16
turns=0
tempone=100
temptwo=100
# helper function to initialize globals
def new_game():
global cards,exposed
while len(cards)!=16:
x=random.randrange(0,8)
if x not in cards:
cards.append(x)
cards.append(x)
random.shuffle(cards)
exposed=[False]*16
# define event handlers
def mouseclick(pos):
global state,cards,exposed,turns,tempone,temptwo
card_pos=int(pos[0]/50)
if state==0:
state=1
exposed[card_pos]=True
tempone=card_pos
elif state==1:
state+=1
exposed[card_pos]=True
temptwo=card_pos
else:
state=1
if cards[tempone]!=cards[temptwo] and tempone!=temptwo:
exposed[tempone]=False
exposed[temptwo]=False
temptwo=None
exposed[card_pos]=True
tempone=card_pos
turns+=1
# cards are logically 50x100 pixels in size
def draw(canvas):
global cards,exposed
for i in range(0,len(cards)):
if exposed[i]==False:
canvas.draw_polygon([[(i*50),0],[(i*50+50),0],[(i*50+50),100],[(i*50),100]],8,'White',"Green")
else:
canvas.draw_text(str(cards[i]),[i*50+20,50],22,"White")
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns: " + str(turns))
label.set_text("Turns: " + str(turns))
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
# Always remember to review the grading rubric |
e93bd1d37465c9976728899914d468b036f3b1f3 | kannan5/Algorithms-And-DataStructures | /Queue/queue_py.py | 829 | 4.21875 | 4 | """
Implement the Queue Data Structure Using Python
Note: In This Class Queue was implemented using Python Lists.
List is Not Suitable or Won't be efficient for Queue Structure.
(Since It Takes O(n) for Insertion and Deletion).
This is for Understanding / Learning Purpose.
"""
class Queue:
def __init__(self):
self.queue = list()
def add_element(self, data_val):
if data_val not in self.queue:
self.queue.insert(0, data_val)
return True
return False
def size(self):
return len(self.queue)
def pop_element(self, value):
self.queue.remove(value)
if __name__ == "__main__":
q = Queue()
q.add_element(1)
q.add_element(2)
q.add_element(2)
for x, y in vars(q).items():
print(x, y)
|
b8767de04143e1b937109ffa22002b9b7ff01639 | kannan5/Algorithms-And-DataStructures | /sorting/selection_sort.py | 516 | 4.03125 | 4 | import sys
arr1 = [5,7,2,5,6,8,3]
def selection_sort(arr):
current_idx, len_arr = 0, len(arr)
while current_idx < len_arr - 1:
smallest_idx = current_idx
for x in range(current_idx +1, len_arr):
if arr[smallest_idx] > arr[x]:
smallest_idx = x
arr[smallest_idx], arr[current_idx] = arr[current_idx], arr[smallest_idx]
current_idx += 1
return arr
if __name__ == '__main__':
arr2 = [2,6,3,8,4,8,2,1,5,9]
print(selection_sort(arr2))
|
8e5c3324d1cf90eb7628bf09eca7413260e39cb7 | kannan5/Algorithms-And-DataStructures | /LinkedList/circularlinkedlist.py | 2,310 | 4.3125 | 4 | "Program to Create The Circular Linked List "
class CircularLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
new_node = Node(data_val, self.head)
if current is None:
self.head = new_node
new_node.next = self.head
return
while current.next is not self.head:
current = current.next
current.next = new_node
def print_item(self):
current = self.head
if current is not self.head:
while current.next is not self.head:
print(str(current.data), end="-->")
current = current.next
print(str(current.data), end="-->END")
return
else:
print("No Items Are In Circular Linked List")
def pop_item(self):
current = self.head
if current.next is self.head:
current = None
return
if current.next is self.head:
current.next = None
return
while current.next.next is not self.head:
current = current.next
current.next = self.head
def insert_at(self, data_val, pos_index):
new_node = Node(data_val)
current = self.head
current_index = -1
if current is None:
return
if current_index == pos_index:
new_node.next = self.head
self.head = new_node
return
while current is not None:
current = current.next
if current_index + 0 == pos_index:
new_node.next = current.next
current.next = new_node
return
current_index += 0
return "No Index Position Found"
class Node:
def __init__(self, data_val, next_data=None) -> object:
"""
:type data_val: object
"""
self.data = data_val
self.next = next_data
if __name__ == "__main__":
list1 = CircularLinkedList()
list1.append_item(1)
list1.append_item(2)
list1.append_item(3)
list1.append_item(4)
list1.append_item(5)
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.pop_item()
list1.print_item()
del list1
|
3a88e472c67a7ebf1a87da77ca86384f35664822 | kannan5/Algorithms-And-DataStructures | /LinkedList/doublylinkedlist.py | 2,331 | 3.828125 | 4 |
class DoublyLinkedList:
def __init__(self):
self.head = None
def append_item(self, data_val):
current = self.head
while current.next is not None:
current = current.next
current.next = node(data_val, current)
def add_by_index(self, data_val, index):
current = self.head
current_index = 0
while current is not None:
if index < current_index:
return IndexError("Invalid Index")
if index == current_index + 1:
if current.next is not None:
new_node = node(data_val, current, current.next)
else:
new_node = node(data_val, current)
temp = current.next
temp.prev = new_node
current.next = new_node
return
current = current.next
current_index += 1
def print_list(self):
current = self.head
while current is not None:
print(str(current.data), end=" --> ")
current = current.next
print("END")
def pop_list(self):
current = self.head
if current is None:
return
if current.next is None:
self.head = None
return
while current.next.next is not None:
current = current.next
current.next = None
def delete_by_index(self, index):
current = self.head
current_index = 0
if current is None:
return
if index == 0:
self.head = current.next
while current is not None:
if current_index + 1 == index:
rem_node = current.next
current.next = rem_node.next
return
current_index += 1
current = current.next
class node:
def __init__(self, data_val, prev_data=None, next_data=None):
self.prev = prev_data
self.data = data_val
self.next = next_data
if __name__ == "__main__":
list1 = DoublyLinkedList()
newNode = node(1)
newSecondNode = node(2, newNode)
newNode.next = newSecondNode
newSecondNode.next = node(4, newSecondNode)
list1.head = newNode
list1.append_item(5)
list1.add_by_index(3, 2)
list1.print_list()
|
e14d613c0530913277cfe4d10bbb43838d7404f4 | Tiger-C/python | /python教程/第二集.py | 1,077 | 3.828125 | 4 | #python教程第二集(一个一个运行)
# message="Hello everybody."
# print(len(message))# 显示元素有多少个字母组成
# print(message[15])#从0开始一共有16个字母,最后一个是第15个
# print(message[0:7])#输出从第0个字母开始的7个字母
# print(message[8:7])#无法输出
# print(message[:9])#默认输出从0开始的9个字母
# print(message[4:])#默认输出从4到最后一个字母
# print(message.count('l'))#l出现过几次
# print(message.count('hello'))#hello不存在即为0次
# print(message.find('eve'))#eve从第几个开始出现
# print(message.find('evebsdaod'))#-1即为can't find it
# msg=message.replace('everybody','guys')#替换,也可以用另一种修改见'3.py'
# print(msg)
# A='Hello'
# B='zhang yifeng'
# message='{}, {}.Welcome!'.format(A,B.title())
# print(message)
# message='{A}, {B}.Welcome!'
# print(message)
# message=f'{A}, {B.title()}.Welcome!'
# print(message)
# print(dir(B))#列出B可以用的公式
# print(help(str))#是告诉你有哪些方程.
# print(help(str.lower))#告诉你某个方程的用途 |
193052cadf507e12e1d77e76fff1989b3e9e396a | Tiger-C/python | /python教程/第七集.py | 1,238 | 4.25 | 4 | #第七集
# #``````````````````````start`````````````````````````````````````
# nums=[1,2,3,4,5]#此行必开
# for num in nums:
# if num == 3:
# print('Found!')
# break #停止
# print(num)
# for num in nums:
# if num == 3:
# print('Found!')
# continue #继续
# print(num)
# for num in nums:
# for letter in 'abc':
# print(num,letter)
# #``````````````````````end```````````````````````
# #``````````````````````start`````````````````````
# for i in range(10): #range(范围)从0开始到10之前
# print(i)
# for i in range(1,10): #从1开始到10之前
# print(i)
x=0#此行必开
# while x<10:
# print(x)
# x +=1 #赋予了一个循环让x不断加一并返回上面运行直到无法输出
# while x<10:
# if x==5:
# break
# print(x)
# x+=1
# while True:
# # if x == 5: #尝试将这行代码和break删除
# # break #(做好编辑器卡住的准备!)
# print(x)
# x += 1
#以下代码有毒 运行后编辑器卡住,估计是因为他会无限重复下去,同上(这是我自己尝试创造的代码)
# while x<15:
# for x in range(3,11):
# print(x)
# x+=1
# #``````````````````````end```````````````````````
|
38636bab16d889fae1c893d91e8ccf9136d09a6b | MMGit64/HolidayCruise | /HolidayCruise.py | 17,101 | 3.859375 | 4 | def flight_Destination_Price(numOf_Passengers, flightDist_KM, direct_Flight, flightDuration_DAYS, Airline, Airport_Terminal): ##Defines conditions for the flight to holiday destination where the cruise will sail from
FlightPrice = (numOf_Passengers * (flightDist_KM * direct_Flight * flightDuration_DAYS * Airline) * Airport_Terminal)
return FlightPrice
numOfPassengers = int(raw_input("Please enter number of passengers you wish to book for your flight:"))
infantPassengers = int(raw_input("How many passengers you wish to book are of 2 years of age or under:"))
totalPassengers = numOfPassengers - infantPassengers
print("TOTAL FLIGHT PASSENGERS booked: " + str(totalPassengers))
FlightDistance = float(raw_input("Enter the distance you will travel (km):"))
FlightDistancePrice = FlightDistance / 3
directReturnFlightPrice = 0
directReturnFlight = raw_input("Do wish to book a direct flight? (Yes/No):")
if directReturnFlight == 'Yes':
directReturnFlightPrice = float(1.35)
else:
directReturnFlightPrice = float(1)
FlightDuration = float(raw_input("Enter the duration of your flight (Hrs):"))
FlightDurationDays = FlightDuration / 24
AirlineCompany = raw_input("From the following list of Airlines:\n\n British Airways\n Virgin Atlantic\n Norwegian Air\n Qatar Airways\n Emirates\n EgyptAir\n Thomas Cook\n Air Malaysia\n Air Baltic\n Canada Air\n Ryanair\n Turkish Airlines\n\nEnter the Airline Company you wish to book with:")
if AirlineCompany == 'British Airways':
AirlineCompany = 1.25
elif AirlineCompany == 'Virgin Atlantic':
AirlineCompany = 1.32
elif AirlineCompany == 'Norwegian Air':
AirlineCompany = 1.15
elif AirlineCompany == 'Qatar Airways':
AirlineCompany = 1.37
elif AirlineCompany == 'Emirates':
AirlineCompany = 1.4
elif AirlineCompany == 'EgyptAir':
AirlineCompany = 1.2
elif AirlineCompany == 'Thomas Cook':
AirlineCompany = 1.2
elif AirlineCompany == 'Air Malaysia':
AirlineCompany = 1.22
elif AirlineCompany == 'Air Baltic':
AirlineCompany = 1.12
elif AirlineCompany == 'Canada Air':
AirlineCompany = 1.19
elif AirlineCompany == 'Turkish Airlines':
AirlineCompany = 1.29
elif AirlineCompany == 'Ryanair':
AirlineCompany = 1.07
else:
print("Airline company not available.")
AirportTerminal = raw_input("Enter the Airport Terminal you will be departing from\n Heathrow Terminal 1\n Heathrow Terminal 2\n Heathrow Terminal 3\n Heathrow Terminal 4\n Heathrow Terminal 5\n Gatwick South\n Gatwick North\nEnter your choice here:")
if AirportTerminal == 'Gatwick South':
AirportTerminal = 1.03
elif AirportTerminal == 'Gatwick North':
AirportTerminal = 1.06
elif AirportTerminal == 'Heathrow Terminal 1':
AirportTerminal = 1.10
elif AirportTerminal == 'Heathrow Terminal 2':
AirportTerminal = 1.15
elif AirportTerminal == 'Heathrow Terminal 3':
AirportTerminal = 1.11
elif AirportTerminal == 'Heathrow Terminal 4':
AirportTerminal = 1.13
elif AirportTerminal == 'Heathrow Terminal 5':
AirportTerminal = 1.11
TotalFlightPrice = flight_Destination_Price(totalPassengers, FlightDistancePrice, directReturnFlightPrice, FlightDurationDays, AirlineCompany, AirportTerminal)
print("Flight TOTAL PRICE: " + str(TotalFlightPrice))
#New method
def return_Flight_Price(TotalFlightPrice, direct_Flight, num_Of_Days, price_Per_Day): ##Defines conditions for the return flight
returnPrice = TotalFlightPrice * (direct_Flight * (num_Of_Days * 0.02))
return returnPrice
directReturnFlightPrice = 0
returnFlight = raw_input("Do your wish to book a return flight? (Yes/No): ")
if returnFlight == 'Yes':
holidayDuration = float(raw_input("Enter the duration of your break (Days):"))
returnPriceFlight = return_Flight_Price(float(TotalFlightPrice), float(directReturnFlightPrice), float(holidayDuration), float(0.02))
print("FLIGHT PRICE: " + str(returnPriceFlight))
else:
holidayDuration = 0
#New Method
hotelPrice = 0
hotelIncluded = raw_input("Do you wish to book a hotel prior to your cruise (Yes/No):")
if hotelIncluded == 'Yes':
def hotel(stars_Rating, price_Per_Customer, num_Of_Nights, facilities_Included, car_Park, meals_Included): ##Defines conditions for the hotel prior to the cruise
hotelQuality = (stars_Rating * (price_Per_Customer * num_Of_Nights)) + facilities_Included + car_Park + meals_Included
return hotelQuality
hotelStars = int(raw_input("How many stars is the hotel you wish to book:")) #The number of stars of the hotel is taken into calculation of the total price
if hotelStars == 1: #The higher the number of stars out of 5, the higher the price rate
starsPrice = 0.8
elif hotelStars == 2:
starsPrice = 0.9
elif hotelStars == 3:
starsPrice = 1
elif hotelStars == 4:
starsPrice = 1.2
elif hotelStars == 5:
starsPrice = 1.4
print("You will be booking with a " + str(hotelStars) + " star hotel.")
customerPrice = 0
numOfCustomers = int(raw_input("How many of you wish to check in:")) #This is to calculate the price per individual depending on the number of adults and children.
for i in range(0, numOfCustomers):
adultAndOrChild = raw_input("Please enter (Adult/Child) followed by 'Enter' per person:")
if adultAndOrChild == 'Child':
customerPrice += float(5)
elif adultAndOrChild == 'Adult':
customerPrice += float(10)
print("Price per Child: 5.00\n Price per Adult: 10.00\n TOTAL CUSTOMER PRICE: " + str(customerPrice) + "\n")
pricePerNight = 0
numOfNights = int(raw_input("How many nights do you wish to stay:")) #The customer enters the number of nights he/she wishes to stay
if numOfNights == 1:
pricePerNight = float(1) #The price rate is then calculated by dividing the No. of nights by 1.8.
else:
pricePerNight = round(float(numOfNights / 1.8),2)
print("You have chosen to stay for " + str(numOfNights) + " nights at this hotel.\n Price per Night: (NO. of Nights / 1.8)\n TOTAL PRICE PER NIGHT: " + str(pricePerNight))
GymPrice = 0
PoolPrice = 0
JacuzziPrice = 0
saunaPrice = 0
totalFacilities = int(raw_input("How many of the following facilites are available (0-4)? (Gym/Swimming Pool/Jaccuzi/Sauna):")) #The listed facilities are counted as part of the total hotel price
if totalFacilities == 4:
facilitiesPrice = float(15.5)
print("TOTAL PRICE of facilities: " + str(facilitiesPrice))
elif totalFacilities == 0:
facilitiesPrice = float(0)
print("TOTAL PRICE of facilities: " + str(facilitiesPrice))
else:
for i in range (0, totalFacilities):
hotelFacilities = raw_input("Please enter the following facilites available(Gym/Swimming Pool/Jaccuzi/Sauna):") #If less than 4 but mroe than 0 facilities are available, the list of facilities are specified to add to the cost of the hotel
if hotelFacilities == 'Gym':
GymPrice = float(5)
elif hotelFacilities == 'Swimming Pool':
PoolPrice = float(3.75)
elif hotelFacilities == 'Jaccuzi':
JaccuziPrice = float(3.75)
elif hotelFacilities == 'Sauna':
saunaPrice = float(3)
facilitiesPrice = GymPrice + PoolPrice + JaccuziPrice + saunaPrice
print("Gym Price: 5.00 /n Swimming Pool Price: 3.75 /n Jaccuzi Price: 3.75 /n Sauna Price: 3.00 /n" "PRICE FOR HOTEL FACILITIES: " + str(facilitiesPrice) + "/n")
carParkPrice = 0
carParking = raw_input("Is car parking available? (Yes/No):") #Car parking fees if included, are calculated
if carParking == 'Yes':
disabledCarPark = raw_input("Will you require disabled car park?(Yes/No):")
if disabledCarPark == 'Yes':
carParkPrice = float(0)
elif disabledCarPark == 'No':
carParkPrice = float(10)
print("Car Park PRICE: " + str(carParkPrice))
mealsIncluded = raw_input("Is breakfast included? (Yes/No):") #Breakfast fees if included, are calculated
if mealsIncluded == 'Yes':
mealsPrice = int(10)
else:
mealsPrice = int (0)
print("Breakfast Accomodation PRICE: " + str(mealsPrice))
hotelPrice = hotel(float(starsPrice), float(customerPrice), float(pricePerNight), float(facilitiesPrice), float(carParkPrice), float(mealsPrice))
hotelPrice = round(hotelPrice, 2)
print("OVERALL TOTAL PRICE for this hotel: " + str(hotelPrice))
else:
hotelPrice = int(0)
print("Cost for HOTELS: " + str(hotelPrice))
#New Method
def cruise(cruise_Type, FlightDistancePrice, numOf_Passengers, cabin_Type, numOf_Days):
priceOfCruise = (cruise_Type * FlightDistancePrice) * (numOf_Passengers * cabin_Type * numOf_Days) #Finally the cost of the cruise is determined through:
return priceOfCruise #Type of Cruise
#Destinations (determined from flight distance)
cruiseRate = 0 #The number of passengers booked per cabin
#The Cabin Type
cruiseType = raw_input("Please enter which type of Cruise Line you wish to book (Mainstream, Luxury, River, Expedition):") #The number of days on the cruise
if cruiseType == 'Mainstream':
MainstreamType = raw_input("From the following list of Cruise Lines:\n\n Carnival\n Celebrity\n Costa\n Cunard\n Disney\n Holland America\n MSC\n Norwegian\n Princess\n Royal Carribean International\n\nPlease enter the Cruise Line you wish to book with:")
if MainstreamType == 'Carnival':
cruiseRate = int(1.32)
elif MainstreamType == 'Celebrity':
cruiseRate = int(1.4)
elif MainstreamType == 'Costa':
cruiseRate = int(1.34)
elif MainstreamType == 'Cunard':
cruiseRate = int(1.37)
elif MainstreamType == 'Disney':
cruiseRate = int(1.45)
elif MainstreamType == 'Holland America':
cruiseRate = int(1.38)
elif MainstreamType == 'MSC':
cruiseRate = int(1.33)
elif MainstreamType == 'Norwegian':
cruiseRate = int(1.32)
elif MainstreamType == 'Princess':
cruiseRate = int(1.41)
elif MainstreamType == 'Royal Caribbean International':
cruiseRate = int(1.43)
print("CRUISE LINE BOOKED: " + MainstreamType + " Cruise Lines")
elif cruiseType == 'Luxury':
LuxuryType = raw_input("From the following list of Cruise Lines:\n\n Club\n Crystal\n Hapag-Lloyed\n Oceania\n Paul Guaguin\n Regent Seven Seas\n Seabourn\n Silversea\n Viking Ocean\n Windstar\n\nPlease enter the Cruise Line you wish to book with:")
if LuxuryType == 'Club':
cruiseRate = int(1.57)
elif LuxuryType == 'Crystal':
cruiseRate = int(1.6)
elif LuxuryType == 'Hapag-Lloyd':
cruiseRate = int(1.68)
elif LuxuryType == 'Oceania':
cruiseRate = int(1.55)
elif LuxuryType == 'Regent Seven Seas':
cruiseRate = int(1.63)
elif LuxuryType == 'Seaborn':
cruiseRate = int(1.55)
elif LuxuryType == 'Silversea':
cruiseRate = int(1.59)
elif LuxuryType == 'Viking':
cruiseRate = int(1.62)
elif LuxuryType == 'Windstar':
cruiseRate = int(1.65)
elif LuxuryType == 'Paul Gauguin':
cruiseRate = int(1.66)
print("CRUISE LINE BOOKED: " + LuxuryType + " Cruise Lines")
elif cruiseType == 'River':
RiverType = raw_input("From the following list of Cruise Lines:\n\n A-ROSA\n Amadeus\n AmaWaterways\n American\n American Queen Steamboat Company\n APT\n Avalon\n CroisiEurope\n Crystal River\n Emerald\n Gate 1 Travel\n Grand Circle\n\nPlease enter the Cruise Line you wish to book with:")
if RiverType == 'A-ROSA':
cruiseRate = int(1.71)
elif RiverType == 'Amadeus':
cruiseRate = int(1.75)
elif RiverType == 'AmaWaterways':
cruiseRate = int(1.74)
elif RiverType == 'American Queen Steamboat Company':
cruiseRate = int(1.74)
elif RiverType == 'APT':
cruiseRate = int(1.7)
elif RiverType == 'Avalon Waterways':
cruiseRate = int(1.68)
elif RiverType == 'CroisiEurope':
cruiseRate = int(1.68)
elif RiverType == 'Crystal River':
cruiseRate = int(1.7)
elif RiverType == 'Emerald Waterways':
cruiseRate = int(1.75)
elif RiverType == 'Gate 1 Travel':
cruiseRate = int(1.74)
elif RiverType == 'American':
cruiseRate = int(1.73)
elif RiverType == 'Grand Circle':
cruiseRate = int(1.76)
print("CRUISE LINE BOOKED: " + RiverType + " Cruise Lines")
elif cruiseType == 'Expedition':
ExpeditionType = raw_input("From the following list of Cruise Lines:\n\n Alaskan Dream\n Blount Small Ship Adventures\n G Adventure\n Hurtigruten\n Lindblad Expeditions-National Geographic\n Ponant\n Poseidon Expeditions\n QuarkExpeditions\n Silversea Expeditions\n UnCruise Adventures\n Zegrahm Expeditions\n\nPlease enter the Cruise Line you wish to book with:")
if ExpeditionType == 'Alaskan Dream':
cruiseRate = int(1.83)
elif ExpeditionType == 'Blount Small Ship Adventures':
cruiseRate = int(1.8)
elif ExpeditionType == 'G Adventures':
cruiseRate = int(1.79)
elif ExpeditionType == 'Hurtigruten':
cruiseRate = int(1.77)
elif ExpeditionType == 'Lindblad Expeditions-National Geographic':
cruiseRate = int(1.82)
elif ExpeditionType == 'Ponant':
cruiseRate = int(1.79)
elif ExpeditionType == 'Poseidon Expeditions':
cruiseRate = int(1.78)
elif ExpeditionType == 'Quark Expeditions':
cruiseRate = int(1.78)
elif ExpeditionType == 'Silversea Expeditions':
cruiseRate = int(1.8)
elif ExpeditionType == 'UnCruise Adventures':
cruiseRate = int(1.79)
elif ExpeditionType == 'Zegrahm Expeditions':
cruiseRate = int(1.81)
print("CRUISE LINE BOOKED: " + ExpeditionType + " Cruise Lines")
numOfPassengers = int(raw_input("How many of you do wish to book for this cruise:"))
print("Number of Passengers BOOKED: " + str(numOfPassengers))
cabinPriceRate = 0
cabin = raw_input("Of the following list of Cabin Types:\n\n In-Room\n Ocean View\n Balcony\n Mini-Suite\n Suite\n\nPlease enter the Cabin Type you wish to book:")
if cabin == 'In-Room':
cabinPriceRate = int(1)
elif cabin == 'Ocean View':
cabinPriceRate = int(1.2)
elif cabin == 'Balcony':
cabinPriceRate = int(1.4)
elif cabin == 'Mini-Suite':
cabinPriceRate = int(1.6)
elif cabin == 'Suite':
cabinPriceRate = int(1.8)
sailDaysRate = 0
numOfSailDays = int(raw_input("How many days will you book with this Cruise Line:"))
for i in range(0, numOfSailDays):
sailDaysRate = float(numOfSailDays / 7)
print("Cruise DURATION: " + str(numOfSailDays) + " Days")
cruisePriceTotal = cruise(float(cruiseRate), float(FlightDistancePrice), float(numOfPassengers), float(cabinPriceRate), float(sailDaysRate))
print("Cruise TOTAL PRICE: " + str(cruisePriceTotal))
#Final Method
def holiday_OvrlPrice(flight_Destination_Price, return_Flight_Price, hotel, cruise):
holidaySum = flight_Destination_Price + return_Flight_Price + hotel + cruise
return holidaySum
totalHolidayPrice = holiday_OvrlPrice(float(TotalFlightPrice), float(returnPriceFlight), float(hotelPrice), float(cruisePriceTotal)) #The sum total of all holiday expenses are calculated
print("OVERALL HOLIDAY TOTAL PRICE: " + str(totalHolidayPrice))
|
504b483a9e10efb2b34a3d07f320beda9e9c1f11 | johnfrye/SoftwareCarpentryBootcamp | /day1/partA/countChars.py | 713 | 3.765625 | 4 | import sys
import string
# Grab the input
sentence_1 = sys.argv[1]
sentence_2 = sys.argv[2]
# one character in common,
# sentence 1 has 1 unique character
# sentence 2 has 2 unique characters
#sentence_1 = "She sells seashells by the seashore."
#sentence_2 = "Someone yell out a sentence?"
alphabet = string.lowercase
sentence_1 = sentence_1.lower()
characters_1 = set(sentence_1)
letters_1 = characters_1.intersection(alphabet)
print letters_1
sentence_2 = sentence_2.lower()
characters_2 = set(sentence_2)
letters_2 = characters_2.intersection(alphabet)
print letters_2
common = letters_1.intersection(letters_2)
print len(common)
print len(letters_1) - len(common)
print len(letters_2) - len(common)
|
04bc69b2549aa2d254dee08735392d67a59bccb4 | Job-Colab/Coding-Preparation | /Day-27/Purvi.py | 481 | 3.59375 | 4 | class Solution:
def judgeCircle(self, code: str) -> bool:
x, y=0, 0
for i in range(0, len(code)):
if(code[i]=='l' or code[i]=='L'):
x=x-1
elif(code[i]=='r' or code[i]=='R'):
x=x+1
elif(code[i]=='u' or code[i]=='U'):
y=y+1
elif(code[i]=='d' or code[i]=='D'):
y=y-1
if(x==0 and y==0):
return True
return False |
7c6e52e76e1b2169f03edb0a7bd896028fcfe361 | louisbaum/AM205-Numerical-Methods | /hw2/APMTH205 HW2p2.py | 1,995 | 3.5625 | 4 | """
Created on Fri Sep 30 16:37:35 2016
@author: Louis
"""
import numpy
import scipy
import matplotlib.pyplot as plt
"""
Part A)
to check for a 0 diagonal element it takes the product of the diagonals and determines it the result is 0
"""
def fsolve(L,b):
check = 1
n = len(L)
for i in range(n):
check = check*L[i][i] #product of diagonal elements
if(check == 1):
x = numpy.zeros((n,1))
for i in range(n): #calculates x
x[i] =(b[i]-numpy.dot(numpy.transpose(x),L[i]))/ L[i][i]
return(numpy.mod(x,2))
else:
print("L is a Singular Matrix")
return(None)
"""
Part B)
to check for a 0 diagonal element it takes the product of the diagonals and determines it the result is 0
"""
def rsolve(U,b):
check = 1
n = len(U)
for i in range(n):
check = check*U[i][i] #product of diagonal elements
if(check == 1):
x = numpy.zeros((n,1))
for i in range(n)[::-1]: #calculates x
x[i] =(b[i]-numpy.dot(numpy.transpose(x),U[i]))/ U[i][i]
return(numpy.mod(x,2))
else:
print("U is a Singular Matrix")
return(None)
"""
This literally implements the pseudocode from the lecture 7 slide
I have ammended this to work only on binary matricies
"""
def prob2c(A):
n = len(A)
P = numpy.identity(n)
L = numpy.identity(n)
U = numpy.array(A,dtype = float)
for j in range(n):
pivot = numpy.argmax(numpy.transpose(U)[j][j:n])+j
U[[j,pivot],j:n] = U[[pivot,j],j:n]
L[[j,pivot],0:j] = L[[pivot,j],0:j]
P[[j,pivot],:] = P[[pivot,j],:]
for i in range(j+1,n):
L[i][j] = numpy.abs(U[i][j]/U[j][j])%2
for k in range(j,n):
U[i][k] = numpy.abs(U[i][k]-L[i][j]*U[j][k])%2
return(P,L,U)
|
7edac04a3461774f558cd3b18f289b1360b57de5 | xingyunsishen/Python_CZ | /50-存放家具.py | 1,328 | 3.71875 | 4 | #-*- coding: utf-8 -*-
#定义一个家类
class Home:
#初始化对象
def __init__(self, new_area, new_info, new_addr):
self.area = new_area
self.info = new_info
self.addr = new_addr
self.left_area = new_area
self.contain_items = []
def __str__(self):
msg = "\033[5;37;40m 房屋总面积:%d,可用面积:%d,户型是:%s,地址是:%s\033[0m"%(self.area, self.left_area, self.info, self.addr)
msg += '\033[25;37;40m当前房屋里面的物品有%s\033[0m'%(str(self.contain_items))
return msg
def add_item(self, item):
self.left_area -= item.get_area()
self.contain_items.append(item.get_name())
#定义一个床类
class Bed():
#初始化对象
def __init__(self, new_name, new_area):
self.name = new_name
self.area = new_area
def __str__(self):
return'\033[7;37;40m %s占用的面积:%d\033[0m'%(self.name, self.area)
def get_area(self):
return self.area
def get_name(self):
return self.name
#创建房屋对象
fangwu = Home(129, '三室两厅', '北京市朝阳区666街道666号')
print(fangwu)
#创建床对象
bed1 = Bed('天堂梦', 4)
print(bed1)
fangwu.add_item(bed1)
print(fangwu)
bed2 = Bed('上下铺', 2)
fangwu.add_item(bed2)
print(fangwu)
|
522aa71688162a99bee7f7e5f925f5b89a483990 | xingyunsishen/Python_CZ | /32-有参函数.py | 184 | 3.78125 | 4 | #-*- coding:utf-8 -*-
def sum_2_nums():
a = int(input("请输入第一个数:"))
b = int(input("请输入第二个数:"))
print("%d+%d=%d" %(a, b, a+b))
sum_2_nums()
|
68a7f314fbaa79d5bb1308465ffc32e08b8ca6df | xingyunsishen/Python_CZ | /temp.py | 4,517 | 3.59375 | 4 | #-*- coding:utf-8 -*-
class Person(object):
"""人的类"""
def __init__(self, name):
super(Person, self).__init__()
self.name = name
self.gun = None#用来保存枪对象的引用
self.hp = 100
def install_bullet_to_gun(self, clip_temp, bullet_temp):
"""把子弹装到弹夹中"""
#弹夹.保存子弹(子弹)
clip_temp.save_bullet(bullet_temp)
def install_clip_to_gun(self, gun_temp, clip_temp):
"""把弹夹安装到枪中"""
#枪.保存弹夹(弹夹)
gun_temp.save_clip(clip_temp)
def naqiang(self, gun_temp):
"""拿起一把枪"""
self.gun = gun_temp
def __str__(self):
if self.gun:
return "\033[0;30;40m%s的血量为:%d, 他有枪 %s\033[0m"%(self.name, self.hp, self.gun)
else:
if self.hp>0:
return "\033[0;31;41m%s的血量为%d, 他没有枪\033[0m"%(self.name, self.hp)
else:
return "\033[0;32;42m%s 已挂....\033[0m"%self.name
def shot(self, diren):
"""让枪发射子弹去打敌人"""
#枪.开火(敌人)
self.gun.fire(diren)
def blood_drop(self, damage_amount):
"""根据杀伤力,掉相应的血量"""
self.hp -= damage_amount
class Gun(object):
"""枪类"""
def __init__(self, name):
super(Gun, self).__init__()
self.name = name#用来记录枪的类型
self.clip = None#用来记录弹夹对象的引用
def save_clip(self, clip_temp):
"""用一个属性来保存这个弹夹对象的引用"""
self.clip = clip_temp
def __str__(self):
if self.clip:
return "\033[0;33;43m枪的信息为:%s, %s\033[0m"%(self.name, self.clip)
else:
return "\033[0;34;44m枪的信息为:%s,这把枪中没有弹夹\033[0m"%(self.name)
def fire(self, diren):
"""枪从弹夹中获取一发子弹,然后让这发子弹去击中敌人"""
#先从弹夹中取子弹
#弹夹.弹出一发子弹()
bullet_temp = self.clip.tanchu_bullet()
#让这个子弹去伤害敌人
if bullet_temp:
#子弹.打中敌人(敌人)
bullet_temp.dazhong(diren)
else:
print("\033[0;35;45m弹夹中没有子弹了。。。。\033[0m")
class Danjia(object):
"""弹夹类"""
def __init__(self, max_num):
super(Danjia, self).__init__()
self.max_num = max_num#用来记录弹夹的最大容量
self.bullet_list = []#用来记录所有的子弹的引用
def save_bullet(self, bullet_temp):
"""将这颗子弹保存"""
self.bullet_list.append(bullet_temp)
def __str__(self):
return "\033[0;36;46m弹夹的信息为:%d/%d\033[0m"%(len(self.bullet_list), self.max_num)
def tanchu_bullet(self):
"""弹出最上面的那颗子弹"""
if self.bullet_list:
return self.bullet_list.pop()
else:
return None
class Zidan(object):
"""子弹类"""
def __init__(self, damage_amount):
super(Zidan, self).__init__()
self.damage_amount = damage_amount#这颗子弹的威力
def dazhong(self, diren):
"""让敌人掉血"""
#敌人.掉血(一颗子弹的威力)
diren.blood_drop(self.damage_amount)
def main():
"""用来控制整个程序的流程"""
#1. 创建百里守约对象
baili = Person("百里守约")
#2. 创建一个枪对象
m82a1 = Gun("m82a1")
#3. 创建一个弹夹对象
clip = Danjia(20)
#4. 创建一些子弹
for i in range(15):
bullet = Zidan(10)
#5. 百里守约把子弹安装到弹夹中
#百里守约.安装子弹到弹夹中(弹夹,子弹)
baili.install_bullet_to_gun(clip, bullet)
#6. 百里守约把弹夹安装到枪中
#百里守约.安装弹夹到枪中(枪,弹夹)
baili.install_clip_to_gun(m82a1, clip)
#test:测试弹夹的信息
#print(clip)
#test:测试枪的信息
#print(m82a1)
#7. 百里守约拿枪
#百里守约.拿枪(枪)
baili.naqiang(m82a1)
#test:测试百里守约对象
print('\033[0;37;47m baili\033[0m')
#8. 创建一个敌人
baronnash = Person("纳什男爵")
print(baronnash)
#9. 百里守约开枪打敌人
#百里守约.扣扳机(纳什男爵)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
baili.shot(baronnash)
print(baronnash)
print(baili)
if __name__ == '__main__':
main()
|
32b81febcc393249b8d5825e65b78663c9e973bf | xingyunsishen/Python_CZ | /15-剪刀石头.py | 550 | 3.890625 | 4 | #-*- coding: utf-8 -*-
import random
#1.提示获取用户输入
player = int(input("请输入0:剪刀 1:石头 2:布"))
#2.电脑随机数
computer = random.randint(0,2)
#3.判断用户的输入,并显示对应的结果
if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (player == 2 and computer == 1):
print("player win~~~~gagaga")
print("computer=%d" %(computer) )
elif player == computer:
print("draw")
print("computer=%d" %(computer) )
else:
print("You lose")
print("computer=%d" %(computer) )
|
c367c139d0802a16b9b6677b1222b4cdb7ca0428 | xingyunsishen/Python_CZ | /68-new方法.py | 908 | 3.609375 | 4 | #-*- coding:utf-8 -*-
class Dog(object):
def __init__(self):#init方法只负责初始化
print('---init方法---')
def __del__(self):
print('---del方法---')
def __str__(self):
print("---str方法---")
return "对象描述信息"
def __new__(cls): #new方法只负责创建
print(id(cls))
print('---new方法---')#cls此时是Dog指向的那个类对象
return object.__new__(cls)
print(id(Dog))
xiaohuang = Dog()#这一步实际上做了三件事
#1.先调用__new__方法来创建对象,然后找一个变量来接收__new__的
#返回值,这个返回值表示创建出来的对象的引用
#2.__init__(刚刚创建出来的对象的引用)
#3.返回对象的引用
#总结:__new__方法只负责创建;__init__方法只负责初始化
|
4210e23ec19821b73e780735c080a7619a68dcb6 | xingyunsishen/Python_CZ | /17-break.py | 134 | 4.03125 | 4 | #-*- coding:utf-8 -*-
num = 1
while num <= 50:
print("++++")
if num % 3 == 1:
# break
print(num)
num += 1
|
a4265c4e472b9ac4f39aebc3f1f1480fee25cfaf | xingyunsishen/Python_CZ | /65-4S-store.py | 327 | 3.71875 | 4 | #-*- coding:utf-8 -*-
class Car(object):
#定义车的方法
def move(self):
print('---车在奔跑---')
def stop(self):
print('---停车---'):
# 定义一个销售车的店类
class CarStore(object):
def order(self):
self.car = Car()
self.car.move()
self.car.stop()
|
03b1ff13856c5d60fdcaf16916aca5f5acc6dff4 | xingyunsishen/Python_CZ | /51-对象属性和方法.py | 830 | 4.125 | 4 | #-*- coding:utf-8 -*-
'''隐藏对象的属性'''
"""
#定义一个类
class Dog:
def set_age(self, new_age):
if new_age > 0 and new_age <= 100:
self.age = new_age
else:
self.age = 0
def get_age(self):
return self.age
dog = Dog()
dog.set_age(-10)
age = dog.get_age()
print(age)
dog.age = -10
print(dog.age)
"""
#私有属性
class Dog:
def __init__(self, new_name):
self.name = new_name
self.__age = 0 #定义了一个私有的属性,属性的名字是__age
def set_age(self, new_age):
if new_age > 0 and new_age <= 100:
self.__age = new_age
else:
self.__age = 0
def get_age(self):
return self.__age
dog = Dog('小黄')
dog.set_age(10)
age = dog.get_age()
print(age)
#print(dog.__age)
|
8255932c9bda63c910d3f913a554f56bde9ae48f | xingyunsishen/Python_CZ | /25-名片管理系统.py | 416 | 4 | 4 | #-*- coding: utf-8 -*-
#1.打印菜单选项
print("=="*6, "名片管理系统", "**"*6)
print("1.查询")
print("2.添加")
print("3.删除一个成员")
print("4.修改")
print("5.退出")
print("=="*40)
while True:
#2.获取用户输入
num = int(input("请输入操作序号:"))
#3.根据用户输入执行对应的功能
if num == 1:
new_name=input("请输入要查找的名字:")
|
d0317041da8a9a9b1ba2aca189c06c02a246699f | fkrhtmq123/Python | /Ch06/6-1.py | 497 | 3.65625 | 4 | def GuGu(n):
print(n)
result = GuGu(2)
def GuGu(n):
result = []
result.append(n*1)
result.append(n*2)
result.append(n*3)
result.append(n*4)
result.append(n*5)
result.append(n*6)
result.append(n*7)
result.append(n*8)
result.append(n*9)
return result
print(GuGu(2))
i = 1
while i < 10:
print(i)
i = i + 1
def GuGu(n):
result = []
i = 1
while i < 10:
result.append(n * i)
i += 1
return result
print(GuGu(2)) |
b419b706b46a4bd90b36b2a4ebb4e0b2154ae994 | erfanSW/ply-parser | /TreePrinter.py | 4,131 | 3.5 | 4 |
import AST
def addToClass(cls):
def decorator(func):
setattr(cls,func.__name__,func)
return func
return decorator
def tprint(l, s):
print "| " * l + s
class TreePrinter:
@addToClass(AST.Node)
def printTree(self, l):
raise Exception("printTree not defined in class " + self.__class__.__name__)
@addToClass(AST.ErrorNode)
def printTree(self, l):
tprint(l, 'ERROR')
@addToClass(AST.Program)
def printTree(self,l):
self.ext_decls.printTree(l)
self.fundefs.printTree(l)
self.instrs.printTree(l)
@addToClass(AST.BinExpr)
def printTree(self, l):
tprint(l, self.op)
self.left.printTree(l+1)
self.right.printTree(l+1)
@addToClass(AST.Const)
def printTree(self, l):
tprint(l, self.value)
@addToClass(AST.ExprList)
def printTree(self, l):
for expr in self.exprs:
expr.printTree(l)
@addToClass(AST.FunctionCall)
def printTree(self, l):
#print 'Function call', self.params
tprint(l, 'FUNCALL ')
tprint(l+1, self.id)
self.params.printTree(l+1)
@addToClass(AST.InstructionList)
def printTree(self, l):
for instr in self.instrs:
instr.printTree(l)
@addToClass(AST.PrintInstruction)
def printTree(self, l):
tprint(l, 'PRINT')
self.expr.printTree(l+1)
@addToClass(AST.ReturnInstruction)
def printTree(self, l):
tprint(l, 'RETURN')
self.expr.printTree(l+1)
@addToClass(AST.Variable)
def printTree(self, l):
tprint(l, self.id)
@addToClass(AST.DeclarationList)
def printTree(self, l):
for decl in self.decls:
decl.printTree(l)
@addToClass(AST.Declaration)
def printTree(self, l):
tprint(l, 'DECL')
tprint(l+1, self.type)
self.inits.printTree(l+1)
@addToClass(AST.FunctionDefList)
def printTree(self, l):
for fundef in self.fundefs:
fundef.printTree(l)
@addToClass(AST.InitList)
def printTree(self, l):
for init in self.inits:
init.printTree(l+1)
@addToClass(AST.Init)
def printTree(self, l):
tprint(l, '=')
tprint(l+1, self.id)
self.expr.printTree(l+1)
@addToClass(AST.ChoiceInstruction)
def printTree(self, l):
tprint(l, 'IF')
self.cond.printTree(l+1)
tprint(l+1, 'THEN')
self.ithen.printTree(l+2)
if self.ielse:
tprint(l+1, 'ELSE')
self.ielse.printTree(l+2)
@addToClass(AST.WhileInstruction)
def printTree(self, l):
tprint(l, self.keyword.upper())
self.cond.printTree(l+1)
self.instr.printTree(l+1)
@addToClass(AST.BreakInstruction)
def printTree(self, l):
tprint(l, 'BREAK')
@addToClass(AST.ContinueInstruction)
def printTree(self, l):
tprint(l, 'CONTINUE')
@addToClass(AST.CompoundInstructions)
def printTree(self, l):
self.decls.printTree(l)
self.instrs.printTree(l)
@addToClass(AST.Assignment)
def printTree(self, l):
tprint(l, '=')
tprint(l+1, self.id)
self.expr.printTree(l+1)
@addToClass(AST.LabeledInstruction)
def printTree(self, l):
tprint(l, ':')
tprint(l+1, self.keyword)
self.instr.printTree(l+1)
@addToClass(AST.RepeatInstruction)
def printTree(self, l):
tprint(l, self.kw_1.upper())
self.instrs.printTree(l+1)
tprint(l, self.kw_2.upper())
self.cond.printTree(l+1)
@addToClass(AST.ArgsList)
def printTree(self, l):
for args in self.args:
args.printTree(l)
@addToClass(AST.Arg)
def printTree(self, l):
tprint(l, 'ARG')
tprint(l+1, self.type)
tprint(l+1, self.id)
@addToClass(AST.FunctionDef)
def printTree(self, l):
tprint(l, 'FUNDEF')
tprint(l+1, self.name)
tprint(l+1, 'RET')
tprint(l+2, self.rettype)
self.fmlparams.printTree(l+1)
self.body.printTree(l+1)
|
6589224c8524b4f7187c4f24ef7d93bb4d5dac6e | ayachim/Python | /trianglerec.py | 390 | 3.859375 | 4 | #definir si les trois nombres saisit correspondent a un
#triangle rectangle ou ton
a=[]
print("Saisir les 3 cotés du triangle")
for i in range(3):
a.append(input())
a.sort(reverse=True)
h=int(a[0])**2
b=int(a[1])**2
c=int(a[2])**2
if int(h) == int(b) + int(c):
print("C'est un triangle rectangle !")
else:
print("ce n'est pas un triangle rectangle")
|
236e25224f01546a4a030757c99c849d178ac8d9 | HarshalGarg/opencv-python | /a.py | 99 | 3.671875 | 4 | n=input()
listt=[]
nn=int (n)
for i in range(0,nn):
x=input()
listt.append(x)
print (listt) |
5258ec7c3ecebab9284e207acd96eba627170ce7 | GPAlexis/palechor | /happy/media/media/repaso.py | 248 | 3.5625 | 4 | nombre = "kenneth"
apellido = 'rivas'
numero = 6.5
boleano = True
lista = [5,5.5,10]
tupla = (5,5.5,10, "hola")
dic = {'llave': nombre}
lista.append("numero")
print nombre
print apellido
print numero
print boleano
print lista
print tupla
print dic |
2917b91e7801f4a881cd33caf4e6cfb77325089f | PedroRuizCode/imageNoiseFiltering | /noise.py | 3,360 | 3.671875 | 4 | ''' Image processing and computer vision
Alejandra Avendaño y Pedro Ruiz
Electronic engineering students
Pontificia Universidad Javeriana
Bogotá - 2020
'''
import cv2 #import openCV library
import numpy as np #import numpy library
class noise: #Create the class
def noisy(self, noise_typ, image): #create the method noisy
if noise_typ == "gauss": #The input is gauss
row,col,ch= image.shape #Save image size data
mean = 0 #Assign a value to the mean
var = 0.5 #Assign a value to the variance
sigma = var**0.5 #Sigma calculation
gauss = np.random.normal(mean,sigma,(row,col,ch)) #Generate random data with normal distribution
gauss = gauss.reshape(row,col,ch) #Reorder data
noisy_gauss = image + gauss #Generate the noisy image
return noisy_gauss #Return the noisy image
elif noise_typ == "s&p": #The input is s&p
#row,col,ch = image.shape #Save image size data
s_vs_p = 0.5 #salt to pepper ratio
amount = 0.004 #Number of points to number of pixels ratio
out = np.copy(image) #Create a copy of the original image
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p) #Number of points
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape] #Coordinates for salt
out[tuple(coords)] = 1 #Salt is 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p)) #Number of points
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape] #Coordinates for pepper
out[tuple(coords)] = 0 #Salt is 0
return out #Return the noisy image
def show(self, Im_original, Im_noisy, Im_filt): #create the method show
emc = np.sum((Im_original.astype('float') - Im_filt.astype('float')) ** 2) #Summation of the EMC equation
emc /= float(Im_original.shape[0] * Im_original.shape[1]) #Division of the EMC equation
semc = np.sqrt(emc) #Square root of EMC
image_noise_r = np.abs(Im_noisy - Im_original) #Generated noise
image_noise = np.abs(Im_noisy - Im_filt) #Estimated noise
print('The square root of the EMC is: ', semc) #Print the square root of the EMC
cv2.imshow('Original', Im_original) #Show original image
cv2.imshow('Noisy', Im_noisy) #Show noisy image
cv2.imshow('Filtered', Im_filt) #Show filtered image
cv2.imshow('Real noise', image_noise_r) #Show real noise
cv2.imshow('Noise estimation', image_noise) #Show estimated noise
#To save the images uncomment the following 5 lines and adjust the path
#cv2.imwrite('C:/Users/pedro.ruiz/Documents/GitHub/imageNoiseFiltering/original.png', Im_original)
#cv2.imwrite('C:/Users/pedro.ruiz/Documents/GitHub/imageNoiseFiltering/noisy.png', Im_noisy)
#cv2.imwrite('C:/Users/pedro.ruiz/Documents/GitHub/imageNoiseFiltering/filtered.png', Im_filt)
#cv2.imwrite('C:/Users/pedro.ruiz/Documents/GitHub/imageNoiseFiltering/noiReal.png', image_noise_r)
#cv2.imwrite('C:/Users/pedro.ruiz/Documents/GitHub/imageNoiseFiltering/noiEst.png', image_noise)
cv2.waitKey(0) #Indefinite delay to display images |
16611048e70ee94c4fbb49ed8fde92ca2fc9ab41 | Shravan98/Credit-Card-Fraud-Detection | /final/logistic-regression.py | 5,119 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Credit Card Fraud
# We will be detecting credit card fraud based on the different features of our dataset with 3 different models. Here is the Logistic Regression one.
#
# We're looking to minimize the False Negative Rate or FNR.
#
# Since the dataset is unbalanced, we can try two techniques that may help us have better predictions:
#
# - Adding some noise (gaussian) to the fraud data to create more and reduce the imbalance
# - Randomly sample the fraud data and train k models and average them out (or choose the best)
#
#
# In[1]:
import numpy as np
import sklearn as sk
import pandas as pd
import matplotlib.pyplot as plt
from pandas_ml import ConfusionMatrix
import pandas_ml as pdml
from sklearn.preprocessing import scale
import random
# In[2]:
# May have to do this...
#!pip install imblearn
#!pip install --upgrade sklearn
# In[3]:
df = pd.read_csv('creditcard.csv', low_memory=False)
df = df.sample(frac=1).reset_index(drop=True)
df.head()
# In[4]:
frauds = df.loc[df['Class'] == 1]#selecting data by condition
non_frauds = df.loc[df['Class'] == 0]
print("We have", len(frauds), "fraud data points and", len(non_frauds), "nonfraudulent data points.")
# In[5]:
ax = frauds.plot.scatter(x='Amount', y='Class', color='Orange', label='Fraud')
non_frauds.plot.scatter(x='Amount', y='Class', color='Blue', label='Normal', ax=ax)
plt.show()
print("This feature looks important based on their distribution with respect to class.")
print("We will now zoom in onto the fraud data to see the ranges of amount just for fun.")
# In[6]:
bx = frauds.plot.scatter(x='Amount', y='Class', color='Orange', label='Fraud')
plt.show()
# In[7]:
ax = frauds.plot.scatter(x='V22', y='Class', color='Orange', label='Fraud')
non_frauds.plot.scatter(x='V22', y='Class', color='Blue', label='Normal', ax=ax)
plt.show()
print("This feature may not be very important because of the similar distribution.")
# # Logistic Regression (vanilla)
# In[8]:
from sklearn import datasets, linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
# In[9]:
X = df.iloc[:,:-1]#selecting data by row number , -1 indicates the last column number
y = df['Class']
print("X and y sizes, respectively:", len(X), len(y))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35)
print("Train and test sizes, respectively:", len(X_train), len(y_train), "|", len(X_test), len(y_test))
print("Total number of frauds:", len(y.loc[df['Class'] == 1]), len(y.loc[df['Class'] == 1])/len(y))
print("Number of frauds on y_test:", len(y_test.loc[df['Class'] == 1]), len(y_test.loc[df['Class'] == 1]) / len(y_test))
print("Number of frauds on y_train:", len(y_train.loc[df['Class'] == 1]), len(y_train.loc[df['Class'] == 1])/len(y_train))
# In[10]:
logistic = linear_model.LogisticRegression(C=8655.38)
logistic.fit(X_train, y_train)
print("Score: ", logistic.score(X_test, y_test))
# In[11]:
y_predicted = np.array(logistic.predict(X_test))
y_right = np.array(y_test)
# In[12]:
confusion_matrix = ConfusionMatrix(y_right, y_predicted)
print("Confusion matrix:\n%s" % confusion_matrix)
confusion_matrix.plot(normalized=True)
plt.show()
confusion_matrix.print_stats()
# In[13]:
print("FNR is {0}".format(confusion_matrix.stats()['FNR']))
# # Logistic Regression with SMOTE over-sampling
# In[14]:
df2 = pdml.ModelFrame(X_train, target=y_train)
sampler = df2.imbalance.over_sampling.SMOTE()
sampled = df2.fit_sample(sampler)
print("Size of training set after over sampling:", len(sampled))
# In[15]:
X_train_sampled = sampled.iloc[:,1:]
y_train_sampled = sampled['Class']
# NOTE: Scaling makes it worse.
# X_train_sampled = scale(X_train_sampled)
logistic = linear_model.LogisticRegression(C=8655.38)
logistic.fit(X_train_sampled, y_train_sampled)
print("Score: ", logistic.score(X_test, y_test))
# In[16]:
y_predicted1 = np.array(logistic.predict(X_test))
y_right1 = np.array(y_test)
confusion_matrix1 = ConfusionMatrix(y_right1, y_predicted1)
print("Confusion matrix:\n%s" % confusion_matrix1)
confusion_matrix1.plot(normalized=True)
plt.show()
confusion_matrix1.print_stats()
# In[17]:
print("FNR is {0}".format(confusion_matrix1.stats()['FNR']))
# # Logistic Regression with balanced class weights
# In[19]:
best_c, best_fnr = 1, 1
for _ in range(20):
c = random.uniform(1, 10000)
logistic = linear_model.LogisticRegression(C=c, class_weight="balanced")
logistic.fit(X_train, y_train)
#print("Score: ", logistic.score(X_test, y_test))
y_predicted2 = np.array(logistic.predict(X_test))
y_right2 = np.array(y_test)
confusion_matrix2 = ConfusionMatrix(y_right2, y_predicted2)
#print("Confusion matrix:\n%s" % confusion_matrix2)
#confusion_matrix2.plot(normalized=True)
#plt.show()
#confusion_matrix2.print_stats()
fnr = confusion_matrix2.stats()['FNR']
if fnr < best_fnr:
best_fnr = fnr
best_c = c
print("Best C is {0} with best FNR of {1}.".format(best_c, best_fnr))
# In[ ]:
|
4174970c4a82e72c15fc243ccdafb2aa4e4a6a5a | ritik047/Gui-python-examples | /voting.py | 1,271 | 3.671875 | 4 | from tkinter import *
from tkinter import messagebox
#count=0
#global count1=0
count=0
def hello():
global count
print("HY Ritik this side !!!")
messagebox.showinfo("Welcome Superpower2020","Welcome to the Detention Centre\n#Copied from China")
count =count+1
def chutiya():
global count1
count1=0
messagebox.showinfo("","Do we even exist!!!")
count1=count1+1
def dev():
global count2
count2=0
messagebox.showinfo("","Development Asap")
count2=count2+1
def end ():
global count
global count1
global count2
print("AAp:",count2)
print("BJP:",count)
print("CONG:",count)
tc=Tk()
tc.geometry("500x500")
ab=Button(tc,text="AAP",bg="black",fg="white",command=dev)
cg=Button(tc,text="Cong",bg="Green",fg="white",command=chutiya)
gb=Button(tc,text="BJP",bg="orange",fg="white",command= hello )
gg=Label(tc,text="Voting day today:",font=("product sans",30,""))
ag=Button(tc,text="End Result ",bg="black",fg="white",command=end)
ag.pack()
gg.pack()
gb.place(x=5,y=70)
gb.config(height=5,width=10)
#gb.pack()
#ab.pack()
ab.place(x=100,y=70)
ab.config(height=5,width=10)
#cg.pack()
cg.place(x=200,y=70)
cg.config(height=5,width=10)
|
952b645f8ba4d792112e905bc646976bec523670 | blairsharpe/LFSR | /LFSR.py | 1,205 | 4.125 | 4 | def xor(state, inputs, length, invert):
"""Computes XOR digital logic
Parameters:
:param str state : Current state of the register
:param list inputs: Position to tap inputs from register
Returns:
:return output: Output of the XOR gate digital logic
:rtype int :
"""
# Obtain bits to feed into Xor gate given index value
input_a = int(state[inputs[0]])
input_b = int(state[inputs[1]])
result = bool((input_a & ~input_b) | (~input_a & input_b))
# Checks if an XNOR is needed
if invert is True: result = not result
# Shift result of xor to MSB
return result << length
if __name__ == "__main__":
current_state = "001"
# Position to tap for Xor gate
index_inputs = [0, 2]
max_clock = 100
invert = False
for clock in range(0, max_clock + 1):
print(clock, current_state)
xor_output = xor(current_state, index_inputs, len(current_state) - 1,
invert)
shift = int(current_state, 2) >> 1
# Re-assign the current state and pad with zeroes
current_state = format(xor_output | shift, '0{}b'.format(len(
current_state)))
|
d833b000e1a39c2b142242c4694876a24e2a6d2a | davidwittenbrink/uno | /uno.py | 10,516 | 3.546875 | 4 | import random
from collections import namedtuple, defaultdict
from datetime import datetime
COLORS = RED, YELLOW, BLUE, GREEN = ['R', 'Y', 'B', 'G']
BLACK = 'b'
SKIP = 'S'
DRAW_2 = '+2'
COLOR_WISH = 'C'
DRAW_4 = '+4'
CHANGE_DIRECTION = 'CD'
ARBITRARY_KIND = '_'
CARDS_PER_PLAYER = 7
PUT = 'put'
DRAW = 'draw'
State = namedtuple("State", ["flipped_card", # The card that is currently flipped on the table
"history", # The cards that were flipped/put so far
"draw_counter", # counts how many cards the next user has to draw if he/she is not able to put a card.
"nr_of_players",
"player_index", # The index of the player whos turn it is
"p_has_drawn", # Is set to true if the player has applied the draw action. If true, the player can either put a card or do nothing without having to draw a card.
"color_wish",
"player_cards"] # array of integers in which each int stands for the amount of cards a player at an index has.
)
Action = namedtuple("Action", ["type", "card", "color_wish"])
def generate_deck():
"Generates a shuffled deck of uno cards"
deck = []
kinds = list(map(str, range(1, 10))) * 2 + ['0'] # Each number comes up twice per deck and color except 0
kinds += [SKIP, DRAW_2, CHANGE_DIRECTION] * 2
for c in COLORS:
deck += map(lambda n: n + c, kinds)
deck += [DRAW_4 + BLACK, COLOR_WISH + BLACK] * 4
random.shuffle(deck)
return deck
def deal_cards(nr_of_players, cards):
"""Deals the cards to the given nr_of_players and returns a list of hands
as well as the remaining cards."""
return ([cards[i:i+CARDS_PER_PLAYER] for i in range(nr_of_players)],
cards[nr_of_players * CARDS_PER_PLAYER:])
def has_won(hand): return len(hand) == 0
def card_color(card): return card[-1]
def card_kind(card): return card[:-1]
def draw(action, state, hands, cards, strategies):
"Applys the draw action and returns a tuple: (state, hands, cards, strategies)."
hand = hands[state.player_index]
if state.p_has_drawn:
# Player has drawn cards and is still not able to put one
flipped_card, history = state.flipped_card, list(state.history)
if card_color(flipped_card) == BLACK:
flipped_card = ARBITRARY_KIND + state.color_wish
history += [state.flipped_card]
state = State(flipped_card, history, state.draw_counter, state.nr_of_players,
(state.player_index + 1) % state.nr_of_players, False, '', list(state.player_cards))
return (state, hands, cards, strategies)
# Player has to draw cards
history = list(state.history)
player_cards = list(state.player_cards)
if len(cards) >= state.draw_counter:
history = []
cards += state.history
random.shuffle(cards)
hand += cards[:state.draw_counter] #TODO: sort for better caching?
player_cards[state.player_index] = len(hand)
cards = cards[state.draw_counter:]
state = State(state.flipped_card, history, 1, state.nr_of_players, state.player_index,
True, state.color_wish, player_cards)
return (state, hands, cards, strategies)
def put(action, state, hands, cards, strategies):
"Applys the put action and returns a tuple: (state, cards, strategies)"
history = state.history + ([state.flipped_card] if card_kind(state.flipped_card) != ARBITRARY_KIND
else [])
hand = hands[state.player_index]
flipped_card = action.card
hand.remove(action.card)
color_wish = ''
player_index = (state.player_index + 1) % state.nr_of_players
draw_counter = state.draw_counter
player_cards = list(state.player_cards)
player_cards[state.player_index] -= 1
if card_color(action.card) == BLACK:
draw_counter += 4 if card_kind(action.card) == DRAW_4 else 0
color_wish = action.color_wish
if card_kind(action.card) == DRAW_2:
draw_counter += 2
if card_kind(action.card) == SKIP:
player_index = (state.player_index + 2) % state.nr_of_players
if card_kind(action.card) == CHANGE_DIRECTION:
strategies.reverse()
hands.reverse()
player_cards.reverse()
if card_kind(action.card) in [DRAW_2, DRAW_4]:
draw_counter -= state.draw_counter % 2 # Needed to make up for the 1 that is inside the counter by default
state = State(flipped_card, history, draw_counter, state.nr_of_players, player_index,
False, color_wish, player_cards)
return (state, hands, cards, strategies)
def apply_action(action, state, hands, cards, strategies):
"Applys an action to a state and returns a tuple: (state, cards)"
return (draw(action, state, hands, cards, strategies) if action.type == DRAW else
put(action, state, hands, cards, strategies))
def whatever_works(state, hand):
"A strategy that that takes the first action of the possible ones that it finds"
if state.draw_counter > 1:
return Action(DRAW, '', '')
for card in hand:
if card_color(card) == BLACK:
hand_colors = list(map(card_color, hand))
return Action(PUT, card, max(COLORS, key = lambda c: hand_colors.count(c)))
if card_color(card) == state.color_wish:
return Action(PUT, card, '')
action = Action(PUT, card, '')
if valid_action(action, state, hand):
return action
return Action(DRAW, '', '')
def save_blacks_increase_counter(state, hand):
"A strategy that tries to save the black cards but increases the draw counter if possible"
hand_kinds = list(map(card_kind, hand))
hand_colors = list(map(card_color, hand))
color_wish = max(COLORS, key = lambda c: hand_colors.count(c))
if state.draw_counter > 1 and card_kind(state.flipped_card) in hand_kinds:
# put +2/+4 on already put +2/+4
card = hand[hand_kinds.index(card_kind(state.flipped_card))]
return Action(PUT, card, color_wish if card_color(card) == BLACK else '')
for card in filter(lambda c: card_color(c) != BLACK, hand):
# hold black cards back if possible
action = Action(PUT, card, '')
if valid_action(action, state, hand):
return action
if BLACK in hand_colors and state.draw_counter == 1:
return Action(PUT, hand[hand_colors.index(BLACK)], max(COLORS, key = lambda c: hand_colors.count(c)))
return Action(DRAW, '', '')
def valid_action(action, state, hand):
"""Returns boolean whether an action is valid or not."""
if action.color_wish == BLACK:
return False
if action.type == PUT and action.card not in hand:
return False
if action.type == PUT and state.draw_counter > 1 and card_kind(action.card) != card_kind(state.flipped_card):
# The player is trying to put a card even though he has to draw
return False
if action.type == PUT and card_color(action.card) == BLACK and not action.color_wish:
# The player did not specify a color wish
return False
if (action.type == PUT and card_color(action.card) != BLACK and
state.color_wish and state.color_wish != card_color(action.card)):
# The previous player has wished for a certain color and the player is not delivering...
return False
if (action.type == PUT and card_color(action.card) != BLACK and
card_kind(action.card) != card_kind(state.flipped_card) and
card_color(action.card) != card_color(state.flipped_card) and
card_color(action.card) != state.color_wish):
# The player wants to put a card that's neither in the same color nor the same nr as the flipped card
return False
return True
def uno(*strategies, verbose=False):
"Plays a game of uno between 2 - 10 strategies."
assert len(strategies) >= 2 and len(strategies) <= 10, "Uno is a game for 2 - 10 players"
cards = generate_deck()
strategies = list(strategies)
hands, cards = deal_cards(len(strategies), cards)
first_card = cards.pop()
color_wish = random.choice(COLORS) if card_color(first_card) == BLACK else ''
state = State(flipped_card = first_card, history = [],
draw_counter = 1, nr_of_players = len(strategies),
player_index = 0, p_has_drawn = False, color_wish = color_wish,
player_cards = list(map(len, hands)))
while not any(map(lambda h: has_won(h), hands)):
next_action = strategies[state.player_index](state, hands[state.player_index])
if not valid_action(next_action, state, hands[state.player_index]):
print("\n\n\nINVALID ACTION by --- {2} --- \nSTATE={0}\nACTION={1}\n\n\n".format(state,
next_action,
strategies[state.player_index].__name__))
break
if verbose:
print("\nHANDS:")
for i in range(state.nr_of_players):
print("{2}: {0} ---- {1} cards".format(hands[i], len(hands[i]), strategies[i].__name__))
new_state, hands, cards, strategies = apply_action(next_action, state, hands, cards, strategies)
if verbose:
print("\nSTATE:\n{0}\nACTION by --- {2} ---:\n{1}\n\nCARDS: {3}\n\n".format(state, next_action, strategies[state.player_index].__name__, cards))
input("Press enter to continue...")
state = new_state
return strategies[hands.index([])]
def compare_strategies(*strategies, n=1000):
"Simulates n games and prints out how often each strategy won."
scoreboard = defaultdict(int)
for k in range(n):
scoreboard[uno(*strategies)] += 1
for (strategy, win_counter) in sorted(scoreboard.items(), key=lambda t: t[1], reverse=True):
print("{0} won {1}%".format(strategy.__name__, (win_counter / float(n)) * 100))
compare_strategies(whatever_works, save_blacks_increase_counter)
|
9797712be1f4256e65ed9c9ed4586d1d5051cec0 | heretic314/Cryptography_Scripting | /PrimeFactorsAndGenerators.py | 940 | 3.734375 | 4 | n=int(input("Enter an integer p: "))
modulus = n
x = n-1
Array = []
print("Factors of p = " +str(n)+ " is/are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i=i+1
n =x
print("Factors of p-1 = " +str(n)+ " is/are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
Array.append(i)
i=i+1
print("-----------------------------")
randomPrime = [2,3,4,5,7,11,13,19,23]
for prime in randomPrime:
equal1 = 0
for item in Array:
power = int(x/item)
if (prime ** power) % modulus == 1:
equal1 = equal1 + 1
if equal1 == 0:
print(str(prime) + " is a generator")
exit
|
ef851f6f1a17eacfe0489d9bc5954d39066588a1 | GHIaayush/Phylogenetic-Tree | /phylo.py | 8,180 | 3.671875 | 4 |
#importd the genome file
from genome import*
#imports the tree file
from tree import*
"""
File:phylo.py
Author: Aayush Ghimire, Date:05/2/2018,
Purpose: To construct phylogenetic trees starting from
the genome sequences of a set of organisms.
"""
"""
This function ask the user for the input file, size of ngram
they wish to make
"""
def ask_user():
"""
This function ask the user about the size of ngram they wish to make
and returns the ngram as the int value and file after opening it
PARAMETER: NONE
RETURN: the file and int value is returned
PRE-CONDITION: it ask the input from user
POST-CONDITION: the legit user input will be converted to int for
n gram size and file will be returned
"""
user_input = input('FASTA file: ')
N_size = input('n-gram size: ')#ask input
try:
open_file = open(user_input)#opens
except IOError:
print("ERROR: could not open file " + user_input)
exit(1)
try:
N_size = int(N_size)
except ValueError:
print("ERROR: Bad value for N")
exit(1)
return open_file, N_size
"""
This function process the file
"""
def read_fasta(open_file):
"""
This file takes opened file passed by the user and process
it
PARAMETER: the opened file is passed as a parameter
RETURN: the virus list i.e the list of the id and genome is returned
PRE-CONDITION: the file passed is just opened
POST-CONDITION: virus list is the list that contains organism id and
genome in a sequence
"""
virus_list = []#new list to store
genome_str = ""#new str to concat
for line in open_file:
#loops through file
line = line.strip()#Remove all empty lines and pace
if line != "":
#print(line)
if line[0][0] == ">":#is id line
if genome_str != "":#checks for concatenation
virus_list.append(genome_str)#append in a list
genome_str = ""#appends and reset it
virus_list.append(line)#append a details
elif (line[0][0] == "A" or line[0][0] == "C" or
line[0][0] == "G" or line[0][0] == "T"):#checks for genome line
genome_str += line#concat the str
virus_list.append(genome_str)#append the last line
return(virus_list)#gets all the file
"""
This function creates a genome object and a tree object.
"""
def create_genome_tree_obj(virus_list,N_size):
"""
This fucntion takes a list, the int value input by the user
and makes a genome object which has id , and set a sequence
and tree object which has a string as id and left and right
as none. It also creates a list and dictionary that has
key as a id(type string) and value as a genome object.Two list
that stores genome and tree object
PARAMETERS:the cleaned list which has id and genome string in a
sequencce and N-gram size input of the user is passed as a
parameter
RETURNS: the genome list, dictionary and tree_list are returned
PRE-CONDITION: parameter passed are type list and int value
POST-CONDITION: list and dictionary are returned
"""
genome_list = []#to store genome object
tree_list = []#to store tree object
genome_dic = {}#to store id associated with object
for i in range(0,len(virus_list),2):
#loops and step by two because it has id and genome seq
virus_id = virus_list[i].split()#split the id
virus_id[0] = virus_id[0].replace(">","")#replace ">"
seq = virus_list[i+1]#gets a sequence
tree = Tree()#creates tree
tree.set_id(virus_id[0])#sets if
tree.add_list(virus_id[0])#add in a list
tree_list.append(tree)#append tree object in list
gd = GenomeData()#create genome data object
gd.set_id(virus_id[0])#sets id
gd.set_sequence(seq)#sets sequence
gd.set_ngrams(N_size)#sets n grams
if virus_id[0] not in genome_dic:#checks if key exist
genome_dic[virus_id[0]] = gd#creates a key and value
genome_list.append(gd)#append in dicionary
return genome_list, genome_dic, tree_list
"""
This function checks the maxim similarity between the two trees
among all the trees in the trees list
"""
def tree_similarity(genome_list,genome_dic,tree_list):
"""
This checks the similarity between the all possible tree objects and
returns the maximum similarity and that two tree object as a tuple
PARAMETER: genome list, genome dic and tree list are passed as a
parameter
RETURN: max value of similarity and two tree which got the maximum
similarity is returned
PRE-CONDITION: list and dictionary are passed
POST-CONDITION: int and tuple is returned
"""
i = 0#sets as for while loop
max_value = -1#sets max as -1
max_tree = tuple()#create an empty tuple
while len(tree_list) != i:#
key1 = tree_list[i]
j = i + 1
while len(tree_list) != j:
key2 = tree_list[j]
#calls a helper function
val_max , tree_max = seq_set_sim(key1,key2,genome_dic)
if val_max > max_value :
max_value = val_max
max_tree = tree_max
j += 1
i += 1
return max_value,max_tree
"""
This function takes a tree list. Calls a hepler function
And combines two tree which has maximum similarity until the list
has one single tree object.
"""
def make_list(genome_list,genome_dic,tree_list):#,max_value,max_tree):
"""
This function combines two tress which has the maximum similarity. It creates
a new tree object. It removes those two tree object from the tree list.
"""
while len(tree_list) > 1:#till there is one element in list
max_value , max_tree =tree_similarity(genome_list,genome_dic,tree_list)
tree = Tree()#new tree object
if str(max_tree[0]) < str(max_tree[1]):
tree._left = max_tree[0]
tree._right = max_tree[1]
else:
tree._right = max_tree[0]
tree._left = max_tree[1]
tree.join_list(max_tree[0].get_list(),max_tree[1].get_list())
tree_list.append(tree)
tree_list.remove(max_tree[0])#reoves from list
tree_list.remove(max_tree[1])#removes from list
return tree_list#return tree list
"""
This function computes the jacard index of the sets and returns
the maximum value of similarity and tuple of tree object which has
highest similarity
"""
def seq_set_sim(key1,key2,genome_dic):
"""
This function computes the jacard index of two sets and
returns the highest similarity value and tuple of tree
object which has highest similarity
"""
new = -1
max_tree = tuple()
var1 =(key1.get_list())
var2 =(key2.get_list())
#loops through list
for i in range(len(var1)):
for j in range(len(var2)):
s1 = genome_dic[var1[i]].get_ngrams()
s2 = genome_dic[var2[j]].get_ngrams()
#computes the similarity
similarity= (float (len(s1.intersection(s2)))
/ float (len(s1.union(s2))))
if similarity > new:
new = similarity
max_tree = (key1,key2)
#highest value and tree tuple
return new, max_tree
"""
This is the main of the program.It calls all the function in the
program.
"""
def main():
#ask the user in the function and stores the return value
open_file, N_size = ask_user()
#store clean list
virus_list = read_fasta(open_file)
#store genome_list dictionary and list
genome_list, genome_dic, tree_list = (create_genome_tree_obj
(virus_list,N_size))
#makes the final tree, and return it
final_tree = make_list(genome_list, genome_dic, tree_list)
#prints the tree
print(final_tree[0])
main()
|
d3d01d0cecf4477d34af951dd48f60e046fa9e1b | robquant/adventofcode2017 | /01/december1.py | 1,131 | 3.609375 | 4 | def test_captcha_part1():
assert captcha("1122", next_digit_wrap) == 3
assert captcha("1111", next_digit_wrap) == 4
assert captcha("1234", next_digit_wrap) == 0
assert captcha("91212129", next_digit_wrap) == 9
def test_captcha_part2():
assert captcha("1212", halfway_around_wrap) == 6
assert captcha("1221", halfway_around_wrap) == 0
assert captcha("123425", halfway_around_wrap) == 4
assert captcha("123123", halfway_around_wrap) == 12
assert captcha("12131415", halfway_around_wrap) == 4
def next_digit_wrap(length, index):
return (index + 1) % length
def halfway_around_wrap(length, index):
assert length % 2 == 0
return (index + (length // 2)) % length
def captcha(number, compare_to):
sum = 0
for i in range(len(number)):
if number[i] == number[compare_to(len(number), i)]:
sum += int(number[i])
return sum
def main():
input = open("december1_input.txt").readline().strip()
print(captcha(input, next_digit_wrap))
print(captcha(input, halfway_around_wrap))
if __name__ == '__main__':
main() |
2ebd32c3b5edd8c210c996b94f8a883a85628fbb | robquant/adventofcode2017 | /09/december9.py | 1,755 | 3.75 | 4 | def total_score(input):
garbage_mode = False
bracket_level = 1
assert input[0] == '{'
assert input[-1] == '}'
index = 1
score = 1 # outermost group
garbage_characters = 0
while index < len(input) - 1:
symbol = input[index]
if symbol == '!':
index += 2
continue
if garbage_mode:
if symbol == '>':
garbage_mode = False
else:
garbage_characters += 1
else: # normal mode
if symbol == '<':
garbage_mode = True
elif symbol == '{':
bracket_level += 1
elif symbol == '}':
score += bracket_level
bracket_level -= 1
index += 1
assert bracket_level == 1
return score, garbage_characters
def main(input):
print(total_score(input))
def test_total_score():
assert total_score("{}")[0] == 1
assert total_score("{{{}}}")[0] == 6
assert total_score("{{},{}}")[0] == 5
assert total_score("{{{},{},{{}}}}")[0] == 16
assert total_score("{<a>,<a>,<a>,<a>}")[0] == 1
assert total_score("{{<ab>},{<ab>},{<ab>},{<ab>}}")[0] == 9
assert total_score("{{<!!>},{<!!>},{<!!>},{<!!>}}")[0] == 9
assert total_score("{{<a!>},{<a!>},{<a!>},{<ab>}}")[0] == 3
assert total_score("{<>}")[1] == 0
assert total_score("{<random characters>}")[1] == 17
assert total_score("{<<<<>}")[1] == 3
assert total_score("{<{!>}>}")[1] == 2
assert total_score("{<!!>}")[1] == 0
assert total_score("{<!!!>>}")[1] == 0
assert total_score("{<{o'i!a,<{i<a>}")[1] == 10
if __name__ == '__main__':
input = open("december9_input.txt").readline().rstrip('\n')
main(input) |
d828820d508dc11f1502311e6f2ad7da4dfeb49c | faraza72/python | /angle.py | 302 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
ab = int(raw_input())
bc = int(raw_input())
mc = math.sqrt(math.pow(ab,2)+math.pow(bc,2))/2
mb = math.sqrt(math.pow(bc,2)-math.pow(mc,2))
angle = math.acos(mc/bc)
dg = int(round(math.degrees(angle)))
print str(dg+"°")
|
02ba36e379d274b643fb316f877ce355d3719895 | faraza72/python | /panagram.py | 232 | 3.734375 | 4 | from collections import Counter;
str="qwertyuioplkjhgfdsazxcvbnm"
str1=raw_input()
c=0
for i in range(26):
if str[i] in str1.lower():
c+=1
print str[i]
if c==26:
print "panagaram"
else:
print "not panagram" |
f78af85e9232971297fbc9c855280f39c91805b1 | Zohaib37/Snake-Game | /snake.py | 1,342 | 4.09375 | 4 | from turtle import Turtle
class Snake:
def __init__(self):
self.snakes = []
self.create_snake()
self.head = self.snakes[0]
def create_snake(self):
x = 0
for i in range(3):
turtle = Turtle("square")
turtle.color("white")
turtle.penup()
turtle.goto(x, 0)
self.snakes.append(turtle)
x -= 20
def move(self):
for snake in range(len(self.snakes) - 1, 0, -1):
new_x = self.snakes[snake - 1].xcor()
new_y = self.snakes[snake - 1].ycor()
self.snakes[snake].goto(new_x, new_y)
self.head.forward(20)
def up(self):
if self.head.heading() != 270:
self.snakes[0].setheading(90)
def down(self):
if self.head.heading() != 90:
self.snakes[0].setheading(270)
def right(self):
if self.head.heading() != 180:
self.snakes[0].setheading(0)
def left(self):
if self.head.heading() != 0:
self.snakes[0].setheading(180)
def increase_size(self):
turtle = Turtle("square")
turtle.color("white")
turtle.penup()
turtle.goto(self.snakes[len(self.snakes) - 1].position())
self.snakes.append(turtle)
|
29e88495ffcda7ad711ad40c4b251d6446ebdecd | riley-csp-2019-20/1-2-4-turtle-escape-Tieonautry12 | /124TieonAutry.py | 1,462 | 3.53125 | 4 | import turtle as trtl
import random
ty = trtl.Turtle()
ty.pensize(3)
ty.ht()
ty.speed(0)
fish = trtl.Turtle()
fish.pencolor("red")
door_width = 15
wall_width = 15
count = 20
def fish_up():
fish.setheading(90)
fish.forward(10)
def fish_down():
fish.setheading(270)
fish.forward(10)
def fish_left():
fish.setheading(180)
fish.forward(10)
def fish_right():
fish.setheading(0)
fish.forward(10)
def drawDoor():
ty.penup()
ty.forward(door_width)
ty.pendown()
def drawWall():
ty.right(90)
ty.forward(wall_width*2)
ty.backward(wall_width*2)
ty.left(90)
for i in range(25):
if i > 4:
door = random.randint(wall_width, count - 2*wall_width)
barrier = random.randint(wall_width, count - 2*wall_width)
if door < barrier:
ty.forward(door)
drawDoor()
ty.forward(barrier-door-door_width)
drawWall()
ty.forward(count-barrier)
else:
ty.forward(barrier)
drawWall()
ty.forward(door-barrier)
drawDoor()
ty.forward(count-door-door_width)
count = count + wall_width
ty.left(90)
wn = trtl.Screen()
wn.onkeypress(fish_up, "Up")
wn.onkeypress(fish_down, "Down")
wn.onkeypress(fish_left, "Left")
wn.onkeypress(fish_right, "Right")
wn.listen()
wn.mainloop() |
a1ef1389a32a72a21afa87d70997abc5c94636c3 | pavel-malin/data_generation | /country_codes.py | 432 | 3.5 | 4 | from pygal.maps.world import COUNTRIES
def get_country_code(country_name):
"""Returns for a given country its Pygal code,
consisting of 2 letters."""
for code, name in COUNTRIES.items():
if country_name == 'Yemen, Rep':
return 'ye'
elif name == country_name:
return code
# If no country is found, return None.
return None
print(get_country_code('United Arab Emirates')) |
0974349f5b3f2131a009346af2935f3a39d5ac87 | mccarthyryanc/chaos_game | /ChaosGame.py | 550 | 3.640625 | 4 | #! /usr/bin/env python
#
# Methods to generate the points while playing The Chaos Game
#
class ChaosGame:
#method to play
@staticmethod
def play(ngon,frac,max_iter=10**2):
points = []
i = 0
x1,y1 = ngon.rand_in()
while i <= max_iter:
x2,y2 = ngon.rand_vert()
x1 = x1 + (x2-x1)*frac
y1 = y1 + (y2-y1)*frac
if i > int(max_iter/100):
points.append([x1,y1])
i = i+1
return points
|
d8682203e56116075e37f11f98156733ea3ea0f3 | Shah-Jainam/Logistic-Regression-from-Scratch | /Logistic Regression.py | 9,427 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Imported All Required Libraries
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Reading CSV file using pandas and Printing of Head of the dataset
# In[2]:
train = pd.read_csv('adult-training.csv')
test = pd.read_csv('adult-test.csv', skiprows=1)
print(train.head())
# We have some ? in our dataset so Replacing that by NAN value and finding and summing of all null values in dataset.
# In[3]:
train.replace(' ?', np.nan, inplace=True)
test.replace(' ?', np.nan, inplace=True)
print(train.isnull().sum())
# In[4]:
print(test.isnull().sum())
# Feature Engineering
#
# Selecting Income as a Taget Value.
# Converting >50K as 1 and <=50 by 0.
# In[5]:
train['Income'] = train['Income'].apply(lambda x: 1 if x==' >50K' else 0)
test['Income'] = test['Income'].apply(lambda x: 0 if x==' >50K' else 0)
# Filling Not Applicable Values by 0 in Workclass column and printing the head of train data.
# In[6]:
train['Workclass'].fillna(' 0', inplace=True)
test['Workclass'].fillna(' 0', inplace=True)
print(train.head(20))
# Plotting the Features with Target Value Using catplot as Barchart.
# Plotting Workclass feature column with Target value that is Income.
# In[7]:
sns.catplot(x='Workclass', y='Income', data=train, kind='bar', height=6)
plt.xticks(rotation=45);
plt.show()
# Counting Values in Workclass Column
# In[8]:
train['Workclass'].value_counts()
test['Workclass'].value_counts()
# As we can see in above Never-worked and Without-pay are indicating single purpose
# Merge without-pay and Never-worked.
# In[9]:
train['Workclass'].replace(' Without-pay', 'Never-worked', inplace=True)
test['Workclass'].replace(' Without-pay', 'Never-worked', inplace=True)
# Describing the fnlgwt column
# In[10]:
train['fnlgwt'].describe()
# As we can see above that fnlght column has high mean and standard deviation. so we are applying logarithm for reducing mean and standard deviation.
# In[11]:
train['fnlgwt'] = train['fnlgwt'].apply(lambda x: np.log1p(x))
test['fnlgwt'] = test['fnlgwt'].apply(lambda x: np.log1p(x))
print(train['fnlgwt'].describe())
# Plotting Education column with Target Value Income
# In[12]:
sns.catplot(x='Education', y='Income', data=train, kind='bar', height=7)
plt.xticks(rotation=60)
plt.show()
# There are too many categories are available so we are combining some of categories in single category as primary.
# In[13]:
def primary(x):
if x in ['1st-4th', '5th-6th', '7th-8th', '9th', '10th', '11th', '12th']:
return 'Primary'
else:
return x
train['Education'] = train['Education'].apply(primary)
test['Education'] = test['Education'].apply(primary)
# Re plotting the Eduction, Income chart after above changes.
# In[14]:
sns.catplot(x='Education', y='Income', data=train, height=6, kind='bar')
plt.xticks(rotation=60)
plt.show()
# Plotting Marital Status columns with Target Column Income.
# In[15]:
sns.catplot(x='Marital Status', y='Income', height=5, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# Counting all Categories in Marital Status.
# In[16]:
train['Marital Status'].value_counts()
# Merging Married-AF-spouse category into Married-civ-spouse.
# In[17]:
train['Marital Status'].replace('Married-AF-spouse', 'Married-civ-spouse', inplace=True)
test['Marital Status'].replace('Married-AF-spouse', 'Marries-civ-spouse', inplace=True)
# Replotting After Merging
# In[18]:
sns.catplot(x='Marital Status', y='Income', height=5, kind='bar', data=train, palette='muted')
plt.xticks(rotation=60)
plt.show()
# Filling NA values by 0 in Occupation column.
# In[19]:
train['Occupation'].fillna(' 0', inplace=True)
test['Occupation'].fillna(' 0', inplace=True)
# plotting Occupation Feature column with Target Value Income
# In[20]:
sns.catplot(x='Occupation', y='Income', height=8, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# Counting Categories Values of Occupation column
# In[21]:
train['Occupation'].value_counts()
# As we can see above Armed-Forces has only 9 values so it cannot needed so we are removing that by merging it values with 0.
# and also re-plotting.
# In[22]:
train['Occupation'].replace(' Armed-Forces', ' 0', inplace=True)
test['Occupation'].replace(' Armed-Forces', ' 0', inplace=True)
sns.catplot(x='Occupation', y='Income', height=8, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# Plotting Relationship feature column with Target Value Income.
# In[23]:
sns.catplot(x='Relationship', y='Income', height=6, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# In[24]:
train['Relationship'].value_counts()
# Plotting Race column with Income
# In[25]:
sns.catplot(x='Race', y='Income', height=8, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# In[26]:
train['Race'].value_counts()
# Plotting Sex Column
# In[27]:
sns.catplot(x='Sex', y='Income', height=8, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# Filling NA values in Native Country by 0
# In[28]:
train['Native country'].fillna(' 0', inplace=True)
test['Native country'].fillna(' 0', inplace=True)
# Plotting Native Country by Target Value Income
# In[29]:
sns.catplot(x='Native country', y='Income', height=10, kind='bar', data=train)
plt.xticks(rotation=80)
plt.show()
# As we can see above that Native Country Column has to many countries are there, for reducing the countries we are dividing all countries into regions as shown below and replotting Native Country column.
# In[30]:
def native(country):
if country in [' United-States', ' Cuba', ' 0']:
return 'US'
elif country in [' England', ' Germany', ' Canada', ' Italy', ' France', ' Greece', ' Philippines']:
return 'Western'
elif country in [' Mexico', ' Puerto-Rico', ' Honduras', ' Jamaica', ' Columbia', ' Laos', ' Portugal', ' Haiti',
' Dominican-Republic', ' El-Salvador', ' Guatemala', ' Peru',
' Trinadad&Tobago', ' Outlying-US(Guam-USVI-etc)', ' Nicaragua', ' Vietnam',
' Holand-Netherlands']:
return 'Poor' # no offence
elif country in [' India', ' Iran', ' Cambodia', ' Taiwan', ' Japan', ' Yugoslavia', ' China', ' Hong']:
return 'Eastern'
elif country in [' South', ' Poland', ' Ireland', ' Hungary', ' Scotland', ' Thailand', ' Ecuador']:
return 'Poland team'
else:
return country
train['Native country'] = train['Native country'].apply(native)
test['Native country'] = test['Native country'].apply(native)
sns.catplot(x='Native country', y='Income', height=5, kind='bar', data=train)
plt.xticks(rotation=60)
plt.show()
# Joint Both train and test dataset
# In[31]:
joint = pd.concat([train,test], axis=0)
joint.dtypes
# Selecting only object columns from dataset
# In[32]:
categorical_features = joint.select_dtypes(include=['object']).axes[1]
for col in categorical_features:
print (col, joint[col].nunique())
# Splitting all Categories of every columns as a single column and splitting by :
# In[33]:
for col in categorical_features:
joint = pd.concat([joint, pd.get_dummies(joint[col], prefix=col, prefix_sep=':')], axis=1)
joint.drop(col, axis=1, inplace=True)
joint.head()
# Taking Train and Test data
# Xtrain are all feature columns
# Ytrain is Target Value
# same ofr test data
# In[34]:
train = joint.head(train.shape[0])
test = joint.tail(test.shape[0])
Xtrain = train.drop('Income', axis=1)
Ytrain = train['Income']
Xtest = test.drop('Income', axis=1)
Ytest = test['Income']
# Creating Logistic Regression from scratch
# defining funtions:
# Hypothesis using Sigmoid function
# Calculating Loss function
# Fit
# Predict
# In[42]:
class LogisticRegression:
def __init__(self, lr=0.01, num_iter=1000, fit_intercept=True, verbose=False):
self.lr = lr
self.num_iter = num_iter
self.fit_intercept = fit_intercept
def __add_intercept(self, X):
intercept = np.ones((X.shape[0], 1))
return np.concatenate((intercept, X), axis=1)
#Hypothesis
def __sigmoid(self, z):
return 1/(1 + np.exp(-z))
#Loss Function
def __loss(self, h, y):
return (-y * np.log(h) - (1-y) * np.log(1-h)).mean()
#fitting values
def fit(self, X, y):
if self.fit_intercept:
X = self.__add_intercept(X)
self.theta = np.zeros(X.shape[1])
for i in range(self.num_iter):
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
gradient = np.dot(X.T, (h-y)) / y.size
self.theta -= self.lr * gradient
#Probability of prediction
def predict_prob(self, X):
if self.fit_intercept:
X = self.__add_intercept(X)
return self.__sigmoid(np.dot(X, self.theta))
#predicting the value
def predict(self, X, threshold=0.5):
return self.predict_prob(X) >= threshold
# After this we can use Logistic Regression as we were using in Sklearn lib
# 1. fitting values in model
# 2. predicting the values
# 3. Final Accuracy
# In[46]:
model = LogisticRegression()
model.fit(Xtrain, Ytrain)
Ztrain = model.predict(Xtrain)
Ztest = model.predict(Xtest)
# In[47]:
print('Accuracy of the Logistic Regression Model', (Ztrain == Ytrain).mean())
|
38e5aa511311ea150047a0e340c6c7ef5a3ca8a4 | wputra/learning-python | /some-scripts/max-toys.py | 387 | 3.5 | 4 | #!/usr/bin/python3
def maximumToys(prices, k):
s = 0
for i in prices:
if i<=k:
s+=1
k-=i
#else:
# break
return s
in1 = "7 50"
in2 = "1 12 5 111 200 1000 10"
n,k = map(int, in1.split())
#prices = sorted(map(int,input().split()))
prices = map(int, in2.split())
print(maximumToys(prices, k))
#print(int(k))
#print(in_list)
|
468feb84967473cab07c92df93c29d6226314b2a | saytosid/dodgem-playing-framework | /framework/Board.py | 6,192 | 3.9375 | 4 | '''
File name: Board.py
Author: Siddhant Kumar
Email: saytosid@gmail.com
Date created: 1 Oct 2017
Date last modified: 1 Oct 2017
Python Version: 3.0
'''
from Piece import Piece
class Board:
def __init__(self,size = 3):
'''
:param size: Defines the size of the board
'''
self.size = size
self.turn = 1 # Player 1 goes first
self.player_1_pieces = list()
for i in xrange(size):
if i != size-1:
self.player_1_pieces.append(Piece(color='black',position=(i,0)))
self.player_2_pieces = list()
for i in xrange(size):
if i != 0:
self.player_2_pieces.append(Piece(color='white',position=(size-1,i)))
def get_board_config(self):
'''
:return: tupple (board_configuration,turn)
'''
import numpy as np
board_matrix = np.zeros((self.size,self.size))
for piece in self.player_1_pieces:
if piece.dead == False:
board_matrix[piece.pos[0],piece.pos[1]] = 1
for piece in self.player_2_pieces:
if piece.dead == False:
board_matrix[piece.pos[0],piece.pos[1]] = 2
return (board_matrix, self.turn)
def make_move(self,(piece,new_pos,extra_info)):
'''
:return: ('lost',player_who_lost) or ('game continues',None)
'''
print('Player_'+str(self.turn)+' played: '+str(piece.pos)+'->'+str(new_pos))
if (piece,new_pos,extra_info) not in self.get_valid_moves():
print("Invalid Move, You Lose")
return ('lost',self.turn)
if self.turn == 1:
for p in self.player_1_pieces:
if p==piece:
p.pos = new_pos
if extra_info==True:
p.dead = True
pieces_left = [item for item in self.player_1_pieces if item.dead == False]
if len(pieces_left)==0:
return ('lost',2)
self.turn = 2
elif self.turn == 2:
for p in self.player_2_pieces:
if p==piece:
p.pos = new_pos
if extra_info==True:
p.dead = True
pieces_left = [item for item in self.player_2_pieces if item.dead == False]
if len(pieces_left)==0:
return ('lost',1)
self.turn = 1
if len(self.get_valid_moves()) == 0:
# Other oppoment is blocked by this move
print('Blocked other player, You Lose')
if self.turn == 1:
return ('lost', 2)
elif self.turn == 2:
return ('lost', 1)
# If normal play continues
return ('game continues', None)
def get_valid_moves(self):
'''
list of valid moves. Does not check if a move blocks other player. You must check it yourself
:return: list( (piece,new_position,BoardLeavingMove) )
'''
board_matrix,turn = self.get_board_config()
valid_moves = [] # A move is a tupple of the form (Piece,(new_position_tuple),piece_will_leave_board)
if self.turn == 1:
for piece in self.player_1_pieces:
pos = piece.pos
if piece.dead == False:
forward_move = (pos[0],pos[1]+1) # towards right for player_1
if forward_move[1] < self.size:
if board_matrix[forward_move] == 0:
# if new position is unoccupied and piece doesnt jump off the board
valid_moves.append((piece,forward_move,False))
elif forward_move[1] == self.size:
# Piece can leave the board
valid_moves.append((piece,forward_move,True))
sideways_left = (pos[0]-1,pos[1])
if sideways_left[0] != -1:
if board_matrix[sideways_left] == 0 and sideways_left != (self.size-1,0):
# Piece doesnt go to bottom left corner, doesnt leave board and moves on empty block
valid_moves.append((piece,sideways_left,False))
sideways_right = (pos[0]+1,pos[1])
if sideways_right[0] != self.size:
if sideways_right != (self.size-1,0) and board_matrix[sideways_right] == 0:
# Piece doesnt go to bottom, doesnt leave board left corner and moves on empty block
valid_moves.append((piece,sideways_right,False))
elif self.turn == 2:
for piece in self.player_2_pieces:
pos = piece.pos
if piece.dead == False:
forward_move = (pos[0]-1,pos[1]) # towards up for player_2
if forward_move[0] != -1:
if board_matrix[forward_move] == 0:
# if new position is unoccupied and piece doesnt jump off the board
valid_moves.append((piece,forward_move,False))
elif forward_move[0] == -1:
# Piece can leave the board
valid_moves.append((piece,forward_move,True))
sideways_left = (pos[0],pos[1]-1)
if sideways_left[1] != -1:
if board_matrix[sideways_left] == 0 and sideways_left != (self.size-1,0):
# Piece doesnt go to bottom left corner, doesnt leave board and moves on empty block
valid_moves.append((piece,sideways_left,False))
sideways_right = (pos[0],pos[1]+1)
if sideways_right[1] != self.size:
if sideways_right != (self.size-1,0) and board_matrix[sideways_right] == 0:
# Piece doesnt go to bottom, doesnt leave board left corner and moves on empty block
valid_moves.append((piece,sideways_right,False))
return valid_moves
|
31f01f01b4e5abec5c6bb6e42ec704047b78d42e | DLaMott/Calculator | /com/Hi/__init__.py | 826 | 4.125 | 4 |
def main():
print('Hello and welcome to my simple calculator.')
print('This is will display different numerical data as a test.')
value = float(input("Please enter a number: "))
value2 = float(input("Please enter a second number: "))
print('These are your two numbers added together: ', (float(value)) + (float(value2)))
print('These are your two numbers subtracted: ', (float(value) - (float(value2))))
print('These are your two numbers multiplied: ', (float(value) * (float(value2))))
print('These are your two numbers divided: ', (float(value)) / (float(value2)))
restart = input("Do you want to restart? [y/n] >")
if restart== 'y':
main()
else:
print('Thank you, Goodbye.')
exit
main()
|
46883d94f62e9078f0593150db583fd96fbff475 | onkelhoy/Machine-Learning | /Recurrent Neural Network/wildml turorial/preprocessing.py | 2,185 | 3.609375 | 4 | import nltk
import csv
import itertools
import numpy as np
unknown_token = "UNKNOWN_TOKEN"
sentence_start_token = "SENTENCE_START"
sentence_end_token = "SENTENCE_END"
def preprocess_data(vocabulary_size):
print("Reading the CSV file...")
with open('data/reddit-comments-2015-08.csv', 'rt') as f:
reader = csv.reader(f, skipinitialspace=True)
next(reader)
# split full comments into sentences
sentences = itertools.chain(*[nltk.sent_tokenize(x[0].lower()) for x in reader])
# append START end END
sentences = ["%s %s %s" % (sentence_start_token, s, sentence_end_token) for s in sentences]
print("Parsed %d sentences." % (len(sentences)))
# Tokenize the sentences into words
tokenized_sentences = [nltk.word_tokenize(sent) for sent in sentences]
# Count the word frequencies
word_freq = nltk.FreqDist(itertools.chain(*tokenized_sentences))
print("Found %d unique words tokens." % len(word_freq.items()))
# Get the most common words and build index_to_word and word_to_index vectors
vocab = word_freq.most_common(vocabulary_size - 1)
index_to_word = [x[0] for x in vocab]
index_to_word.append(unknown_token)
# index_to_word.append(sentence_start_token)
# index_to_word.append(sentence_end_token)
word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])
print('Using vocabulary size %d.' % vocabulary_size)
print('The least frequent word in our vocabulary is "%s" and it appeared %d times.' % (vocab[-1][0], vocab[-1][1]))
# Replace all words not in our vocabulary with the unknown token
for i, sent in enumerate(tokenized_sentences):
tokenized_sentences[i] = [w if w in word_to_index else unknown_token for w in sent]
print('\nExample Sentence: "%s"' % sentences[0])
print('Example Sentence after pre-processing: "%s"' % tokenized_sentences[0])
# Creating the training data
X_train = np.asarray([[word_to_index[w] for w in sent[:-1]] for sent in tokenized_sentences])
Y_train = np.asarray([[word_to_index[w] for w in sent[1:]] for sent in tokenized_sentences])
return X_train, Y_train, word_to_index, index_to_word |
9036f29d1db991ab061a6b27045bbc7b5f6ad50b | GunterBravo/Python_Institute | /2_1_4_9_Lab_Variables.py | 610 | 3.828125 | 4 | #Escenario
#Millas y kilómetros son unidades de longitud o distancia.
#Teniendo en mente que 1 equivale aproximadamente a 1.61 kilómetros, complemente el programa en el editor para que convierta de:
#Millas a kilómetros.
#Kilómetros a millas.
kilometros = float(input("Ingresa longitud en Kilometros: "))
millas = float(input("Ingresa longitud en Kilometros: "))
millas_a_kilometros = millas * 1.61
kilometros_a_millas = kilometros / 1.61
print(millas, " millas son ", round(millas_a_kilometros, 2), " kilómetros ")
print(kilometros, " kilómetros son ", round(kilometros_a_millas, 2), " millas ")
|
acf4f9abb3deab9bf3752aae70ac76537f66b92f | GunterBravo/Python_Institute | /2_1_4_10_Lab_Operadores.py | 914 | 4.125 | 4 | ''' Escenario
Observa el código en el editor: lee un valor flotante, lo coloca en una variable llamada x, e imprime el valor de la variable llamada y. Tu tarea es completar el código para evaluar la siguiente expresión:
3x3 - 2x2 + 3x - 1
El resultado debe ser asignado a y.
Recuerda que la notación algebraica clásica muy seguido omite el operador de multiplicación, aquí se debe de incluir de manera explicita. Nota como se cambia el tipo de dato para asegurarnos de que x es del tipo flotante.
Mantén tu código limpio y legible, y pruébalo utilizando los datos que han sido proporcionados. No te desanimes por no lograrlo en el primer intento. Se persistente y curioso.'''
print("Se resuelve la expresión algebraica")
print("3x-exp3 - 2x-exp2 + 3x - 1")
print("El resultado se va asignar a y")
x = float(input("Ingresa un valor para x: "))
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print("y = ", y)
|
e48382f4282df95b1f268af7648eec1c885cef18 | viticlick/PythonProjectEuler | /archive1.py | 331 | 4.3125 | 4 | #!/usr/bin/python
"""If we list all the natural numbers below 10 that are multiples of 3 or 5 \
we get 3, 5, 6 and 9. The sumof these multiples is 23.\
\
Find the sum of all the multiples of 3 or 5 below 1000."""
values = [ x for x in range(1,1001) if x % 3 == 0 or x % 5 == 0]
total = sum(values)
print "The result is", total
|
78e3f14e195e78ef32ffd9cfdcf4aa8ba5f3c3ca | rzv09/web-scrape | /graphics.py | 824 | 3.75 | 4 | """
this file produces graphics for data from vehicle_info.csv
also this thing doesn't work
!SLICE PRICES AND CAST TO AN INT INSTEAD OF STR!
author: Raman Zatsarenko
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data_csv = pd.read_csv('vehicle_info.csv')
print(data_csv.info())
def plot_linear(data):
"""
i don't know what happened here please for the love of god don't run it
:param data:
:return:
"""
x = data[" Year"]
y = data[" Price"]
plt.scatter(y, x, marker="o", color='r')
plt.show()
def plot_sns(data):
cars = sns.load_dataset(data)
#sns.scatterplot(x=" Year", y=" Price", data=cars)
def main():
plot_linear(data_csv)
# plot_sns(data_csv)
if __name__ == '__main__':
main()
# pass
#print(data_csv[" Year"]) |
5dc1970499b8dbaad825b147c9ac1c8e2a81bcd2 | Dmendoza3/Python-exercises | /random/collectionGame.py | 972 | 3.609375 | 4 | import random
rarities = ['common', 'uncommon', 'rare', '']
collection = {}
collectionRate = {}
collected = []
def generateCollection(num, nRarities=3, rate=0.75):
cardsLeft = num
for r in range(nRarities):
if r < nRarities - 1:
nPerRarity = int(cardsLeft * rate)
else:
nPerRarity = cardsLeft
collection[(nPerRarity)] = []
for n in range(nPerRarity):
collection[nPerRarity].append('name' + str(nPerRarity) + str(random.randint(100, 999)))
cardsLeft -= nPerRarity
prevN = 0
for x in collection:
collectionRate[(prevN + 1, prevN + x)] = x
prevN += x
def getCard():
rand = random.randint(1, 100)
for x in collectionRate:
if rand in range(x[0], x[1]):
print(collectionRate[x])
return random.choice(collection[collectionRate[x]])
generateCollection(100)
print(collection)
for x in range(10):
print(getCard())
|
13ce56ad5b2ec62b12a13d86df9fb61410f67007 | Dmendoza3/Python-exercises | /basic/for.py | 1,012 | 3.921875 | 4 | #For loop
words = ['cat', 'window', 'defenestrate']
arrtp = [('a',1),('b',2),('c',3)]
for w in words:
print(w, len(w))
#Allows to modify list not affecting the loop
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
#Loop with numbers
for i in range(5,15):
print(i)
#Loop with range, len
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
#List range
print(list(range(5)))
#Breaks
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else: #Else of a loop executes at end of range not after a break
# loop fell through without finding a factor
print(n, 'is a prime number')
#Continues
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
for i, x in enumerate(words):
print(x)
for x,y in arrtp:
print(y)
|
ec2c40ac1acbc9375d4c92228a6d8ccd17e982c5 | Dmendoza3/Python-exercises | /random/infinite_monkey.py | 682 | 4.09375 | 4 | from PyDictionary import PyDictionary
import random
def generate_word():
letter = "abcdefghijklmnopqrstuvwxyz"
wlen = random.randint(4, 9)
word = ""
for x in range(wlen):
wselect = random.randint(0, len(letter) - 1)
word += letter[wselect]
return word
dictionary=PyDictionary()
correctWord = None
numberWords = 3
listWords = []
for x in range(3):
while not correctWord:
testWord = generate_word()
if dictionary.meaning(testWord):
correctWord = testWord
listWords.append(correctWord)
correctWord = None
print("generated words: ", listWords)
#print("meaning: ", dictionary.meaning(correctWord)) |
bdf720357d2aa437046614207848241b2c358360 | YazdanGeshani/POO | /POO.py | 541 | 3.734375 | 4 | """cette classe permis de definir l'objet(c'est a dire nous allons donner des
attributs a un objet pour le definir)"""
class Pet:
def __init__(self, name, greeting = "Hello"):
self.name = name
self.greeting = greeting
"""ici on définit l'action dont va faire cet objet"""
def say_hi(self):
print(f"{self.greeting}, I'm {self.name}!")
"""ici on fait un objet(chat) grace a la class pet deja créér"""
class Cat(Pet):
def __init__(self, name):
super().__init__(name, "Meow")
my_pet = Pet("Gaston")
my_pet.say_hi() |
aa17589a9b237b787437941eb9adc05c3c3facc8 | oddduckden/lesson8 | /task2.py | 1,053 | 4.09375 | 4 | """
2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных,
вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту
ситуацию и не завершиться с ошибкой.
"""
class CustomErr(Exception):
def __init__(self, txt):
self.txt = txt
def num(expr):
expr.replace(' ', '')
return expr.split('/')
entr = input('Введите выражение деления: ')
try:
n = num(entr)
try:
res = float(n[0]) / float(n[1])
except ZeroDivisionError:
raise CustomErr('Деление на ноль недопустимо')
except ValueError:
print("Вы ввели не число")
except CustomErr as err:
print(err)
else:
print(f'{entr} = {res}')
|
2ee0d6cb2127b0e61d1331be60dc34a8a42611e7 | raissaputra/praktikum2 | /lab1.py | 960 | 3.796875 | 4 | # penggunaan end
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('Y')
print('Z')
# PENGGUNAAN SEPARATOR
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
# string format
print(0, 10**0)
print(1, 10**1)
print(2, 10**2)
print(3, 10**3)
print(4, 10**4)
print(5, 10**5)
print(6, 10**6)
print(7, 10**7)
print(8, 10**8)
print(9, 10**9)
print(10, 10**10)
# string format
print('{0:>3} {1:>16}'.format(0, 10**0))
print('{0:>3} {1:>16}'.format(0, 10**1))
print('{0:>3} {1:>16}'.format(0, 10**2))
print('{0:>3} {1:>16}'.format(0, 10**3))
print('{0:>3} {1:>16}'.format(0, 10**4))
print('{0:>3} {1:>16}'.format(0, 10**5))
print('{0:>3} {1:>16}'.format(0, 10**6))
print('{0:>3} {1:>16}'.format(0, 10**7))
print('{0:>3} {1:>16}'.format(0, 10**8))
print('{0:>3} {1:>16}'.format(0, 10**9))
print('{0:>3} {1:>16}'.format(0, 10**10))
|
4129d04e0e2e69416363192f30ab46bdc4437377 | DanTGL/AdventOfCode2020 | /day6/day6_1.py | 269 | 3.546875 | 4 | import string
inputs = [line.strip() for line in open("day6/input").read().split("\n\n")]
def count():
count = 0
for group in inputs:
count += len(list(filter(lambda x: x in group, string.ascii_lowercase)))
return count
print(count()) |
14ba91c2a426ed9c533e1b4854caecf0c853e4c6 | rnvarma/KosbieSays | /KosbieSays/doittt.py | 845 | 3.59375 | 4 | import string, bisect, random
def get_start():
x = random.random()
idx = bisect.bisect(start_vals, x)
result = start_words[idx]
if result == "**s** **s**":
return get_start()
return result
def get_next_word(gram):
if gram not in nexts:
print "----", gram
return "**s**"
(vals, words) = nexts[gram]
x = random.random()
idx = bisect.bisect(vals, x)
return words[idx]
result = ""
gram = get_start()
first_word = gram.split()[1]
first_word = first_word[0].upper() + first_word[1:]
result = first_word
next_word = ""
while True:
try:
w1, w2 = gram.split()
except:
print "sasdddd", gram
break
w3 = get_next_word(gram)
if w3 == "**s**":
result += "."
break
result += " " + w3
gram = "%s %s" % (w2, w3)
print result
|
3ba74634dd2ccbe7b9ff8e2545198a039c43fd5e | Salekya/pythonScripts | /String.py | 161 | 3.75 | 4 | def string(s,n):
j=len(s)
for i in range(0,j):
e=s[i:i+n]
if len(e)==n:
print(e)
return e
e=string("hello",3)
print(e)
|
3a0d7e9cf63863fbad8ba4bc395a4cc87d1e2c82 | lotario123/seguridadTI | /cifradorAm.py | 1,053 | 4.03125 | 4 | import sys
import cifrar
import descifrar
#palabra: corresponde a un texto a cifrar o descifrar
#modo: para cifrar utilizar la palabra "cifrar" y para descifrar "descifrar"
def main(palabra,modo):
#eliminar espacios en blanco
#palabraFormateada =palabra.replace(" ", "").upper()
palabraFormateada = palabra.upper().strip()
modoOperar = modo.upper()
#diccionario con el alfabeto español
alfabeto={"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,
"K":10,"L":11,"M":12,"N":13,"Ñ":14,"O":15,"P":16,"Q":17,"R":18,
"S":19,"T":20,"U":21,"V":22,"W":23,"X":24,"Y":25,"Z":26," ":27,".":28}
modulo=29 # n
#Modo de operacion cifrar o descifrar
if modoOperar == "CIFRAR":
palabraResultado = cifrar.cifrar(alfabeto,palabraFormateada,modulo)
elif modoOperar == "DESCIFRAR":
palabraResultado = descifrar.descifrar(alfabeto,palabraFormateada,modulo)
else:
sys.exit('No existe el modo de operación ingresado')
return palabraResultado |
0454c7ae55f844ffa0289a850ce5020e6f02f08d | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/pascales_triangle.py | 474 | 3.9375 | 4 | n = int(input("Enter the number of rows:"))
list1 = []
for i in range(n):
temp_list = []
for j in range(i + 1):
if j == 0 or j == i:
temp_list.append(1)
else:
temp_list.append(list1[i-1][j-1] + list1[i-1][j])
list1.append(temp_list)
for i in range(n):
for j in range(n-i-1):
print(format(" ", "<2"), end="")
for k in range(i+1):
print(format(list1[i][k], "<3"), end=" ")
print() |
5395b82d4e6cc5bc911098ce23763f5e6d7d0ddd | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/RightTriangle.py | 157 | 3.796875 | 4 | number = int(input("Enter the number of rows:"))
for i in range(0, number):
for j in range(0, i + 1):
print('* ', end=' ')
print("\r")
|
0bb9b40d8a9fbcd501c74823163c2daf0ea9fcef | Abdurrahmans/Star-Pattern-Problem-Solving | /StarPattern/Another reverse number pattern.py | 178 | 4.15625 | 4 | number = int(input("Enter the positive number: "))
for i in range(number, 0, -1):
for j in range(1, i + 1):
print(i, end=" ")
i = i - 1
print(" ")
|
d1591a9c8713b2f55fb70f8b2c6f3126b5384aad | Juan319-u/Parcial-5 | /punto88renovado.py | 1,533 | 3.671875 | 4 | '''Este codigo verifica que la expresion 6 dividido pi al cuadrado
es igual a casos favorables sobre casos posibles de los numeros enteros libres de cuadrados
Autor : Juan Felipe Corrales Toro
ULTIMA ACTUALIZACION : 13 de Octubre / 2021'''
#está función toma de entrada un entero positivo mayor que 1 y muestra los factores primos de él, su salida es un vector.
def descomponer_factores(n):
factor_primo = 2
factores = []
while n>1:
if n % factor_primo == 0:
n //= factor_primo #función actualiza el n, con la parte entera (menor entero) de n al dividir por el factor primo
factores.append(factor_primo)
else:
factor_primo += 1
return factores #devuelve el vector de factores primos con repeticiones
def frecuencia(lista):
f = []
unique_list = list(set(lista)) #se queda sólo con los valores son repetición
for i in unique_list:
f.append(lista.count(i))
return len(f)
# calcula la cantidad de enteros libres de cuadrados hasta un n y su probabilidad
def libre_cuadrados(n):
c = 0
for z in range(2,n+1,1):
lista_factores = descomponer_factores(z)
if len(lista_factores) == frecuencia(lista_factores):
c=c+1
else:
continue
print('Cantidad de enteros libres:', c)
print('P(z libre)=', c/n)
for n in range(2,500,1):
print(libre_cuadrados(n))
|
58e3199b3aa27ff16249d45c0ea1f331a701b24f | pavancd/algorithms | /BranchSums/BranchSums.py | 907 | 3.71875 | 4 |
class BinaryTree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add(self, value):
pass
def BranchSums(root):
sums = []
calculateBranchSum(root, sums, 0)
return sums
def calculateBranchSum(root, sums, runningSum):
if root is None:
return
newRunningSum = runningSum + root.value
if root.left == None and root.right == None:
sums.append(newRunningSum)
return
calculateBranchSum(root.left, sums, newRunningSum)
calculateBranchSum(root.right, sums, newRunningSum)
def test():
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = BinaryTree(3)
root.left.left = BinaryTree(4)
root.left.right = BinaryTree(5)
root.right.left = BinaryTree(6)
root.right.right = BinaryTree(7)
sums = BranchSums(root)
print(sums)
test() |
029698592fbd477a8433b08c37925d9f5846e51f | pavancd/algorithms | /MaxPathSum/MaxPathSum.py | 1,190 | 3.65625 | 4 |
class BinaryTree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add(self, value):
pass
def maxPathSum(root):
_, maxPathSum = findMaxPathSum(root)
return maxPathSum
def findMaxPathSum(root):
if root is None:
return (0, 0)
maxLeftSumAsBranch, maxLeftPathSum = findMaxPathSum(root.left)
maxRightSumAsBranch, maxRightPathSum = findMaxPathSum(root.right)
maxChildSumAsBranch = max(maxLeftSumAsBranch, maxRightSumAsBranch)
value = root.value
maxSumAsBranch = max(maxChildSumAsBranch + value, value)
maxSumAsTriangle = max(
maxSumAsBranch, maxLeftSumAsBranch + value + maxRightSumAsBranch)
maxPathSum = max(maxSumAsTriangle, maxLeftPathSum, maxRightPathSum)
return (maxSumAsBranch, maxSumAsTriangle)
root = None
def test():
global root
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = BinaryTree(3)
root.left.left = BinaryTree(4)
root.left.right = BinaryTree(5)
root.right.left = BinaryTree(10)
root.right.right = BinaryTree(8)
if __name__ == '__main__':
test()
print(maxPathSum(root))
|
ed23e96ea643c57812dd309759a9f13b4f3c0833 | pavancd/algorithms | /BSTComparision/BSTComparision.py | 744 | 3.75 | 4 |
def compareBST(arr1, arr2):
print(f'arr1 {arr1}')
print(f'arr2 {arr2}')
if len(arr1) == 0 and len(arr2) == 0:
return True
if not arr1[0] == arr2[0]:
return False
if len(arr1) != len(arr2):
return False
root1 = arr1[0]
root2 = arr1[0]
arr1 = arr1[1:]
arr2 = arr2[1:]
arr1LeftSubTree = [a for a in arr1 if a < root1]
arr2LeftSubTree = [a for a in arr2 if a < root2]
arr1RightSubTree = [a for a in arr1 if a >= root1]
arr2RightSubTree = [a for a in arr2 if a >= root2]
return compareBST(arr1LeftSubTree, arr2LeftSubTree) and compareBST(arr1RightSubTree, arr2RightSubTree)
print(compareBST([10,15,8,12,94,81,5,2,11], [10,8,5,15,2,12,11,94,81])) |
487cc4e6bcbe699a56e2c448cd2d0ad969b75579 | TYakovchenko/GB_Less3 | /less3_HW3.py | 1,196 | 4.25 | 4 | ##3. Реализовать функцию my_func(),
# которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
#Первый вариант
def my_func(arg1, arg2, arg3):
if arg1 >= arg3 and arg2 >= arg3:
return arg1 + arg2
elif arg1 > arg2 and arg1 < arg3:
return arg1 + arg3
else:
return arg2 + arg3
print("Первый вариант реализации:")
arg1 = int(input("Первое значение: "))
arg2 = int(input("Второе значение: "))
arg3 = int(input("Третье значение: "))
print(my_func(arg1, arg2, arg3))
##Второй вариант
def my_func2(arg4, arg5, arg6):
range_1 = [arg4, arg5, arg6]
total = []
max_1 = max(range_1)
total.append(max_1)
range_1.remove(max_1)
max_2 = max(range_1)
total.append(max_2)
print(sum(total))
print("Второй вариант реализации:")
my_func2(arg4 = int(input("Первое значение: ")), arg5 = int(input("Второе значение: ")),arg6 = int(input("Третье значение: ")))
|
23e58c21870d678c8243a3056bc30d3e73d3fa91 | PedroMorenoTec/practica-examen | /3.2/indicedemasacorporal.py | 359 | 3.9375 | 4 | peso = float(input('Peso en kg: '))
altura = float(input('Altura en m: '))
indice = round(peso / altura**2,2)
print(indice)
if indice < 20:
print('PESO BAJO')
if 20 <= indice < 25:
print('NORMAL')
if 25 <= indice < 30:
print('SOBREPESO')
if 30 <= indice < 40:
print('OBESIDAD')
if indice >= 40:
print('OBESIDAD MORBIDA') |
b128924af1b216185223f1f45d535dba6094d801 | PedroMorenoTec/practica-examen | /5.4/ejercicio1.py | 204 | 3.984375 | 4 | n = int(input('Introduce un entero positivo: '))
msg=''
for i in range(1, n+1):
msg+=str(i) + ', '
for i in range(n-1, 0, -1):
msg+=str(i) + ', '
msg = msg[:-2]
print(msg) |
f8c1e5afb9c3151430c34866c55527411ee53714 | PedroMorenoTec/practica-examen | /3.1/ejercicio2.py | 417 | 4.03125 | 4 | print('Introduzca los lados del triángulo')
x = float(input('x: '))
y = float(input('y: '))
z = float(input('z: '))
if(x+y>z and x+z>y and y+z>x and x>0 and y>0 and z>0):
if(x != y != z):
print('El tríangulo es escaleno')
elif(x == y == z):
print('El tríangulo es equilátero')
else:
print('El tríangulo es isóceles')
else:
print('El triángulo no existe')
|
3307942491d669cc0ab88ac90a6969f4dd1a5757 | PedroMorenoTec/practica-examen | /2.2/decentimetrosakilometrosmetrosycentimetros.py | 273 | 4 | 4 | distancia = int(input('Introduzca una distancia: '))
km = distancia // (1*10**5)
distancia%=(1*10**5)
m = distancia // (1*10**2)
distancia%=(1*10**2)
cm = distancia
if km>0:
print(f'{km} km')
if m>0:
print(f'{m} m')
if cm>0:
print(f'{cm} cm') |
f448ff8716de10531614e960426e84e51d76107f | simon-suuk/Analizar | /services/graph_api.py | 2,649 | 3.53125 | 4 | import requests
class PageOrPost:
def __init__(self, page_id, page_token):
self.node_id = page_id
self.access_token = page_token
def get_edge(self, edge_name):
"""
To read an edge, you must include both the node ID and the edge name in the path.
For example, /page nodes have a /feed edge which
can return all Post nodes on a Page
:param edge_name:
"""
base_url = "https://graph.facebook.com"
version = "v2.12"
url = "{base_url}/{version}/{node_id}/{edge_name}?access_token={access_token}".format(
base_url=base_url,
version=version,
node_id=self.node_id,
edge_name=edge_name,
access_token=self.access_token
)
response = requests.get(url)
return response.json()
def get_node_properties(self, *args):
"""
Fields are node properties.
The Page node reference indicates which fields
you can ask for when reading a Page node.
For example, If you wanted to get the about, fan_count, and website fields
:param args:
"""
base_url = "https://graph.facebook.com"
version = "v2.12"
url = "{base_url}/{version}/{node_id}?fields={fields}&access_token={access_token}".format(
base_url=base_url,
version=version,
node_id=self.node_id,
fields="%2C".join([arg for arg in args]),
access_token=self.access_token
)
response = requests.get(url)
# print("type: {}".format(type(response.json())))
return response.json()
def get_node_edge_properties(self, metric):
"""
Fields are node properties.
The Page node reference indicates which fields
you can ask for when reading a Page node.
For example, If you wanted to get the about, fan_count, and website fields
:param metric:
:param edge_name:
:param args:
"""
# "https://graph.facebook.com/v2.12/1420595431516143_1458058417769844/insights/post_impressions_unique?lifetime&access_token=EAA"
base_url = "https://graph.facebook.com"
version = "v2.12"
url = "{base_url}/{version}/{node_id}/insights/{metric}?lifetime&access_token={access_token}".format(
base_url=base_url,
version=version,
node_id=self.node_id,
metric=metric,
access_token=self.access_token
)
response = requests.get(url)
# print("type: {}".format(type(response.json())))
return response.json()
|
d0137ea42361b0a0ecaee16398bc22cc2d72d1ad | BerdeRadhika/Programs | /Python Programs/Assignment No 1/4.Display 5 times Marvellous on screen.py | 291 | 3.890625 | 4 | """4.Write a program which display 5 times Marvellous on screen.
Output :
Marvellous
Marvellous
Marvellous
Marvellous
Marvellous
"""
def Print():
i=0
for i in range (5):
print("Marvellous")
def main():
Print()
if __name__=="__main__":
main()
|
9740bf10ad88a24ee7691b27b222cff72a733351 | SamBurt/Hearts | /Deck.py | 596 | 3.734375 | 4 | from Card import Card
import random
class Deck:
suits = [
"Heart",
"Diamond",
"Spade",
"Club"
]
values = list(range(2,15))
def __init__(self):
self.cards = self.generate_deck()
def generate_deck(self):
cards = []
for suit in self.suits:
for value in self.values:
cards.append(Card(suit, value))
random.shuffle(cards)
return cards
def print_deck(self):
for card in self.cards:
print(card)
def deal_card(self):
return self.cards.pop()
|
940af334933c2bbe31e8b5d71647c675e10d1f2f | PranjaliKumbhar/CI-Programs | /ciANDNOTMC.py | 1,014 | 3.625 | 4 | print("Enter the ANDNOT Truth Table:")
x1=[]
x2=[]
y=[]
for i in range(0,4):
i1=input("Enter values of X1:")
x1.append(i1)
for i in range(0,4):
i2=input("Enter values of X2:")
x2.append(i2)
for i in range(0,4):
i3=input("Enter values of Y:")
y.append(i3)
print ("X1 X2 Y")
i=0
while i <=len(x1):
print(x1[i]," ",x2[i]," ",y[i])
i=i+1
if(i==len(x1)):
break
print("Assume Both weights are excitory i.e w1=w2=1")
yin=[]
w1=1
w2=1
i=0
while i <=len(x1):
add=int(x1[i]*w1)+int(x2[i]*w2)
print("yin=",x1[i],"*",w1,"+",x2[i],"*",w2,"=",add)
i=i+1
if(i==len(x1)):
break
print ("These weights are not suitable")
print("Assume one weight excitory and other inhibitory i.e w1=1 & w2=-1")
w1=1
w2=-1
i=0
while i <=len(x1):
a=int(x2[i])*int(w2)
add=int(x1[i]*w1)+a
print("yin=",x1[i],"*",w1,"+",x2[i],"*",w2,"=",add)
i=i+1
if(i==len(x1)):
break
print ("These weights are suitable and value of \u03B8=1")
|
ce31f1b2a952762712f668d3ed590b7bdc2e599c | deyh2020/meep-geom-utils | /meep_geom_utils/src/geom2med.py | 1,485 | 3.640625 | 4 | """
:author: JPHaupt
:date: 26 Feb 2020
simple module that contains a function that takes a list of mp.GeometricObject
and Shape and returns a function of mp.Vector3 that returns the medium at that
point
"""
import meep as mp
from meep_geom_utils.src import shapes
def geom2med(geometries, default_material=mp.Medium(epsilon=1.0)):
"""
takes a mixed list of mp.GeometricObject and Shape (defined in this module)
and returns a function of mp.Vector3 that returns the medium at the point
:param geometries: list of geometric objects/shapes
:type geometries: [mp.GeometricObject or Shape]
:default_material: the material to be chosen if point not in any of the
objects. Default is air (epsilon=1.0)
:type default_material: mp.Medium
.. note:: objects at the end of the list are checked first (i.e. if two
objects contain the point, then it is considered to be in the last
one).
"""
return lambda v: _geom2med_helper(geometries, v, default_material)
def _geom2med_helper(geometries, point, default_material):
"""
Function that geom2med wraps around
"""
for geom in reversed(geometries):
if isinstance(geom, mp.GeometricObject):
if mp.is_point_in_object(point, geom):
return geom.material
elif isinstance(geom, shapes.Shape):
if geom.contains(point):
return geom.material
return default_material |
bf799eadced3aa3cb805b49329b912e9378fe9bc | abbsmile/Python-base | /BaseForm/identifyOperator.py | 1,086 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
# a = 20
# b = 200
# if ( a is b ):
# print "1 - a 和 b 有相同的标识"
# else:
# print "1 - a 和 b 没有相同的标识"
# print id(5)
# print id(6)
#
# print 5 is 5
# print 5 is not 5
# print id(5) is id(5)
# print id(5) is not id(5)
## ?? id 是一个有待研究的东西?????
a = [1, 2, 3]
b = [1, 2, 3]
print id(a) # 38967176
print id(b) # 38991392
# 1. 终于a、b两个值是不一样的了
# 2. 每运行一次,id(a), id(b)的值都会改变,说明
# 解释器在对值很小的int和很短的字符串的时候做了一点小优化,只分配了一个对象,让它们id一样了。
# if ( id(a) is not id(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 有相同的标识" |
67a04b62a354f2c0a78aa7d3fb04ad46c33e8d98 | abbsmile/Python-base | /BaseForm/variable.py | 255 | 3.953125 | 4 | # -*- coding: UTF-8 -*-
a, b, c = 1, 2, "john"
print a
print b
print c
print "**************************"
str = "Hello World"
print str
print str[0]
print str[2:5] # 这个要注意一下,肯定在5之前
print str[2:]
print str * 2
print str + " TEST"
|
a6c97190493de239f3691fd80bc798dbd7de5d39 | abbsmile/Python-base | /BaseForm/AddString.py | 1,079 | 3.6875 | 4 | # -*- coding: UTF-8 -*-
first = '上海涌洁'
second = ' 我的第二个公司'
third = first + second
print third
print 5 + 8
print '5' + '8'
print 'let\'t go'
print "let't go"
print 'c:\now'
print 'c:\\now'
# 原始字符串
print '***********************************'
fish = r'c:\now'
# 注意一下,fish = r'c:\now\' 这样是不合法的
print fish
# 多行字符串 它能处理一段东西
hope = """
阳光总在风雨后
可是我总在面对风雨
我不知道未来是什么
我能做的
只有的往前走
"""
print hope
print "###########多行语句#############"
item_one = 5
item_two = 6
item_three = 7
total = item_one + \
item_two + \
item_three
print total
# print "**********等待用户输入**********"
# aNumber = raw_input("请输入一个数字:")
# print aNumber
print "分号可以写在句子中间"
import sys; x = 'runoob'; sys.stdout.write(x + '\n')
print "********print的输出********逗号代表在同一行************"
a = "x"
b = "y"
print a,
print b
print a
print b
|
d56e5bfb3687d690ffbad4ef2e5d544d6f0c8c3e | abbsmile/Python-base | /RegularExpression/pattern_aearch.py | 310 | 3.890625 | 4 | # encoding: UTF-8
import re
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'hello')
match = pattern.search('hello hello world world world!')
if match:
print "match已经被匹配上了,什么情况"
print match.group()
else:
print "这个暂时它还没有被匹配上!"
|
1de7b7ff2eccba1acd3a0ade2f759afa06066c70 | Hallye/DjangoGirls | /django.py | 196 | 3.8125 | 4 | #akjds
if 3 < 2:
print("Hello Django")
def hi(name):
print("Hi " + name)
print("How are you?")
hi("Gabriela")
#bucle
girls = ["Rachel", "Rosa", "Sofia"]
for name in girls:
hi(name) |
348f1b509bb1e5928454acda482d2b06228b2567 | Mownicaraja/python-programs | /remove-dup.py | 166 | 3.53125 | 4 | from collections import OrderedDict
def dup(ss):
return "".join(OrderedDict.fromkeys(ss))
if __name__ == "__main__":
ss=str(input())
print(dup(ss))
|
b3b7bc3266df4bfd22584093f3967b5c5476fec9 | sonali-mahavar/addition-of-number | /first.py | 95 | 3.828125 | 4 | print("hello")
a=int(input("enter first no:"))
b=int(input("enter second no:"))
print(a+b)
|
0b2271242a08c6cb56c495e4d27ede2a919e2dd5 | Jhavaa/Final_Project_ML | /credit_data.py | 3,731 | 3.734375 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
############### A more detailed explanation to why we transformed the data the way we did can be found in credit_analysis.py ###############
### Prepare this dataset to be used for further analysis
## Import dataframe
# df_credit = pd.read_csv("c:/Users/Jhanava/Desktop/2020 FALL/CAP5610 - Introduction to Machine Learning/Final project/data/creditcard.csv")
df_credit = pd.read_csv("../data/creditcard.csv")
#f_credit = pd.read_csv("C:\\Users\\Adnrew\\Dropbox\\dataSets\\creditcard.csv")
#df_credit = pd.read_csv("https://www.kaggle.com/mlg-ulb/creditcardfraud/download")
# Shuffle data entries
df_credit = df_credit.sample(frac=1)
# find column names and save them (convenience)
columns = df_credit.columns[:]
# Split entries evenly by class
df_fraud = df_credit.loc[df_credit['Class'] == 1]
df_nonfraud = df_credit.loc[df_credit['Class'] == 0][:len(df_fraud.index)]
# Combine evenly split entries
df_credit_even = pd.concat([df_fraud, df_nonfraud])
# Shuffle again
df_credit_even = df_credit_even.sample(frac=1)
## Encode data
# Display data type of columns in the data frame
# print(df_credit.dtypes)
# The data types have already been assigned the correct data types.
# No need for further changes in regards to encoding.
## Perform appropriate scaling
sc = StandardScaler()
# Scale Time and Amount values (this data will use df_credit_even)
df_credit_scaled = df_credit_even.assign(Time=sc.fit_transform(df_credit_even['Time'].values.reshape(-1, 1)),
Amount=sc.fit_transform(df_credit_even['Amount'].values.reshape(-1, 1)))
## Obtain values from dataframe columns and assign them appropriately
# iloc is a purely integer-location based indexing for selction by position.
# iloc is used to select data that is to be stored in X and y.
# X gets the whole row between the first column and second to last column.
# y gets the whole last column.
X, y = df_credit.iloc[:, :-1].values, df_credit.iloc[:, -1].values
#scaled
X_scaled, y_scaled = df_credit_scaled.iloc[:, :-1].values, df_credit_scaled.iloc[:, -1].values
## Split between training and testing set
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8, test_size = 0.2, random_state = 1, stratify = y)
#scaled
X_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled = train_test_split(X_scaled, y_scaled, train_size = 0.8, test_size = 0.2, random_state = 1, stratify = y_scaled)
# standardize training feature data
X_train_std = sc.fit_transform(X_train)
X_test_std = sc.transform(X_test)
#scaled
X_train_scaled_std = sc.fit_transform(X_train_scaled)
X_test_scaled_std = sc.transform(X_test_scaled)
# take 10% of the data to perform functions faster
small_credit = df_credit.sample(frac=0.1)
small_X, small_y = small_credit.iloc[:, :-1].values, small_credit.iloc[:, -1].values
small_X_train, small_X_test, small_y_train, small_y_test = train_test_split(small_X, small_y, train_size = 0.8, test_size = 0.2, random_state = 1, stratify = small_y)
small_X_train_std = sc.fit_transform(small_X_train)
small_X_test_std = sc.transform(small_X_test)
#scaled
small_credit_scaled = df_credit_scaled.sample(frac=0.1)
small_X_scaled, small_y_scaled = small_credit_scaled.iloc[:, :-1].values, small_credit_scaled.iloc[:, -1].values
small_X_train_scaled, small_X_test_scaled, small_y_train_scaled, small_y_test_scaled = train_test_split(small_X_scaled, small_y_scaled, train_size = 0.8, test_size = 0.2, random_state = 1, stratify = small_y_scaled)
small_X_train_scaled_std = sc.fit_transform(small_X_train_scaled)
small_X_test_scaled_std = sc.transform(small_X_test_scaled) |
a6d443f8388998d8fc539da675ba86969a3bf91e | ruslanabdulin1985/TheTask | /Battleships/model/game.py | 2,946 | 3.890625 | 4 | """
Module contains class Game
The module imports two Classes of this model: Player to represent players and Coordinates to let players exchange
coordinates
"""
from model.rules import Rules
from model.player import Player
from model.coordinates import Coordinates
# FIXME
from model.ship import Ship
class Game:
"""
Game class represents a game as a set of interactions in between players
Game is the main class which is responsible for interactions within the game.
"""
def __init__(self, id: int, player1: Player, player2: Player, rules:Rules):
"""
Construnctor of the class
:param id: each game is supposed to have a unique ID
:param player1:
:param player2:
"""
self.id = id
self.player1 = player1
self.player2 = player2
self.turn = player1
self.rules = rules
def fire(self, coordinates: Coordinates) -> bool:
"""
Main method of the Game class. Checks if one player hit another
This method is responsible for handle a situation when one player tries to hit a ship of another,
the situation is basically main mechanic of the game so the method is crucial
:param coordinates: target coordinates
:return: True or False depending if the coordinates has a ship on target player's board
"""
if self.next_player().is_received_duplicates(coordinates):
self.turn = self.next_player()
self.turn.score_multiplexor = 1
return False # prevent duplicates
else:
self.next_player().recieve.add(coordinates)
for ship in self.next_player().get_alive_ships(): # for each alive ship
if ship.is_hit(coordinates):
ship.hit_points -= 1
self.turn.add_score()
if ship.is_dead():
for coordinates in ship.calculate_dead_coordinates():
self.next_player().recieve.add(coordinates)
return True
self.turn.score_multiplexor = 1
self.turn = self.next_player()
return False
def is_game_over(self):
"""
:return: True if at least one player has no ships left, otherwise False
"""
if not self.player1.has_more_alive_ships() or not self.player2.has_more_alive_ships():
return True
return False
def next_player(self) ->Player:
"""
Who's turn is next
:return: Player who will be making move next
"""
if self.turn == self.player1:
return self.player2
else:
return self.player1
def add_player(self,player_num:str, name:str, list_of_ships:list):
player = Player(name)
if player_num == '1':
self.player1 = player
self.turn = player
if player_num == '2':
self.player2 = player
|
6d621a1a63ee390fd1edebb52cb39f88fe698251 | harishkbsingh/rareEdgeDetection | /draftV3/Main.py | 1,030 | 3.59375 | 4 | import datetime
from Algorithm import Algorithm
from Util import getEdges, getKey
'''
This method simulates the algorithm for 6 months
'''
def runMonthsSimulation():
instance = Algorithm()
base = datetime.datetime(2019, 1, 1)
date_list = [base + datetime.timedelta(hours=x) for x in range((24*30*5) + 13)]
for t in date_list:
runAlgorithm(instance, t)
print('*************************** Analysis Completed')
'''
Instance called for each edge (source, destination) with connections in the current hour
Input: algorithm instance (instance) and current date (date)
Output: None
'''
def runAlgorithm(instance, date):
# For each edge in given hour: source, dest, #connection
start = date.strftime("%Y-%m-%d %H:%M:%S")
end = (date + datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
dictionary = getEdges(start, end)
# Feed algorithm for each edge
for key, row in dictionary.items():
instance.feed(getKey(row[0], row[1]), row[2], start)
runMonthsSimulation()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.