blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8b7564e7d455e89b129e36852f851a5f2c9b1e2f | code-ninja-james/MachineLearning-DataScience | /Python/built_in.py | 125 | 3.546875 | 4 | #inbuilt functions and methods
quote='to be or not to be'
quote2=print(quote.replace('be','me'))
print(quote2)
print(quote) |
dc0238dfd80b7303d03f763713238469352da9a1 | brij2020/Ds-pythonic | /Quiz-Linked-List/Student_information.py | 1,882 | 3.765625 | 4 | """
QUIZE :
Store information in linked list
"""
'''****** MARK Linked List for Each Students ******** '''
class Mark(object):
next = None
mark = None
pass
class Mark_lis(object) :
head = None
def markList(self, val):
node = Mark()
node.mark = val
node.next = self.head
self.head = node
pass
''' ********************** END *******************'''
'''***************Students Linked List ************'''
class Node(object):
roll = None
name = None
next = None
pass
class Students(object):
head = None
marks = None
students = []
pass_status = 0
def store_data(self,roll, name , marks_list):
Students.students.append(self)
node = Node()
node.roll = roll
node.name = name
self.marks = Mark_lis()
for x in marks_list :
self.marks.markList(x)
node.next = self.head
self.head = node
pass
@staticmethod
def detail_All_students():
total = 0
for x in Students.students:
mar = x.marks.head
while mar :
total += mar.mark
mar = mar.next
if (total/3)>=40 :
Students.pass_status += 1
print(Students.pass_status)
pass
def show_data(self):
node = self.head
while node:
print('{} {}'.format(node.roll,node.name))
node = node.next
pass
pass
def main():
st1 = Students()
st2 = Students()
st3 = Students()
st4 = Students()
st1.store_data(120,'Brijbhan',[44,35,30])
st2.store_data(121,'Ramesh',[12,13,25])
st3.store_data(122,'Gopi',[12,35,20])
st4.store_data(123,'Aand',[23,34,26])
Students().detail_All_students()
pass
if __name__ == '__main__':
main()
|
dad9b00b0340802b7326eb77981d794712ffb051 | lishuchen/Algorithms | /lintcode/31_Partition_Array.py | 654 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution:
"""
@param nums: The integer array you should partition
@param k: As description
@return: The index after partition
"""
def partitionArray(self, nums, k):
# write your code here
# you should partition the nums by k
# and return the partition index as description
if not nums:
return 0
i, large = 0, len(nums) - 1
while i <= large:
if nums[i] < k:
i += 1
else:
nums[i], nums[large] = nums[large], nums[i]
large -= 1
return i
|
7013a8cde90c6f411724d6dfb748a6624163bf7b | KnightChan/LeetCode-Python | /Median of Two Sorted Arrays.py | 1,105 | 3.5 | 4 | class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
'''There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
'''
la = len(A)
lb = len(B)
l = la + lb
if l % 2 == 1:
return self.findKth(A, la, B, lb, l // 2 + 1)
else:
return (self.findKth(A, la, B, lb, l // 2) + self.findKth(A, la, B, lb, l // 2 + 1)) * 0.5
return self.findMedian(A, la, B, lb)
def findKth(self, A, la, B, lb, k):
if la == 0:
return B[k - 1]
if lb == 0:
return A[k - 1]
if k == 1:
return min(A[0], B[0])
i = min(k // 2, la)
j = min(k // 2, lb)
if A[i - 1] > B[j - 1]:
return self.findKth(A, la, B[j:], lb - j, k - j)
else:
return self.findKth(A[i:], la - i, B, lb, k - i)
A = [0, 10]
B = [1.1, 2.1, 3.2]
x = [[], [2,3]]
so = Solution()
print(x)
print(so.findMedianSortedArrays(x[0], x[1])) |
7c4cd9fb12ff84f37bac18da8a3882a2996d74b7 | EduardoShibukawa/UEM | /MOA/Puzzle15/Utils/PriorityQueue.py | 609 | 3.6875 | 4 | import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._dic = {}
def empty(self):
return len(self._queue) == 0
def put(self, item):
if str(item) in self._dic and \
self._dic[str(item)].fn() > item.fn():
self._dic[str(item)].to_pop = False
self._dic[str(item)] = item
item.to_pop = True
heapq.heappush(self._queue, item)
def get(self):
item = heapq.heappop(self._queue)
while not item.to_pop:
item = heapq.heappop(self._queue)
return item
|
a78b80791666b2554082bcd62730d5d079b743fb | RSANJAYKUMAR/THALA-DHONI | /vowel.py | 154 | 3.84375 | 4 | test=['a','e','i','o','u','A','E','I','O','U']
ss=raw_input()
if(ss in test):
print('Vowel')
elif(ss!=test):
print('Consonant')
else:
print('invalid')
|
465fc00d09131237489aed7d3b5fd1c98840aa4a | alexblumenfeld/gas-lines-puzzle | /gui-main.py | 1,423 | 3.546875 | 4 | from tkinter import *
from tkinter import ttk
# Set up a master frame for the whole window, as well as one frame for the game board and one for the configuration section
root = Tk()
general_frame = ttk.Frame(root,width=1000,height=1000)
general_frame.grid(column=0,row=0,columnspan=20,rowspan=20)
general_frame.columnconfigure(1,weight=1)
general_frame.rowconfigure(1,weight=1)
board_frame = ttk.Frame(general_frame, borderwidth = 5,width=800,height=1000)
board_frame.grid(column=0,row=0,columnspan=20,rowspan=20)
board_frame.columnconfigure(1,weight=1)
board_frame.rowconfigure(1,weight=1)
config_frame = ttk.Frame(general_frame,borderwidth=5)
config_frame.grid(column=0,row=0,columnspan=20,rowspan=20)
config_frame.columnconfigure(1,weight=1)
config_frame.rowconfigure(1,weight=1)
# Titles
board_title = ttk.Label(board_frame,text='Puzzle Board')
board_title.grid(column=0,row=0,columnspan=13,rowspan=1)
# Set up a Canvas for the 7x7 board (will try to adjust for variable board size later if I figure out how)
board_canvas = Canvas(board_frame)
# Create a list of locations for the circles representing houses/utilities/nodes
for x in range(10,370,60):
for y in range(10,370,60):
board_canvas.create_oval(x,y,x+30,y+30)
board_canvas.create_line(x+15,y+30,x+15,y+60)
board_canvas.create_line(x+30,y+15,x+60,y+15)
board_canvas.grid(column=1,row=0,columnspan=13,rowspan=13)
root.mainloop() |
8e69a4426ce814d3124745a4f5cd7489dbdcfc52 | tashvit/beginner_python_problems | /6_tiles_cost.py | 744 | 4.5 | 4 | # Find Cost of Tile to Cover W x H Floor -
# Calculate the total cost of tile it would take to cover a floor plan
# of width and height, using a cost entered by the user.
# Floor tile cost calculator
import math
floor_width = float(input("Enter floor width: "))
floor_height = float(input("Enter floor height: "))
tile_width = float(input("Enter tile width: "))
tile_height = float(input("Enter tile height: "))
tile_cost = float(input("Enter cost of single tile: "))
tiles_for_w = math.ceil(floor_width / tile_width)
tiles_for_h = math.ceil(floor_height / tile_height)
total_tiles = tiles_for_w * tiles_for_h
final_cost = tile_cost * total_tiles
print(f"Final cost of tiles for floor plan {floor_width} x {floor_height} is: {final_cost}") |
6ec7f51e6a0798b93e58d6a2b23565e644623bc3 | hmhuan/advanced-python | /sets.py | 713 | 4.21875 | 4 | # This is sets 101
my_set = {"pomme", "orange", "chocolat", "gateau"}
print(my_set)
my_set = set([1, 2, 3, 4, 4])
print(my_set)
my_set = set((1, 2, 3, 4, 4))
print(my_set)
my_set = set("abcdefffgggghhhiii")
print(my_set)
# default {} -> dict
a = {}
print(type(a))
a = set()
print(type(a))
# methods
my_set = set()
my_set.add(1)
my_set.add('a')
my_set.add(True)
my_set.add(False)
print(my_set)
print(set({1,True})) # result is {1}
my_set = {"apple", "banana", "grape", "strawberry"}
# my_set.remove("orange") -> use discard instead
my_set.discard("orange")
print(my_set)
my_set.remove("banana")
print(my_set)
my_set.pop()
print(my_set)
# frozen set
my_set = frozenset([1, 2, 3, 4, 5, 5])
print(my_set)
|
8349ae8b4f1a41add64ec40c181c8739259223df | nathanielatom/Gravity-Well | /dimmer.py | 2,532 | 4 | 4 | """
Dimmer class
Tobias Thelen (tthelen@uni-osnabrueck.de)
6 September 2001
PUBLIC DOMAIN
Use it in any way you want...
tested with: Pyton 2.0/pygame-1.1, Windows 98
A class for 'dimming' (i.e. darkening) the entire screen, useful for:
- indicating a 'paused' state
- drawing user's attention away from background to e.g. a Quit/Don't Quit
dialog or a highscore list or...
Usage:
dim=Dimmer(keepalive=1)
Creates a new Dimmer object,
if keepalive is true, the object uses the same surface over and over again,
blocking some memory, but that makes multiple undim() calls possible -
Dimmer can be 'abused' as a memory for screen contents this way..
dim.dim(darken_factor=64, color_filter=(0,0,0))
Saves the current screen for later restorage and lays a filter over it -
the default color_filter value (black) darkens the screen by blitting a
black surface with alpha=darken_factor over it.
By using a different color, special effects are possible,
darken_factor=0 just stores the screen and leaves it unchanged
dim.undim()
restores the screen as it was visible before the last dim() call.
If the object has been initialised with keepalive=0, this only works once.
"""
import pygame
class Dimmer:
def __init__(self, keepalive=0):
self.keepalive=keepalive
if self.keepalive:
self.buffer=pygame.Surface(pygame.display.get_surface().get_size())
else:
self.buffer=None
def get_dim(self):
return bool(self.buffer)
def dim(self, darken_factor=64, color_filter=(0,0,0)):
if not self.keepalive:
self.buffer=pygame.Surface(pygame.display.get_surface().get_size())
self.buffer.blit(pygame.display.get_surface(),(0,0))
if darken_factor>0:
darken=pygame.Surface(pygame.display.get_surface().get_size())
darken.fill(color_filter)
darken.set_alpha(darken_factor)
# safe old clipping rectangle...
old_clip=pygame.display.get_surface().get_clip()
# ..blit over entire screen...
pygame.display.get_surface().blit(darken,(0,0))
pygame.display.update()
# ... and restore clipping
pygame.display.get_surface().set_clip(old_clip)
def undim(self):
if self.buffer:
pygame.display.get_surface().blit(self.buffer,(0,0))
pygame.display.update()
if not self.keepalive:
self.buffer=None
|
0d237e78581e9bb73316d8f35a5f868e047963cb | frsojib/python | /Anisur/demo.py | 146 | 3.609375 | 4 | n = 20
m = 60
sum = n+m
print("Your sum is " + str(sum))
print(f"{n} + {m} = {n+m}")
# stop new line
print("fayzur Rahman",end=" ")
print("01779031617") |
919c692bc6316ec4fa9e616cd2ca2d5a6feb6e49 | danuker/piggies | /piggies/processing.py | 1,598 | 3.5 | 4 | import logging
from decimal import Decimal
from time import sleep
logger = logging.getLogger('piggy_logs')
def inexact_to_decimal(inexact_float):
"""
Transforms a float to decimal, through its __str__() method.
>>> inexact_to_decimal(3.14)
Decimal('3.14')
Avoids doing the following:
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
"""
return Decimal(str(inexact_float))
def wait_for_success(success_check, description, max_seconds=120):
"""
Wait until calling `success_check` returns a truthy value.
:param success_check: Callable returning truthy on success, false otherwise
:param description: What the task is about (to log)
:param max_seconds: Maximum amount of time to wait, before giving up
"""
logger.info('Waiting for {} (at most {} seconds)'.format(description, max_seconds))
for wait in range(max_seconds):
if success_check():
return
else:
logger.info('Waited for {} ({} seconds so far)'.format(description, wait))
sleep(1)
if not success_check():
raise ValueError('{} failed after {} seconds'.format(description, max_seconds))
def check_port(port_num, name='port'):
"""Check that the port is a valid number. You'd be surprised."""
if not isinstance(port_num, int):
raise ValueError('Error! {} ({}) is not an integer!'.format(name, port_num))
elif port_num > 65535:
raise ValueError('Error! {} number too large ({}})'.format(name, port_num))
else:
return port_num
|
d2c1e86b6bd345c54188b982464fdb98a7166a8a | tuhiniris/Python-ShortCodes-Applications | /file handling/Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File.py | 439 | 4.09375 | 4 | '''
Problem Description
The program takes a letter from the user
and counts the number of occurrences of
that letter in a file.
'''
fileName=input('Enter the file Name: ')
character=input('Enter letter to be searched: ')
k=0
with open(fileName,'r') as f:
for line in f:
words=line.split()
for i in words:
for letter in i:
if letter==character:
k+=1
print(f'Occurance of letters \'{character}\' is: {k}') |
c0520baa42a12071a220ffec33ea0629527ebf04 | huiba7i/Mycode | /python/class code/code4.23/bank.py | 2,760 | 4.15625 | 4 | class Account:
def __init__(self, card_code, name, password):
"""
银行账户类
:param card_code:卡号
:param name:开户人
:param password:密码
"""
self.card_code = card_code
self.name = name
self.password = password
self.money = 0.0
def in_money(self, money):
"""存钱"""
self.money += money
return "存钱成功,账户余额:%.2f" % self.money
def out_money(self, money):
"""取钱"""
if self.money - money < 0:
return "账户余额不足"
else:
self.money -= money
return "取钱成功,账户余额:%.2f" % self.money
class Bank:
def __init__(self):
self.accounts = [] # 定义银行的所有账户
def find_account(self, card_code):
"""根据银行卡号查找账户"""
for account in self.accounts:
if card_code == account.card_code:
return account
return None
# 应用开发
bank = Bank()
while True:
result = input("请选择:1.开户 2.存钱 3.取钱 4.查询 5.退出")
if result == "1":
card_code = input("请输入卡号:\n")
password = input("请输入密码:\n")
name = input("请输入开户人姓名:\n")
account = Account(card_code, name, password)
bank.accounts.append(account)
print("恭喜您开户成功")
elif result == "2":
card_code = input("请输入卡号:\n")
account = bank.find_account(card_code)
if account:
money = input("请输入存钱金额:\n")
r = account.in_money(float(money))
print(r)
else:
print("输入的卡号不存在")
elif result == "3":
card_code = input("请输入卡号:\n")
account = bank.find_account(card_code)
if account:
password = input("请输入密码:\n")
if password != account.password:
print("密码不正确")
else:
money = input("请输入取钱金额:\n")
r = account.out_money(float(money))
print(r)
else:
print("输入的卡号不存在")
elif result == "4":
card_code = input("请输入卡号:\n")
account = bank.find_account(card_code)
if account:
password = input("请输入密码:\n")
if password != account.password:
print("密码不正确")
else:
print(account.card_code, account.name, account.password, account.money)
else:
print("输入的卡号不存在")
elif result == "5":
break
|
7bae7a197afaf09e9b4b3bcb2e269ac099c75b4e | dimitrisarnellos/ThesisScripts | /extractFastaSeq.py | 658 | 4.125 | 4 | #!/usr/bin/python3
#
# Program that outputs selected sequences from a FASTA file.
# User supplies the FASTA file as first argument and the file with the sequence IDs
# whose sequences we want to output as the second argument.
import sys, re
idList = []
with open(sys.argv[2], 'r') as f:
for line in f:
line = line.rstrip()
idList.append(line)
found = False
with open(sys.argv[1], 'r') as fu:
for line in fu:
if re.match('\>', line):
seqid = re.match('\>(\S+)', line)
if seqid.group(1) in idList:
found = True
line = line.rstrip()
print(line)
else:
found = False
elif found is True:
line = line.rstrip()
print(line) |
116c32f8e4d3fc7296ce32fbb73b66459f1cd9c2 | SherifElbishlawi/My-Codewars-Katas-Python-Solutions | /6kyu/Counting Duplicates/CountingDuplicates.py | 874 | 4.34375 | 4 | # Count the number of Duplicates Write a function that will return the count of distinct case-insensitive alphabetic
# characters and numeric digits that occur more than once in the input string. The input string can be assumed to
# contain only alphabets (both uppercase and lowercase) and numeric digits.
#
# Example
# "abcde" -> 0 # no characters repeats more than once
# "aabbcde" -> 2 # 'a' and 'b'
# "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
# "indivisibility" -> 1 # 'i' occurs six times
# "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
# "aA11" -> 2 # 'a' and '1'
# "ABBA" -> 2 # 'A' and 'B' each occur twice
def duplicate_count(text):
temp = []
output = 0
for x in text:
if x.lower() in temp and (temp.count(x.lower()) == 1):
output += 1
temp.append(x.lower())
return output
|
3c25d46c38984b86cad4634d6e9195f7a9e55fc8 | HienPhanVN/Nguyen_Ly_May_Hoc | /TH_1.py | 1,875 | 3.609375 | 4 | # Cau 1
A = [2,5,3,6,7,8]
# Cau 2
B =[]
for i in range(200):
B.insert(i,i+1)
print(B[i])
#Cau 3
import numpy as np
B = np.linspace(2,1000,500)
#Cau 4
A5 = []
count = 0
for i in A:
A5.insert(count,i+5)
count += 1
#Cau 5
B3 = []
count = 0
for i in B:
B3.insert(count,i*3)
count += 1
#Cau 6
A.sort(reverse=False)
#Cau 7
Dict = {'Name':'Phan Vo Dinh Hien','Age':22,'Course':'Nguyen Ly May Hoc'}
#Cau 8
Dict['Course'] = 'Tri Tue Nhan Tao'
#Cau 9
ten = raw_input("Nhap ten vao : ")
print("hello "+ten)
#Cau 10
import numpy as np
a = input("Nhap a : ")
b = input("Nhap b : ")
c = input("Nhap c : ")
delta = b*b - 4*a*c
if(delta > 0):
delta_calculated = np.sqrt(delta)
x1 = (-b + delta_calculated)/2*a
x2 = (-b - delta_calculated)/2*a
print("x1 "+str(x1))
print("x2 "+str(x2))
else:
print("Phuong Trinh Vo Nghiem")
#Cau 11
array = []
a = input("Nhap a : ")
array.insert(0,a)
b = input("Nhap b : ")
array.insert(1,b)
c = input("Nhap c : ")
array.insert(2,c)
array.sort(reverse=True)
print(array[0])
#Cau 12
w, h = 3, 3
Matrix = [[0 for x in range(w)] for y in range(h)]
for x in range(3):
for y in range(3):
Matrix[x][y] = input('nhap phan tu o vi tri ['+str(x)+']['+str(y)+']')
for x in range(3):
for y in range(3):
print Matrix[x][y],
print ""
#Cau 13
#Cau 12
w, h = 3, 3
Matrix = [[0 for x in range(w)] for y in range(h)]
for x in range(3):
for y in range(3):
Matrix[x][y] = input('nhap phan tu o vi tri ['+str(x)+']['+str(y)+']')
for x in range(3):
for y in range(3):
print Matrix[x][y],
print ""
|
deb4063298f25b5a0319ce0b9d49b08f7a9b217b | MichaelIseli/GEOG5991_ABM | /agentframework_final_180204.py | 2,251 | 3.875 | 4 | #-------------------------------------------------------------------------------
# Name: agentframework_final_180204
# Purpose:
#
# Author: Michael Iseli
#
# Created: 23/01/2018
# Copyright: (c) iseli 2018
#-------------------------------------------------------------------------------
'''
Coding for GEOG5991M
Assessment1
Geographical Information Analysis
module for MSc GIS at University of Leeds
Tutor: Dr. Andy Evans
All code derived from practical handouts by Dr. Evans
'''
# Import radom module for creation of agents
import random
# Creating Agent class and the relevant environment
class Agent():
def __init__(self, environment, agents, neighbourhood):
self.x = random.randint(0,99)
self.y = random.randint(0,99)
self.environment = environment
self.agents = agents
self.store = 0
self.neighbourhood = neighbourhood
# Movment of agents withing the defined environment
# Limiting movement to the "environment" perimeter
# If an agents "leaves" environment it will reappear on the oposite side
def move(self):
if random.random() < 0.5:
self.y = (self.y +1) % len(self.environment)
else:
self.y = (self.y -1) % len(self.environment)
if random.random() < 0.5:
self.x = (self.x +1) % len(self.environment)
else:
self.x = (self.x -1) % len(self.environment)
# Nibbling away the current location
def eat(self):
if self.environment[self.y][self.x] > 10:
self.environment[self.y][self.x] -= 10
self.store += 10
# Defining the distance between the agent and its sibblings
# a2+b2=c2... Pythagoras - Ellada kai pali Ellada!
def distance_between(self, agent):
return(((self.x - agent.x)**2)+((self.y - agent.y)**2))**0.5
# if within neigbourhood eat only an "average" portion
def share_with_neighbours(self, neighbourhood):
for agent in self.agents:
dist = self.distance_between(agent)
if dist <= neighbourhood:
sum = self.store + agent.store
avg = sum/2
self.store = avg
agent.store = avg
#print("sharing" + str(dist) + " " + str(avg))
|
3105ce97b8fca9539721b5b0b0e04c16b8b6e986 | sunshinedude/practice | /leetcode/1002_find_common_characters.py | 1,272 | 3.71875 | 4 | # Problem
# Given an array A of strings made only from lowercase letters,
# return a list of all characters that show up in all strings within the list (including duplicates).
# For example, if a character occurs 3 times in all strings but not 4 times,
# you need to include that character three times in the final answer.
#
# You may return the answer in any order.
#
#
#
# Example 1:
#
# Input: ["bella","label","roller"]
# Output: ["e","l","l"]
# Example 2:
#
# Input: ["cool","lock","cook"]
# Output: ["c","o"]
#
#
# Note:
#
# 1 <= A.length <= 100
# 1 <= A[i].length <= 100
# A[i][j] is a lowercase letter
# Solution
from typing import List
from leetcode.test import Test
class Solution:
def commonChars(self, A: List[str]) -> List[str]:
c = {}
for i in A[0]:
if not c.get(i):
c[i] = A[0].count(i)
for j in A[1::]:
c[i] = min(c[i], j.count(i))
res = []
for k, v in c.items():
res += [k] * v
return res
# Tests
cases = [
{
"input": ["bella", "label", "roller"],
"output": ["e", "l", "l"]},
{
"input": ["cool", "lock", "cook"],
"output": ["c", "o"]},
]
Test(Solution().commonChars, cases, True).test()
|
fc9db1f92dd41844c742c26f92449a65ea15135b | douglasleandro/adventure-game | /adventure_game.py | 4,385 | 4 | 4 | import time
import random
monsters = ['pirate', 'gorgon', 'troll', 'wicked fairie']
def print_pause(message):
print(message)
time.sleep(2)
def intro(monster):
print_pause("You find yourself standing in an open field, filled with "
"grass and yellow wildflowers.")
print_pause(f"Rumor has it that a {monster} is "
"somewhere around here, and has been terrifying the near by "
"village.")
print_pause("In front of you is a house.")
print_pause("To your right is a dark cave.")
print_pause("In your hand you hold your trusty (but not very effective) "
"dagger.\n")
def valid_input(prompt, opt1, opt2):
while True:
response = input(prompt)
if response == opt1:
break
elif response == opt2:
break
return response
def field():
print_pause("Enter 1 to knock on the door of the house.")
print_pause("Enter 2 to peer into the cave.")
def house(item, monster):
print_pause("You approach the door of the house.")
print_pause("You are about to knock when the door opens and out steps a "
f"{monster}.")
print_pause(f"Eep! This is the {monster}'s house!")
print_pause(f"The {monster} attacks you!")
if "sword" in item:
option = valid_input("Would you like to (1) fight or (2) run away?",
"1", "2")
if option == "1":
print_pause(f"As the {monster} moves to "
"attack, you unsheath your new sword.")
print_pause("The Sword of Ogoroth shines brightly in your hand as "
"you brace yourself for the attack.")
print_pause(f"But the {monster} takes one "
"look at your shiny new toy and runs away!")
print_pause(f"You have rid the town of the {monster}. You are "
"victorious!")
elif option == "2":
print_pause("You run back into the field. Luckily, you don't seem "
"to have been followed.\n")
field()
main(item)
else:
print_pause("You feel a bit under-prepared for this, what with only "
"having a tiny dagger.")
option = valid_input("Would you like to (1) fight or (2) run away?",
"1", "2")
if option == "1":
print_pause("You do your best...")
print_pause("but your dagger is no match for the "
f"{monster}.")
print_pause("You have been defeated!")
elif option == "2":
print_pause("You run back into the field. Luckily, you don't seem "
"to have been followed.\n")
field()
main(item, monster)
def cave(item, monster):
if "sword" in item:
print_pause("You peer cautiously into the cave.")
print_pause("You've been here before, and gotten all the good stuff. "
"It's just an empty cave now.")
print_pause("You walk back out to the field.\n")
field()
main(item, monster)
else:
print_pause("You peer cautiously into the cave.")
print_pause("It turns out to be only a very small cave.")
print_pause("Your eye catches a glint of metal behind a rock.")
print_pause("You have found the magical Sword of Ogoroth!")
print_pause("You discard your silly old dagger and take the sword "
"with you.")
item.append("sword")
print_pause("You walk back out to the field.\n")
field()
main(item, monster)
def main(item, monster):
option = valid_input("What would you like to do? \n"
"(Please enter 1 or 2).\n", "1", "2")
if option == "1":
house(item, monster)
elif option == "2":
cave(item, monster)
def play_again():
option = valid_input("Would you like to play again? (y/n)", "y", "n")
if option == "y":
print_pause("Excellent! Restarting the game ... \n")
play_game()
elif option == "n":
print_pause("Thanks for playing! See you next time.")
def play_game():
item = []
monster = random.choice(monsters)
intro(monster)
field()
main(item, monster)
play_again()
play_game()
|
ec269b0b75181455e4c50b55a81661fd4a042fbf | nandadao/Python_note | /note/my_note/second_month/day05/homework_day05.py | 1,043 | 3.890625 | 4 | """
质数又被称为素数,是指一个大于1的自然数,
除了1和它自身外,不能被其它自然数整除,
且其个数是无穷的,具有许多独特的性质,现如今多被用于密码学上。
求100000以内的质数之和
"""
# 自己的想法
# 做一个生成器,需要一个加一个
import time
# def prime():
# # 求质数
#
# for item in range(2, 1000): # 5
# if item == 2:
# yield item
# for i in range(2, item): # (2, 5)
# if item % i == 0:
# break
#
# yield item
#
start = time.time()
def prime():
for i in range(2,100000):
for j in range(2, i):
if (i % j) == 0:
break
else:
# num.append(i)
yield i
# print(num)
# prime()
# for i in prime():
# print(i)
#
i = 0
for item in prime():
i += item
stop = time.time()
use_time = stop - start
print("使用迭代器方法耗时:", use_time)
print("100000以内质数的和是:", i)
# 使用迭代器方法耗时: 0.32865428924560547
# 10000以内质数的和是: 5736396
|
202e7daa2c1eefd3e77a07b2e05217999fc88faf | andysai/python | /风变编程/python基础-山脚班/fb_22.py | 256 | 3.875 | 4 | # 八、让用户输入一个数字,并指出这个数字是否是10的整数倍
number = int(input("请输入一个数:"))
if (number % 10) == 0 :
print("{}是10的整倍数".format(number))
else:
print("{}不是10的整倍数".format(number)) |
566f5b664446a8cb27c14c8f954a19693cda2746 | ESzabelski/Good-Projects | /better guessing game.py | 2,323 | 3.984375 | 4 | import random
secretword=input("Please pick a secret word for the other person to match.\
It must be 4 letters or longer.")
listb=[]
listb.extend(secretword)
lengthb=len(listb)
#eg. result is v a n q u i s h AND length 8
while lengthb <4:
secretword=input("Try again. It must be 4 letters or longer.")
listb=[]
listb.extend(secretword)
lengthb=len(listb)
for x in range(40):
print()
guess = ""
totalGuesses=0
victory=0
how_many_guesses_are_allowed = 5
random_tip=[1,2,3,4,5,6]
random.shuffle(random_tip)
#should 1st tip always be length?
def clues(random_tip):
if random_tip ==1:
print("Wrong answer. The secret word is" , lengthb , " letters long.")
if random_tip ==2:
print("Hint: the FIRST letter is: " , listb[0])
if random_tip ==3:
print("Hint: the SECOND letter is: " , listb[1])
if random_tip ==4:
print("Hint: the THIRD letter is: " , listb[2])
if random_tip ==5:
print("Hint: the FOURTH letter is: " , listb[3])
if random_tip ==6:
print("Hint: the LAST letter is: " , listb[lengthb-1])
while guess != secretword:
print()
guess = input("Enter your guess for the secret word: ")
if guess == secretword:
victory=1
break
totalGuesses +=1
if totalGuesses==1:
print()
print("You have", how_many_guesses_are_allowed-1, "guesses left")
clues(random_tip[0])
if totalGuesses==2:
print()
print("You have", how_many_guesses_are_allowed-2, "guesses left")
clues(random_tip[1])
if totalGuesses==3:
print()
print("You have ", how_many_guesses_are_allowed-3, " guesses left")
clues(random_tip[2])
if totalGuesses==4:
print()
print("You have ", how_many_guesses_are_allowed-4, " guess left!! You get one more clue: ")
clues(random_tip[3])
#total guesses before game is over
if totalGuesses >= how_many_guesses_are_allowed:
victory=2
break
if victory == 1:
print()
print ("Nice job, you win!")
print()
elif victory == 2:
print()
print("No, you lose.")
print("The answer was: ", secretword)
|
3d03c3a3d003db3db750226fbfc3d0537900a6f4 | Chamangro/PythonPUNCHIT | /Ejercicio 5 Edades.py | 887 | 4.0625 | 4 | #Ingresar las edades de dos personas. Si una de ellas es mayor de edad
#y la otra menor de edad, calcular y mostrar su promedio. En caso
#contrario mostrar las edades.
MAYOR_DE_EDAD = 18
persona_1 = int(input("Ingrese edad de la persona: "))
persona_2 = int(input('Ingrese edad de la segunda persona: '))
if persona_1 > MAYOR_DE_EDAD and persona_2 < MAYOR_DE_EDAD:
print(persona_1)
print(persona_2)
promedio_edad = (persona_1 + persona_2) / 2
print(f'El promedio de edad ingresado es de {promedio_edad}')
elif persona_1 < MAYOR_DE_EDAD and persona_2 > MAYOR_DE_EDAD:
print(persona_1)
print(persona_2)
promedio_edad = (persona_1 + persona_2) / 2
print(f'El promedio de edad ingresado es de {promedio_edad}')
else:
print(f'La edad de la primera persona es: {persona_1} y la edad de la segunda persona es: {persona_2}') |
0d7597237234e90a862b5f53c28dab847dd0ca26 | Lawapaul/Fair-Calculator | /Travel Agency.py | 476 | 3.796875 | 4 | print(" F A R E C A L C U L A T O R ")
a = int(input("Enter Distance: "))
b = int(input("Enter no of Children: "))
c = int(input("Enter no of adults: "))
if a>=1000 :
Fare = 500
TF = c*500 + b*250
print("Total Fare: ",TF)
if a<500 :
Fare2 = 200
TF2 = c*200 + b*100
print("Total Fare: ",TF2 )
if 500<a<=999 :
TF3 = c*300 + b*150
print("Fare: ",TF3)
print(" T H A N K Y O U ! ")
|
aad1ed452a09af623ace7e24b40ead14f96baa09 | ShimSooChang/exercicosdepython6 | /1.py | 257 | 4.09375 | 4 | numero_1=int(input("entre com o primeiro numero:"))
numero_2=int(input("entre com o segundo numero:"))
numero_3=int(input("entre com o terceiro numero:"))
soma= numero_1 + numero_2 + numero_3
quadrado= soma * soma
print("o quadrado da soma é:" ,quadrado) |
a329bdb126ec4caaec57fec32dc392259d6a660a | fywest/python | /shiyanlou_python3/student_teacher.py | 1,927 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
from collections import Counter
class Person(object):
def __init__(self, name):
self.name = name
def get_details(self):
return self.name
def get_grade(self, grade):
print(grade)
class Student(Person):
def __init__(self, name, branch, year):
Person.__init__(self, name)
self.branch = branch
self.year = year
def get_details(self):
return "{} studies {} and is in {} year.".format(self.name, self.branch, self.year)
def get_grade(self, grade):
c = Counter(grade)
grade_list = c.most_common(4)
num_pass, num_fail = 0, 0
for i, pari in enumerate(grade_list):
if pari[0] in ['A', 'B', 'C']:
num_pass += pari[1]
else:
num_fail += pari[1]
print("pass: {},fail: {}".format(num_pass, num_fail))
class Teacher(Person):
def __init__(self, name, papers):
Person.__init__(self, name)
self.papers = papers
def get_details(self):
return "{} teaches {}".format(self.name, ','.join(self.papers))
def get_grade(self, grade):
c = Counter(grade)
grade_list = c.most_common(4)
list_len = len(grade_list)
for i, pari in enumerate(grade_list):
if i != list_len - 1:
print("{}: {}, ".format(pari[0], pari[1]), end='')
else:
print("{}: {}".format(pari[0], pari[1]))
if __name__ == '__main__':
person1 = Person('Sachin')
student1 = Student('Kushal', 'CSE', 2005)
teacher1 = Teacher('Prashad', ['C', 'C++'])
if len(sys.argv) < 4:
print("check command")
exit(-1)
role = sys.argv[3].lower()
grade_input = sys.argv[4].upper()
if role == 'teacher':
teacher1.get_grade(grade_input)
elif role == 'student':
student1.get_grade(grade_input)
|
3dd8c047c87c0b27781ed3c578bddf2f82287635 | white812/tools | /deeplink/Lib/generate_func/base_class.py | 1,752 | 4.25 | 4 |
INDENT = ' '
class FuncLine(object):
__doc__ = """
This file is aimed to provide basic function line as an object.
Generate() is able to return a function line with indent choosen
"""
def __init__(self, content='', next_indent_level_change=0, indent_level=-1):
__doc__ = """
next_indent_level_change is used to control next line's additional indent
indent_level is used to control current line's indent with respect to function starting line
indent level is currently not in use."""
self.content = content
self.next_indent_level_change = next_indent_level_change
self.indent_level = indent_level
def generate(self, current_level):
if current_level<0: raise ValueError
return INDENT*(current_level) + self.content + '\n'
class Func(object):
__doc__ = """
This class is the basics for function auto-creation
It involves header() to create function line
It involves body() to create function body
It will generate function line with proper indent.
"""
def __init__(self, func_def_indent_level=0):
self.func_def_indent_level = func_def_indent_level
self.func_lines = []
def add(self, new_line):
self.func_lines.append(new_line)
def generate_function(self):
content = ''
start = self.func_def_indent_level
for func_line in self.func_lines:
if func_line.indent_level<0:
content += func_line.generate(start)
start += func_line.next_indent_level_change
else:
start = func_line.indent_level
content += func_line.generate(start+self.func_def_indent_level)
return content |
d509415e805166bbb1ca0a932fc52642a514321a | AlonsoCerpa/Tipos-de-Ordenamiento | /OrdBurbQuicksort.py | 1,040 | 3.671875 | 4 | def ordBurbuja(lista):
a = len(lista)
b = True
while b:
b = False
for i in range(0,a - 1):
if lista[i] > lista[i+1]:
x = lista[i]
lista[i] = lista[i+1]
lista[i+1] = x
b = True
a = a - 1
return lista
def particion(sublista,primero,ultimo):
indexPivote = primero
valorPivote = sublista[indexPivote]
temp = sublista[indexPivote]
sublista[indexPivote] = sublista[ultimo]
sublista[ultimo] = temp
index = primero
for i in range(primero, ultimo):
if sublista[i] < valorPivote:
temp1 = sublista[i]
sublista[i] = sublista[index]
sublista[index] = temp1
index = index + 1
temp2 = sublista[index]
sublista[index] = sublista[ultimo]
sublista[ultimo] = temp2
return index
def quickSort(lista,inicio,fin):
if inicio < fin:
p = particion(lista,inicio,fin)
quickSort(lista,inicio,p-1)
quickSort(lista,p+1,fin)
|
b0838c59349b32aa80c8b15ce4eccb8011982ffc | Alinda-Azzahra/POSTTEST | /percabangan.py | 2,061 | 3.765625 | 4 | #Program Percabangan
import os
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
print("*" * 50)
print("\t\t SELAMAT DATANG\n")
print("\t\tTAKOYAKI ENAK LOH")
print("*" * 50)
beli = str(input("Apakah anda ingin membeli takoyaki?"))
def varian():
clear_screen()
print("~" * 30)
print("\t Silahkan Pilih")
print("~" * 30)
print("1. Varian 1: Rp 2000/pcs")
print("2. Varian 2: Rp 2500/pcs")
print("3. Tidak jadi")
pilih = input("Pilih Varian>>> ")
if(pilih == "1"):
varian_satu()
elif(pilih == "2"):
varian_dua()
elif(pilih == "3"):
clear_screen()
print("*" * 41)
print("Terimakasih, silahkan datang kembali ^_^")
print("*" * 41)
exit()
else:
print("Varian yang kamu pilih tidak ada")
back_to_menu()
def back_to_menu():
print("\n")
input("Tekan Enter Untuk Kembali...")
varian()
def varian_satu():
clear_screen()
print("~" * 28)
print("\t Varian 1")
print("~" * 28)
jumlah = int(input("Jumlah pesanan: "))
bayar = int(jumlah) * 2000
if int(jumlah) >= 10:
print("Selamat karena anda membeli takoyaki >= 10 pcs, anda mendapatkan diskon 10%!!!")
diskon = int(jumlah) * 2000 * 10/100
bayar = diskon
print("Total yang harus dibayar: Rp %s" %bayar)
print("Terimakasih, Silahkan datang kembali ^_^")
exit()
def varian_dua():
clear_screen()
print("~" * 28)
print("\t Varian 2")
print("~" * 28)
jumlah = int(input("Jumlah pesanan: "))
bayar = jumlah * 2500
if int(jumlah) >= 8:
print("Selamat karena anda membeli takoyaki >= 8 pcs, anda mendapatkan diskon 8%!!!")
diskon = int(jumlah) * 2500 * 8/100
bayar = diskon
print("Total yang harus dibayar: Rp %s" %bayar)
print("Terimakasih, Silahkan datang kembali ^_^")
exit()
if __name__ == "__main__":
while True:
varian() |
8dd0f231a9708c0ea83eba1710a22b8c7f46b29f | kailash-manasarovar/A-Level-CS-code | /algorithms/binary_search.py | 2,155 | 4.125 | 4 | # BINARY SEARCH
# input - list, value to search for
# algorithm
# output - boolean
# PREREQUISITE: list has to be in order!!
# Big O (worst case scenario runtime) of Binary Search = log n
# list has n items
# _ _ _ _ _ _
# _ _ _
# _
# _ _ _ _ _ _
# _ _ _
# _
#import time
def binary_search(list_of_elements, item):
# debug, print out trace table
#print("TRACE TABLE")
#print(list_of_elements[:])
first = 0
last = len(list_of_elements) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
#print(mid)
if list_of_elements[mid] == item:
found = True
else:
if item < list_of_elements[mid]:
last = mid - 1
else:
first = mid + 1
# debug, print out trace table
# print(list_of_elements[first:last])
return found
## A Level mock question test
my_list = ["Adam", "Alex", "Anna", "Hon", "Mohammed", "Moonis", "Niraj", "Philip", "Punit", "Ravi", "Richard", "Timothy", "Tushara", "Uzair", "Zara"]
#print(binary_search(my_list, "Richard"))
# def recursive_binary_search(list_of_elements, item):
#
# if len(list_of_elements) == 0:
# return False
# else:
# mid = len(list_of_elements) // 2
#
# if list_of_elements[mid] == item:
# return True
# else:
# if item < list_of_elements[mid]:
# return recursive_binary_search(list_of_elements[:mid], item)
# else:
# return recursive_binary_search(list_of_elements[mid + 1:], item)
# import random as r
# randomlist = []
# for i in range(0,100000000):
# n = r.randint(1,10000000)
# randomlist.append(n)
# #print(randomlist)
#
# start = time.time()
# is_found = binary_search(randomlist, 300)
# end = time.time()
# time_took = end - start
# rounded_time = round(time_took,5)
#
#
# if is_found:
# print("Your item is in the list.")
# else:
# print("Your item is not in the list.")
#
# print("It took in seconds: {:0.5f} ".format(rounded_time))
# print(binary_search([1,2,3,5,8], 5))
# print(binary_search(['a','c','d','e','f'],'c')) |
fe50cc22f8ad59b0106a003c653f3edb5e3805b9 | jkaalexkei/TrabajosEnPython | /ejemplos/manejodearrays.py | 337 | 3.875 | 4 | def selectionSort(array):
for i in range(len(array)-1):
min_idx = i
for idx in range(i+1,len(array)-1):
if array[idx]<array[min_idx]:
min_idx = idx
array[i],array[min_idx] = array[min_idx],array[i]
return array
lista = [1,2,3,4,True]
print(selectionSort(lista)) |
d1a9268efc0d6de57ff9023b5761d5a0b9b5e1ca | knrastogi/PythonPrograms | /EndTermLabExamSol/CA/mymath.py | 721 | 4.34375 | 4 | def square(n):
'''
A function to return the square of a number.
'''
return n**2
def cube(n):
'''
A function to return the cube of a number.
Usage: cube()
'''
return n**3
def power(a,n):
'''
A function to calculate power of n to a
'''
return a**n
def sqrt(n):
'''
A function that calculates sqrt
'''
return n**(1/2)
def cubert(n):
'''
A function that calculates cubre root
'''
return n**(1/3)
def nthroot(n,m):
'''
A function that finds nth root of a number.
'''
return n**(1/m)
PI = 3.1415 # a constant PI with value 3.1415
e = 2.71 # a constant e with value 2.71
|
07d6d20fe97f18b7524621dcbd9b369b10d7890f | Eric-cv/QF_Python | /day5/test.py | 350 | 3.75 | 4 | '''
break continue 跳转语句
'''
# 方式一
sum = 0
for i in range(10):
if i%3 != 0:
sum += i
print('sum---111',sum)
# 方式二
sum = 0
for i in range(10):
if i%3 == 0:
# pass 占位符
# break 跳出循环
continue # 跳过循环体中continue下方的语句不执行,直接执行下一次循环
sum += i
print('sum---222',sum)
|
accd0244e45445ded5d5ea0ac6e2e2cd96178045 | Man0j-kumar/python | /areaofcircle.py | 101 | 4.21875 | 4 | r=float(input("enter the radius of circle"))
pi=3.14
area=pi*r*r
print("area of circle is",area)
|
be8a85adf79d3a40f4ad3f005239bbc199565d47 | ZDawang/leetcode | /144_Binary_Tree_Preorder_Traversal.py | 1,971 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#author : zhangdawang
#data: 2017-12
#difficulty degree:
#problem: 144_Binary_Tree_Preorder_Traversal
#time_complecity:
#space_complecity:
#beats:
class Solution(object):
#递归
def preorderTraversal(self, root):
def dfs(node, res):
res.append(node.val)
if node.left: dfs(node.left, res)
if node.right: dfs(node.right, res)
if not root: return []
res = []
dfs(root, res)
return res
#迭代
def preorderTraversal2(self, root):
stack = []
res = []
while stack or root:
while root:
res.append(root.val)
stack.append(root)
root = root.left
root = stack.pop()
root = root.right
return res
#迭代2
def preorderTraversal3(self, root):
if not root: return []
stack, res = [root], []
while stack:
root = stack.pop()
res.append(root.val)
if root.right: stack.append(root.right)
if root.left: stack.append(root.left)
return res
def preorderTraversal4(self, root):
#前驱节点与当前节点
pre, cur = None, root
res = []
while cur:
#左孩子为空,输出当前节点,并转右孩子
if not cur.left:
res.append(cur.val)
cur = cur.right
else:
#寻找前驱节点
pre = cur.left
while pre.right and pre.right != cur:
pre = pre.right
#若前驱节点右孩子为空
if not pre.right:
pre.right = cur
res.append(cur.val)
cur = cur.left
else:
pre.right = None
cur = cur.right
return res
|
4437c504e3e7b77cd81662adc6d252251c20e3c9 | MoreiraMatheus/Projetos_curso_em_video | /desafio 036.py | 506 | 3.765625 | 4 | casa = float(input('me diga o valor da casa: '))
salario = float(input('me diga seu salário: '))
anos = int(input('me diga em quantos anos você pretende pagar a casa: '))
prest = casa/(anos*12)
print('o valor da casa será: \033[32mR${:.2f}\033[m, em parcelas de'.format(casa), end=' ')
print('\033[32mR${:.2f}\033[m por mês a cada \033[34m{}\033[m anos'.format(prest, anos))
if salario * 0.3 >= prest:
print('emprestimo \033[32mAPROVADO\033[m!')
else:
print('emprestimo \033[31mNEGADO\033[m!')
|
9267b15177e70556de8c9bcdfee63815e4121886 | Celot1979/liga | /Jugadores.py | 1,811 | 3.5625 | 4 | import csv
jugador = {}
jugador_Segunda = {}
jugador_SegundaB = {}
def archivo_primero():
with open("jugador_uno.csv", "w") as csv_file:
write = csv.writer(csv_file)
for key, value in jugador.items():
write.writerow([key, value])
def archivo_segundo():
with open("jugador_dos.csv", "w") as csv_file:
write = csv.writer(csv_file)
for key, value in jugador_Segunda.items():
write.writerow([Key, value])
#------------------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------------------
def gestionar_jugadores():
j = str(input("¿De qué categoría quieres gestionar la plantilla?\n1.Primera División\n2.Segunda División"
"\n3.SegundaB División\n==>"))
if j == "1":
nombre = str(input("\nNombre del Jugador: "))
edad = str(input("Edad: "))
posicion = str(input("Posicion: "))
nacionalidad = str(input("Nacionalidad: "))
jugador[nombre]=edad, posicion, nacionalidad
archivo_primero()
elif j == "2":
nombre = str(input("Nombre del Jugador: "))
edad = str(input("Edad: "))
posicion = str(input("Posicion: "))
nacionalidad = str(input("Nacionalidad: "))
jugador_S[nombre] = edad, posicion, nacionalidad
elif j == "3":
nombre = str(input("Nombre del Jugador: "))
edad = str(input("Edad: "))
posicion = str(input("Posicion: "))
nacionalidad = str(input("Nacionalidad: "))
jugador_B[nombre] = edad, posicion, nacionalidad
|
76c20ab1595d91c77539117f16b7b6f3f456dd76 | multiscripter/python | /wikibooks/ch12_07_stdlib_array.py | 535 | 3.984375 | 4 | from array import array # Эффективные массивы числовых значений.
# https://docs.python.org/3/library/array.html
arr = array('i', [1, 2, 3, 4, 5, 6]) # Создаёт экземпляр класса Array типа int.
print('arr.itemsize:', arr.itemsize) # Размер одного элемнета массива в байтах.
arr.append(10)
# array.count(x)
# Вернуть количество вхождений x в массиве.
print('arr.count(5)', arr.count(5)) # 1
print(arr[5]) # 6 |
6b16b04a69f3421e84af32931be6d98b70848cb3 | mukeshkumarsahani/Python-for-Beginner | /Python/Function.py | 933 | 4.09375 | 4 | '''
Keyword ---> def
Syntax ---> def function-Name():
## Body
calling ---> function-Name()
'''
def First():
print("Hello Mukesh!")
# ending function
print("Top")
First() # Function is calling
print("Bottom") # Top
# Hello Mukesh!
# Bottom
def mks(name):
print("Hello " + name)
mks("mukesh") # Hello mukesh
mks("Rakesh") # Hello Rakesh
def mks(name,age):
print("Hello " + name + ", You are "+ str(age))
mks("mukesh",23) # Hello mukesh, You are 23
mks("rakesh",20) # Hello rakesh, You are 20
# Using of 'Return' keyword
def cube(num):
return num*num*num
print(cube(3)) # 27
def cube(num):
return num*num*num
result = cube(3)
print(result) # 27
def cube(num):
return num*num*num
print("Code") # don't print code b/z 'return' is used like 'break' keyword
result = cube(3)
print(result) # 27
|
5286488c5904134801ec8d69ccb19ece283e6102 | superY-25/algorithm-learning | /src/algorithm/202003/countCharacters.py | 697 | 3.71875 | 4 |
class Solution:
def countCharacters(self, words: list, chars: str) -> int:
count = 0
for item in words:
temp = 0
temp_chars = chars
for c in item:
if c in temp_chars:
temp += 1
temp_chars.replace(c, '', 1)
if temp == len(item):
count += temp
return count
if __name__ == '__main__':
s = Solution()
words = ["dyiclysmffuhibgfvapygkorkqllqlvokosagyelotobicwcmebnpznjbirzrzsrtzjxhsfpiwyfhzyonmuabtlwin","ndqeyhhcquplmznwslewjzuyfgklssvkqxmqjpwhrshycmvrb","ulrrbpspyudncdlbkxkrqpivfftrggemkpyjl","boygirdlggnh","xmqohbyqwagkjzpyawsydmdaattthmuvjbzwpyopyafphx","nulvimegcsiwvhwuiyednoxpugfeimnnyeoczuzxgxbqjvegcxeqnjbwnbvowastqhojepisusvsidhqmszbrnynkyop","hiefuovybkpgzygprmndrkyspoiyapdwkxebgsmodhzpx","juldqdzeskpffaoqcyyxiqqowsalqumddcufhouhrskozhlmobiwzxnhdkidr","lnnvsdcrvzfmrvurucrzlfyigcycffpiuoo","oxgaskztzroxuntiwlfyufddl","tfspedteabxatkaypitjfkhkkigdwdkctqbczcugripkgcyfezpuklfqfcsccboarbfbjfrkxp","qnagrpfzlyrouolqquytwnwnsqnmuzphne","eeilfdaookieawrrbvtnqfzcricvhpiv","sisvsjzyrbdsjcwwygdnxcjhzhsxhpceqz","yhouqhjevqxtecomahbwoptzlkyvjexhzcbccusbjjdgcfzlkoqwiwue","hwxxighzvceaplsycajkhynkhzkwkouszwaiuzqcleyflqrxgjsvlegvupzqijbornbfwpefhxekgpuvgiyeudhncv","cpwcjwgbcquirnsazumgjjcltitmeyfaudbnbqhflvecjsupjmgwfbjo","teyygdmmyadppuopvqdodaczob","qaeowuwqsqffvibrtxnjnzvzuuonrkwpysyxvkijemmpdmtnqxwekbpfzs","qqxpxpmemkldghbmbyxpkwgkaykaerhmwwjonrhcsubchs"]
chars = "usdruypficfbpfbivlrhutcgvyjenlxzeovdyjtgvvfdjzcmikjraspdfp"
print(s.countCharacters(words, chars))
|
317f45348f7452d662102ac867f6c4da6e47571f | Hawk453/Project-Euler | /even fibonacci clever approach.py | 799 | 4.125 | 4 | #Each new term in the Fibonacci sequence is generated by adding the previous
#two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#By considering the terms in the Fibonacci sequence whose values do not
#exceed four million, find the sum of the even-valued terms.
#By Saksham Madan
#for computer with less computational power
n = 4000000
def Fibonacci(nterms):
# first two terms
result = 2
fib3 = 2
fib6 = 0
arr = []
while result < nterms:
arr.append(result)
result = 4*fib3 + fib6
fib6 = fib3
fib3 = result
return arr
arr = []
arr = Fibonacci(n)
sum = 0
for i in arr:
if i%2 == 0: #this step is redundant as the series generated is already even
sum = sum + i
print(sum)
|
6b9a791d54fee75423af97194a5a9c04ff81b93b | blitzbutter/MyCode | /netCalc.py | 1,718 | 4.25 | 4 | ### Jacob Bryant
### 12/8/2018
### Program to calculate the network address
# --- Takes a string to ask a user as input --- #
def calc_bin(user_in):
bin_f = "{0:08d}" # Pads binary numbers with 8 bytes
# --- Formats the input IP address and converts it to binary --- #
ip_in = input(user_in)
ip = ip_in.split('.')
ip_bin = ""
for i in range(0, len(ip)):
ip[i] = bin(int(ip[i])) # Converts it to binary
ip[i] = ip[i].replace('0b','') # Removes the leading '0b'
ip[i] = bin_f.format(int(ip[i])) # Formats the input to pad with eight zeroes
ip_bin += ip[i] # Adds it to the string of binary numbers
return ip_bin
# --- Ask the user for the IP and netmask --- #
ip_str = calc_bin("Enter IP: ")
net_str = calc_bin("Enter netmask: ")
# --- Lets the user know what operation is happening --- #
print("ANDing %s" % ip_str)
print(" %s" % net_str)
network_ip = "" # Network IP variable
# --- And each individual bit in the IP and netmask string of bits, then store in network_ip --- #
for i in range(0, len(ip_str)):
bit = int(ip_str[i]) & int(net_str[i]) # Ands each individual bit
network_ip += str(bit)
# --- Splits the string of bits into 4 parts, to convert back to their decimal counterparts --- #
n = 8
network_ip = [network_ip[i:i+n] for i in range(0, len(network_ip), n)]
# --- Converts back to decimal format and formats the output nicely --- #
network_ip_out = ""
for i in range(0, len(network_ip)):
network_ip_out += str(int(network_ip[i], 2))
if i != len(network_ip)-1:
network_ip_out += '.'
print("Network address is %s" % network_ip_out) # Prints the network IP
|
5885a848ed12b11b85465e2e63cae652fa547da2 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1/ghonyme/1.txt | 498 | 3.890625 | 4 |
#!/usr/bin/python
import sys
def isDigitInStr(digit,str):
return digit in str
def problem(number,res):
for i in range(0,10):
if str(i) not in res and isDigitInStr(str(i),number):
res.append(str(i))
return res
res = []
number = int(sys.argv[1])
number_tmp = number
if number == 0:
print "INSOMNIA"
else:
mul=1
while len(res) != 10:
problem(str(number_tmp),res)
mul = mul + 1
number_tmp = number * mul
print number_tmp - number
|
23a8e224e3b450a5603812bd276aa5f0b2f5bcb8 | DemetriosP/lp2-exercicios | /lista_1/exercicio_7.py | 335 | 3.921875 | 4 | distancia_quilometros = float(input("Informe a distancia percorrida pelo objeto em quilometro: "))
tempo_minutos = int(input("Informe o espaço em tempo em minutos: "))
velocidade_projetil = (distancia_quilometros * 100) / (tempo_minutos * 60)
print(f"A velocidade do projetil é de {round(velocidade_projetil)} metros por segundo")
|
9619eab19b6b41c8b723e79c4bc248c054e9714d | laffitto/test | /numpy_test.py | 888 | 3.625 | 4 | import numpy as np
# # 可以自动判断数据类型
# arr1 = np.array([2,3,4]) # 定义一个数组
# print(arr1)
# print(arr1.dtype)
#
# arr2 = np.array([1.2,2.3,3.4])
# print(arr2)
# print(arr2.dtype)
# # 实现列表的累加
# print(arr1+ arr2)
#
# print(arr2*10)
# # 定义二维数组(矩阵)
# data = [[1,2,3],[4,5,6]]
# arr3 = np.array(data)
# print(arr3)
# print(arr3.dtype)
# # 定义0矩阵
# print(np.zeros(10)) # 一维矩阵
# print(np.zeros((3,5))) # 定义3*5 的矩阵
#
# print(np.ones((4,6))) # 全为1 的矩阵
# # 将矩阵空置(但会填充随机值)
# print(np.empty((2,3,2))) # 三维矩阵
print(np.arange(10)) # 生成数组
arr4 = np.arange(10)
print(arr4[5:8]) # 切片操作
arr4[5:8] = 10 # 切片内容赋值
print(arr4)
# 赋值而不改变原有内容
arr_slice = arr4[5:8].copy() # 添加副本
arr_slice[:]= 15
print(arr_slice)
print(arr4) |
016386f97f0cbf7ee1826415f878c47c439df51b | elfeasto/house-price-models | /ML_Models/Parametric models/Simple Linear/sqft_living_Linear.py | 697 | 3.671875 | 4 | """
Simple linear regession using one feature(sqft_living)
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import tools
from project_tools import *
# load train data
train_data, test_data = get_train_test_data()
# pick feature
features = ["sqft_living"]
# fit our model
sqft_model = LinearRegression()
X = train_data[features]
y = train_data["price"]
sqft_model.fit(X, y)
# get test data r sq
X = tools.get_features_matrix(test_data, features)
y = test_data["price"]
test_r_sq = sqft_model.score(X,y)
print("Using simple linear regression on sqft_living we get")
print("Test r squared is:", np.round(test_r_sq,4))
|
79a807b684016008dc33ef4c0bbcfab9fefb1195 | Christopher102/IntroToProgramming-Labs | /extracredit/question7.py | 448 | 4.09375 | 4 | # Calculates babysitter pay
def main():
start = float(input("At what hour did you start? Input in HH:MM. " ))
Starttime = input("What this AM or PM?")
end = float(input("At what hour did you end? Input in HH:MM. "))
endtime = input("Was this AM or PM?")
if Starttime.lower() == "am":
print("You started at {} am.".format(start))
elif Starttime.lower() == "pm":
print("You started at {} pm.".format(start))
|
c518381f8e76ea3c266c15edeba999182e1cbe8c | justinh5/CipherBox | /Crypt0/Caesar/CEnDecode.py | 2,232 | 4.53125 | 5 |
def encode(plaintext, shift):
"""Encode plaintext
Encode the message with a given shift key. Offset each character
in the message by 'shift' number of letters in the alphabet
"""
ciphertext = ""
# shift each character
for x in plaintext:
if 97 <= ord(x) <= 122: # if character is alphabetic lowercase
ciphertext += chr((ord(x) - 97 + shift) % 26 + 97)
elif 65 <= ord(x) <= 90: # if character is alphabetic uppercase
ciphertext += chr((ord(x) - 65 + shift) % 26 + 65)
else: # non-alphabetic characters do not change
ciphertext += x
return ciphertext
def decode(ciphertext, shift, known):
"""Decode ciphertext
Decode the message in either of the cases where
the shift key is or is not known. A shift key that isn't known
will call the decode_all function to test all possible shifts.
"""
if not known:
return decode_all(ciphertext) # decode with all possibilities if shift key is unknown
plaintext = ""
for x in ciphertext:
if 97 <= ord(x) <= 122: # character is alphabetic lowercase
plaintext += chr((ord(x) - 97 - shift) % 26 + 97)
elif 65 <= ord(x) <= 90: # character is alphabetic uppercase
plaintext += chr((ord(x) - 65 - shift) % 26 + 65)
else: # non-alphabetic characters do not change
plaintext += x
return plaintext
def decode_all(ciphertext):
"""Decode ciphertext when shift key is unknown
All possible 25 shifts are attempted, each with a
different offset in the alphabet.
"""
plaintext = ""
for i in range(1, 26):
temp = ""
for x in ciphertext:
if 97 <= ord(x) <= 122: # character is alphabetic lowercase
temp += chr((ord(x) - 97 - i) % 26 + 97)
elif 65 <= ord(x) <= 90: # character is alphabetic uppercase
temp += chr((ord(x) - 65 - i) % 26 + 65)
else: # non-alphabetic characters do not change
temp += x
plaintext += "Shift " + str(i) + ": " + "\n" + temp + "\n\n"
return plaintext
|
dedf161447234f2f5e6507ff0cf4dfd097d47852 | penelopy/Hackbright_Classwork | /SkillsExercises/skills_wendy_version.py | 2,678 | 3.984375 | 4 | # Things you should be able to do.
number_list = [-5, 6, 4, 8, 15, 16, 23, 42, 2, 7]
word_list = [ "What", "about", "the", "Spam", "sausage", "spam", "spam", "bacon", "spam", "tomato", "and", "spam"]
# Write a function that takes a list of numbers and returns a new list with only the odd numbers.
def all_odd(number_list):
newlist = []
for num in number_list:
if num % 2 != 0:
newlist.append(num)
return newlist
# Write a function that takes a list of numbers and returns a new list with only the even numbers.
def all_even(number_list):
newlist = []
for num in number_list:
if num % 2 == 0:
newlist.append(num)
return newlist
# Write a function that takes a list of strings and a new list with all strings of length 4 or greater.
def long_words(word_list):
newlist = []
for word in word_list:
if len(word) >= 4:
newlist.append(word)
return newlist
# Write a function that finds the smallest element in a list of integers and returns it.
def smallest(number_list):
min = number_list[0]
for num in number_list:
if num < min:
min = num
return min
# Write a function that finds the largest element in a list of integers and returns it.
def largest(number_list):
max = number_list[0]
for num in number_list:
if num > max:
max = num
return max
# Write a function that takes a list of numbers and returns a new list of all those numbers divided by two.
def halvesies(number_list):
newlist = []
for num in number_list:
newlist.append(num/2.0)
return newlist
# Write a function that takes a list of words and returns a list of all the lengths of those words.
def word_lengths(word_list):
newlist = []
for word in word_list:
newlist.append(len(word))
return newlist
# Write a function (using iteration) that sums all the numbers in a list.
def sum_numbers(number_list):
sum = 0
for num in number_list:
sum += num
return sum
# Write a function that multiplies all the numbers in a list together.
def mult_numbers(number_list):
product = 1
for num in number_list:
product *= num
return product
# Write a function that joins all the strings in a list together (without using the join method) and
# returns a single string.
def join_strings(word_list):
newstring = ""
for word in word_list:
newstring += word
return newstring
# Write a function that takes a list of integers and returns the average (without using the avg method)
def average(number_list):
return sum_numbers(number_list) / float(len(number_list)) |
dee8e06ea937a6c4f83d42a98440535675743161 | RandhirJunior/Python | /Oops/Static_Variables.py | 3,424 | 4.375 | 4 | # If the value not varied from object to object ,such types of variable we have to declare at class level and such type of variable is called static variable.
# static variable:- For all objects a single copy maintained at class level.
class Student:
cname='IIT'
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
s1=Student('Ram',101)
s2=Student('Sayam',102)
print(s1.name,s1.rollno,Student.cname)
print(s2.name,s2.rollno,Student.cname)
# O/P :- Ram 101 IIT
# Sayam 102 IIT
# What are various places are there to declare static variables?.
#------------------------------------------------------------------------------
# 1. Within the class directly but from outside of any method
# 2. Inside constructor by using classname.
# 3. Inside instance metod by using classname.
# 4. Inside classmethod by using cls variable or classname
# 5. Inside staticmethod by using classname.
# 6. From outside of class by using classname.
class Test:
a=10
def __init__(self):
Test.b=20
def m1(self):
Test.c=30
@classmethod
def m2(cls):
cls.d=40
Test.e=50
@staticmethod
def m3():
Test.f=60
t=Test()
t.m1()
Test.m2()
Test.m3()
Test.g=70
print(Test.__dict__) # It will print only class level static variables i.e a and g
# How to access static variables:-
#-------------------------------------------------------------------------
# We can access static variables either by classname or by object reference.
#
# Within the class
#--------------------
# classname,self,cls
#
# Outside of the class:
#-------------------------------
# object reference,classname
#Examples 1:
class Test:
a=10
def __init__(self):
print('Inside constructor')
print(Test.a)
print(self.a)
def m1(self):
print('Inside instance method')
print(Test.a)
print(self.a)
@classmethod
def m2(cls):
print('Inside class method')
print(Test.a)
print(cls.a)
@staticmethod
def m3():
print('Inside sttatic method')
print(Test.a)
t=Test()
t.m1()
t.m2()
t.m3()
print('From outside of the class')
print(Test.a)
print(t.a)
#------------------------------------------------------------------------------------
# How to modify static variables:-
#-------------------------------------------------------------------------------------
# 1. Within the class we should use classname,cls variables.
# 2. From outside of the class: only classname.
# Example:-
class Test:
a=10
def __init__(self):
self.a=20
t=Test()
print(Test.a) # It call static variable i.e a=10
print(t.a) # here it calls instance variable i.e a=20
# Example:-
class Test:
a=10
def __init__(self):
Test.a=20
@classmethod
def m1(cls):
cls.a=30
Test.a=40
@staticmethod
def m2():
Test.a=50
t=Test()
t.m1()
t.m2()
Test.a=60 # From outside of the class
print(Test.a)
print(t.a)
# How to delete static variable:-
#-----------------------------------------------------------
# within the class we should use classname,cls variables
# From outside of the class: only classname
# Example:-
class Test:
a=10
def m1(self):
del Test.a
print(Test.__dict__)
t=Test()
print(Test.__dict__)
|
00fd23048aa3d9c7384099b1dbf6e2c28a66c6ac | Jenionthenet/Week-2 | /Day-3/remove_duplicate.py | 544 | 3.609375 | 4 | with open("emails.txt") as file:
emails = file.read()
split_emails = emails.split(',')
#print(split_emails)
#emails_arr = split_emails
dup_arr = []
unique_arr = []
for email in split_emails:
if email not in unique_arr:
unique_arr.append(email)
if email in unique_arr:
dup_arr.append(email)
print(unique_arr)
with open('unitq_emails.txt', 'a') as file:
for email in unique_arr:
file.write(email)
file.write("\n")
|
7289c9b37fa3cc91ba4e68f3ed45d1e765aa5df4 | aditya-doshatti/Leetcode | /largest_time_for_given_digits_949.py | 1,041 | 3.890625 | 4 | '''
949. Largest Time for Given Digits
Easy
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time can be made, return an empty string.
Example 1:
Input: [1,2,3,4]
Output: "23:41"
https://leetcode.com/problems/largest-time-for-given-digits/
'''
class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
retVal = ''
for i, a in enumerate(A):
for j, b in enumerate(A):
for k, c in enumerate(A):
if i == j or i == k or j == k:
continue
hour, minute = str(a) + str(b), str(c) + str(A[6 - i - j - k])
if hour < '24' and minute < '60':
print(hour, minute)
retVal = max(retVal, hour + ':' + minute)
return retVal
|
758c89716ac881741456e162191363c8e742080f | b1ueskydragon/PythonGround | /leetcode/p0048/test_rotate.py | 1,127 | 3.734375 | 4 | import unittest
from leetcode.p0048.solve01 import Solution as A
class RotateTest(unittest.TestCase):
def test_rotate_2x2(self):
a = A()
matrix = [
[1, 2],
[4, 5]
]
expected = [
[4, 1],
[5, 2]
]
a.rotate(matrix) # in-place
self.assertEqual(expected, matrix)
def test_rotate_3x3(self):
a = A()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
a.rotate(matrix)
self.assertEqual(expected, matrix)
def test_rotate_4x4(self):
a = A()
matrix = [
[5, 1, 9, 11],
[2, 4, 8, 10],
[13, 3, 6, 7],
[15, 14, 12, 16]
]
expected = [
[15, 13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7, 10, 11]
]
a.rotate(matrix)
self.assertEqual(expected, matrix)
if __name__ == '__main__':
unittest.main()
|
5617bd4bcc3351ac9f7508e016c0152cf1b4b162 | ymirthor/hr-forritun | /PC/midterm1.py | 74 | 3.671875 | 4 | n=int(input("Number of stars: "))
for i in range(1,n+1): print("*"*i)
|
68b0bac24e3007c876266e1df14c4d141d509618 | TejaswitaW/DataScienceMachineLearningCourse | /12_day/factorial_number.py | 310 | 4.0625 | 4 | #facto_number = 1
def facto(number):
if number == 1:
return number
else:
return number*facto(number-1)
# return facto_number
number = int(input("Enter the number, to find factorial : "))
facto_number = facto(number)
print("Factorial of number is : ", facto_number)
|
b9bd9fb1a2b056b07dd1b860212076783ad39ab7 | Maheboopathy/FST-M1 | /Python/Activities/activity4.py | 1,339 | 4.15625 | 4 | #Get the user names
user1=input("What is Player1's name:")
user2=input("What is Player2's name:")
#looping endlessly
while True:
#Ask user's answers
user1_answer = input(user1 +", do you want to choose rock, paper or scissors?").lower()
user2_answer = input(user2 +", do you want to choose rock, paper or scissors?").lower()
#run the algorithm
if user1_answer==user2_answer:
print("Its a tie!!")
elif user1_answer == 'rock':
if user2_answer == 'scissors':
print("rock wins!!")
else:
print("paper wins!!")
elif user1_answer == 'scissors':
if user2_answer =='paper':
print("scissors wins!!")
else:
print("rock wins!!")
elif user1_answer == 'paper':
if user2_answer == 'rock':
print("paper wins!!")
else: print("scissors wins!!")
else: print("Invalid input! You have not entered rock, paper, scissors, try again")
#Ask them if they want to play again
repeat = input("Do you want to play another round? Yes/No: ").lower()
#if they say yes
if (repeat=="yes"):
pass
#if they say no
elif (repeat=="no"):
raise SystemExit
#if they say anything exit with an error message
else:
print("you entered an invalid option. Exiting now")
raise SystemExit |
e29c2870e0313c7f02cf4e00f3425f233a77ac17 | michalrom089/PythonCourse-ex | /04_exceptions/4_1_basics/00-basic.py | 234 | 3.53125 | 4 | def div(a, b):
if b == 0:
raise Exception('dividing by 0')
return a/b
if __name__ == '__main__':
try:
result = div(2, 0)
except Exception as e:
print(str(e))
print('End of thre program')
|
5168be409b78274bde4c321b644bbf7f615e1a43 | ELOISESOULIER/acterrea | /descriptor_model.py | 5,591 | 3.796875 | 4 | """ Model to load the data, compute the Y variable to predict and the descriptors """
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def plot_two_scales_y(plot1, plot2, title='', x_label='', y_label1='', y_label2='', label1='', label2=''):
""" Plot two curves with different Y-axis """
fig, ax1 = plt.subplots()
ax1.set_xlabel(x_label)
ax1.set_ylabel(y_label1)
ax1.plot(plot1, color='b', label=label1)
ax1.legend()
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.set_ylabel(y_label2) # we already handled the x-label with ax1
ax2.plot(plot2, color='r', label=label2)
ax2.legend()
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.title(title)
plt.show()
class DescriptorModel():
""" Model to load the data, compute the Y variable to predict and the descriptors """
def __init__(self, data_file):
self.df = pd.read_csv(data_file)
self.T, self.nb_sim = np.shape(self.df)
self.nb_sim -= 1
print("{} simulations with {} values loaded".format(self.nb_sim, self.T))
self.variables = [col for col in list(self.df.columns) if 'V' in col]
def plot_some_simulations(self, nb=20):
plt.figure()
for col in self.variables[:nb]:
plt.plot(self.df[col])
plt.title('Evolution on {} simulations'.format(nb))
plt.xlabel('time')
plt.show()
def process_var(self, params):
""" Compute Y variable to be predicted """
self.params = params
# Concatenate x variable, and compute the cumulative mean
X = []
trajec = []
X_cummean = []
for j in range(len(self.variables)):
col = self.variables[j]
X += list(self.df[col])
trajec += [j for _ in range(len(self.df))] # Trajec = the number of the trajectory
# CumMean of X (t-1 previous values)
cummean = np.cumsum(self.df[col]) / np.array(range(1, len(self.df) + 1))
X_cummean += [self.df[col][0]] + list(cummean[:-1])
self.data = pd.DataFrame({'X': X, 'trajec': trajec, 'X_cummean': X_cummean})
# Compute Y
self.data['X_diff'] = abs(self.data['X'] - self.data['X_cummean'])
# The difference between X and the cummean is it below the threshold thres_mean ?
self.data['Y1'] = self.data['X_diff'].apply(lambda x: 1 if x > params['thres_mean'] else 0)
# The value of X is it below the general threshold thres_gal ?
self.data['Y2'] = self.data['X'].apply(lambda x: 1 if abs(x - params['X0_base']) > params['thres_gal'] else 0)
# The incident happens if one of the two previous event happen
self.data['Y'] = self.data['Y1'] + self.data['Y2']
self.data['Y'] = self.data['Y'].apply(lambda x: 1 if x > 0 else 0)
def compute_descriptors(self, tau, len_X):
"""Separate data x in windows of lenght len_X
and compute descriptors on this window """
self.tau = tau
self.len_X = len_X
try:
self.data
except:
print("First process the variables using the function 'process_var' with parameters")
descriptors = {'X': [], 'Y': [], 'trajec': [], 'Y_to_predict': [],
'mean': [],
'diff_to_mean': [],
'diff_first_second_mean': [],
'diff_to_X0': [],
'actual_evolution': [], 'past_evolution': [], 'mean_past_evolution': []}
for i in range(1, len_X + 1):
descriptors['X_{}'.format(i)] = []
for n in range(self.nb_sim):
for j in range(len_X, self.T - tau):
i = n*self.T + j
X_ = list(self.data['X'][i - len_X:i]) # Past
descriptors['X'].append(self.data['X'][i])
descriptors['Y'].append(self.data['Y'][i])
descriptors['Y_to_predict'].append(self.data['Y'][i + tau])
descriptors['trajec'].append(self.data['trajec'][i])
descriptors['mean'].append(np.mean(X_))
descriptors['diff_to_mean'].append(np.abs(self.data['X'][i] - np.mean(X_)))
descriptors['diff_first_second_mean'].append(np.abs(np.mean(X_[:int(len_X/2)])\
- np.mean(X_[int(len_X/2):])))
descriptors['diff_to_X0'].append(np.abs(np.mean(X_) - self.params['X0_base']))
descriptors['actual_evolution'].append(self.data['X'][i] - self.data['X'][i-1])
past_evolution = [X_[k] - X_[k-1] for k in range(1, len(X_))]
descriptors['past_evolution'].append(past_evolution)
descriptors['mean_past_evolution'].append(np.mean(past_evolution))
# Past values
for k in range(1, len_X + 1):
descriptors['X_{}'.format(k)].append((self.data['X'][i - k]))
self.descriptors = pd.DataFrame(descriptors)
self.name_descriptors = list(descriptors.keys())
self.name_descriptors.remove('X')
self.name_descriptors.remove('Y')
self.name_descriptors.remove('trajec')
self.name_descriptors.remove('Y_to_predict')
print("The descriptors computed are:", self.name_descriptors)
print("{} trajectories of length {}".format(self.nb_sim, self.T)) |
556fe27d50b1c0b3104aff7e56982282fe2707c0 | v2krishna/PythonRoutines | /06_ControlStatements/09_NestedForLoops.py | 149 | 4.03125 | 4 | """
Using the nested for loops
"""
for i in range(0,3):
for j in range(0,4):
print("i= ", i, "\t", "j = ", j)
print("End of the program") |
a6389f0dd28bd9991403a6662a7ce3cd99b2e2b0 | pinky0916/python_Basics | /Handson_Exercise/f_Tuple_unpacking.py | 544 | 4.15625 | 4 |
def emp_month(list1):
max_hrs=0
min_hrs=0
for name,no_of_hours in list1:
print(name,no_of_hours)
if max_hrs<no_of_hours:
max_hrs=no_of_hours
emp_month=name
else:
min_hours=no_of_hours
worst_emp=name
return (emp_month,max_hrs,worst_emp,min_hours)
list1 = [('Abby',10),('Billy',3),('Cathy',500),('D',5)]
x,y,a,b=emp_month(list1)
print(f'Employee of the month is {x} has {y} hours worked ')
print(f'Worst employee of the month is {a} has {b} hours worked ') |
7a362edad6c89eca2840fba9910f600ec568e884 | fatezy/Algorithm | /offer2/43LeftRotateString.py | 677 | 4.09375 | 4 | # 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串
# 模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列
# 输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果
# ,即“XYZdefabc”。是不是很简单?OK,搞定它!
class Solution:
def LeftRotateString(self, s, n):
if not s:
return ""
s = list(s)
s[0:len(s)-n],s[len(s)-n:len(s)] = s[n:len(s)],s[0:n]
return "".join(s)
if __name__ == '__main__':
print(Solution().LeftRotateString("abcXYZdef", 3)) |
1acc058ac820f28cd05741abacda589acf4da145 | Izardo/my-work | /Topic_6_functions/pop.py | 153 | 3.921875 | 4 | # This program creates a list and pops of the item at index 1
# Author: Isabella
list = [1, 2, 3]
a, b, c = list
list.pop(1)
print(list)
print(a, b, c) |
8ed2e63fc5698bd5d687bdc87531b9496a532ac7 | dmcdekker/interview-and-coding-problems | /easy-python-problems/python_problems_3.py | 5,879 | 4.3125 | 4 | #reverse_digits
#pair_product
#slice_between_vowels
#array_times_two (don't modify array)
#array_times_twoo (modify array)
#redact_five_letter_words
#largest_pair
#boolean_to_binary
#third_largest
#time_conversion
##################### Reverse Digits ###################
'''
>>> reverse_digits(5)
[5, 4, 3, 2, 1]
>>> reverse_digits(10)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> reverse_digits(1)
[1]
'''
def reverse_digits(number):
'''Define a method that reverses the digits of its argument and
returns the resulting list of numbers'''
rev_lst = []
for num in range(1, number + 1):
rev_lst.append(num)
return rev_lst[::-1]
##################### Pair Product ###################
'''
>>> pair_product([3, 1, 5], 15)
True
>>> pair_product([4, 1, 5], 20)
True
>>> pair_product([5, 5, 2], 30)
False
'''
def pair_product(arr, target_product):
'''Define a method, that accepts two arguments:
a list of integers and a target_product (an integer).
The method returns a boolean indicating whether any pair
of elements in the array multiplied together equals that product'''
for idx1 in range(0, len(arr)):
for idx2 in range(1, len(arr)):
if arr[idx1] * arr[idx2] == target_product:
return True
return False
##################### Slice Between Vowels ###################
'''
>>> slice_between_vowels('serendipity')
'rendip'
>>> slice_between_vowels('train')
''
>>> slice_between_vowels('dog')
''
>>> slice_between_vowels('refrain')
'fr'
'''
def slice_between_vowels(word):
'''Return the slice of the word between the first and last vowels of that word. Return an empty string if the word has less than 2 vowels'''
vowels = ('a', 'e', 'i', 'o', 'u')
first_idx = 0
last_idx = -1
for letter in word.split():
if letter in vowels:
word[first_idx]
word[last_idx]
first_idx += 1
last_idx -= 1
return word[first_idx + 1: last_idx - 1]
##################### Array Times Two ###################
'''
>>> array_times_two([2, 3, 4])
[4, 6, 8]
>>> array_times_two([15, 22, 34])
[30, 44, 68]
'''
def array_times_two(lst):
'''Given an array of numbers, returns another array with each of the argument's numbers multiplied by two. Do not modify the original array'''
lst_times_two = []
for num in lst:
lst_times_two.append(num * 2)
return lst_times_two
##################### Array Times Twoo ###################
'''
>>> array_times_twoo([2, 3, 4])
[4, 6, 8]
>>> array_times_twoo([15, 22, 34])
[30, 44, 68]
'''
def array_times_twoo(lst):
'''given an array of numbers, mulitplies each of its elements by two. This SHOULD mutate the original array'''
for idx, num in enumerate(lst):
lst[idx] = num * 2
return lst
##################### Redact 5 letter word ###################
'''
>>> redact_five_letter_words('long longer longest longy')
'long longer longest #####'
>>> redact_five_letter_words('denis hello world')
'##### ##### #####'
'''
def redact_five_letter_words(string):
'''Define a method that substitutes all five-letter words in its argument with "#####" and returns the result. Do not consider punctuation.'''
new_str = []
for word in string.split():
if len(word) == 5:
new_str.append('#####')
else:
new_str.append(word)
return ' '.join(new_str)
##################### Largest Pair ###################
'''
>>> largest_pair([[-4, 0],[-2,-1],[-3,2]])
[-3, 2]
>>> largest_pair([[4, 0],[2,-1],[-3,-2]])
[4, 0]
>>> largest_pair([[1, 0]])
[1, 0]
'''
def largest_pair(pairs_lst):
largest = pairs_lst[0]
for pair in pairs_lst:
if (largest[0], largest[1]) < (pair[0], pair[1]):
largest = pairs_lst[pair[0] + pair[1]]
return largest
##################### Boolean to Binary ###################
'''
>>> boolean_to_binary([True])
'1'
>>> boolean_to_binary([True, False, True])
'101'
>>> boolean_to_binary([False, False, True, False])
'0010'
'''
def boolean_to_binary(boolean_lst):
'''Define a method that accepts an array of booleans as an argument. Your method should convert the array into a string of 1's (for true values) and 0's (for false values) and return the result'''
binary_string = ''
for boolean in boolean_lst:
if boolean == True:
binary_string += '1'
elif boolean == False:
binary_string += '0'
return binary_string
##################### Third Largest ###################
'''
>>> third_largest([5, 9, 9, 3, 7, 7, 2, 10])
7
>>> third_largest([5, 10, 3])
3
'''
'''
>>> third_largest([5, 9, 9, 3, 7, 7, 2, 10])
7
>>> third_largest([5, 10, 3])
3
'''
from operator import itemgetter
def third_largest(lst):
'''Define a method that returns the third-largest element in an array (assume at least 3 elems)'''
nums_dict = {}
for num in lst:
nums_dict[num] = nums_dict.get(num, 0) + 1
sorted_dict = sorted(nums_dict.items())[-3][0]
return sorted_dict
##################### Date TIme Conversion ###################
'''
>>> time_conversion(60)
'01:00'
>>> time_conversion(20)
'00:20'
>>> time_conversion(160)
'02:40'
'''
def time_conversion(minutes):
'''Define a method that takes a number of minutes as its argument and returns a string formatted HH:MM'''
hour = minutes / 60
mins = minutes % 60
return '{}:{}'.format('%02d' % hour, '%02d' % mins)
# ##################### Tests ###################
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. NICE ONE!\n" |
3839258f6b3f3ba380106b166ba6fc430a6ded3c | MaxT2/EWPythonDevelopment | /PythonCodingClub/pygameGameWithEnemy.py | 2,252 | 3.609375 | 4 |
# import pygame library so we can use it!
import pygame
# define player sprite
class Enemy(pygame.sprite.Sprite):
def __init__(self,screen_width,screen_height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill((0,255,0))
self.rect = self.image.get_rect()
self.rect.center = (screen_width / 2, screen_height / 2)
self.x_speed = 15
self.y_speed = 20
def update(self):
self.rect.x += self.x_speed
self.rect.y += self.y_speed
# check to see if sprite left screen and reverse direction
if self.rect.right > 1000:
# to make sure you never get stuck
# self.rect.right = 999
# reverse direction
self.x_speed *= -1
if self.rect.left < 0:
self.x_speed *= -1
if self.rect.bottom > 1000:
self.y_speed *= -1
if self.rect.top < 0:
self.y_speed *= -1
# game code that needs to run only once
pygame.init()
# setup display dimensions
display_width = 1000
display_height = 1000
gameSurface = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Window Caption!')
# setup game clock
FPS = 60
clock = pygame.time.Clock()
# setup game resources
# create a sprite group to keep track of sprites
all_sprites = pygame.sprite.Group()
enemy1 = Enemy(display_width, display_height)
all_sprites.add(enemy1)
# fill entire screen with black
gameSurface.fill(0)
# main game loop
running = True # when running is True game loop will run
while running == True:
# get input events and respond to them
# if event is .QUIT
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# UPDATE STUFF
# only update FPS (60) times a second
clock.tick(FPS)
# run update on all sprites in all_sprites group
all_sprites.update()
# DRAW STUFF
# clear display every frame(redraw background)
gameSurface.fill(0)
# draw all sprites in all_sprites group
all_sprites.draw(gameSurface)
# update and redraw entire screen
pygame.display.flip()
# update some of the screen
# pygame.display.update()
|
cfa9722112cf5be23f0c64ca3be69f2f495e8a4a | natalieparellano/dat-chapter-1 | /labs/exercise_1/solution.py | 210 | 4.0625 | 4 | def divisible_by_33( numbers ):
to_return = []
for num in numbers:
if num % 33 == 0:
to_return.append( num )
return to_return
numbers = [ x for x in range( 1, 999) ]
divisible_by_33( numbers )
|
106b30480a4d36a0f8beecd7dfe78834f591ddc6 | molchiro/AtCoder | /random/ATC001B.py | 659 | 3.671875 | 4 | class union_find:
def __init__(self, N):
self.par = [i for i in range(N)]
def root(self, i):
if self.par[i] == i:
return i
else:
# 経路圧縮
self.par[i] = self.root(self.par[i])
return self.par[i]
def same(self, a, b):
return self.root(a) == self.root(b)
def unite(self, a, b):
if not self.same(a, b): self.par[a] = self.root(b)
N, Q = map(int, input().split())
UF = union_find(N)
for _ in range(Q):
P, A, B = map(int, input().split())
if P == 0:
UF.unite(A, B)
else:
print('Yes' if UF.same(A, B) else 'No')
|
aa2403bea4086199b568c49d98bae41d9363f0c4 | kanukolluGVT/CP-and-DSA | /selection_sort.py | 406 | 4.0625 | 4 | def find_smallest(arr):
smallest=arr[0]
smallest_idx=0
for i in range(1,len(arr)):
if arr[i]<smallest:
smallest=arr[i]
smallest_idx=i
return smallest_idx
def selection_sort(arr):
new_arr=[]
for i in range(len(arr)):
smallest=find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
print(selection_sort([5,4,1,7,9]))
|
4ca752c4354477560fa66d7a42486e8f2ae9894b | AdrianoKim/ListaDeExerciciosPythonBrasilAdrianoKim | /PythonBrasil/1. Estrutura Sequencial/7. area do quadrado.py | 316 | 4.09375 | 4 | """ 7.Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro
# desta área para o usuário.
"""
lado = float(input('Digite o tamanho do lado do quadrado: '))
# Obs.: Fórmula da área do quadrado = lado * lado
print('O dobro da área deste quadrado é: ', format((lado * lado) * 2, 'n'))
|
e3e204509cd7641583cfc9d02634a1396d826a1e | donpaul999/UBB | /Year 1/Semester 1/python/Seminar/seminar_07_08/ui.py | 2,891 | 4.125 | 4 | '''
Create an application for a car rental business using a console based user interface. The application must allow keeping records of the companyâs list of clients, existing car pool and rental history. The application must allow its users to manage clients, cars and rentals in the following ways:
* Clients
- Add a new client. Each client is a physical person having a unique ID, name and age
- Update the data for any client.
- Remove a client from active clients. Note that removing a client must not remove existing car rental statistics.
- Search for clients based on ID and name.
- All client operations must undergo proper validation!
* Cars
- Add a new car to the car pool. Each car must have a valid license plate number, a make, a model and a color.
- Remove a car from the car pool.
- Search for cars based on license number, make and model and color.
- All car operations must undergo proper validation!
* Rentals
- An existing client can rent one or several cars from the car pool for a determined period. When rented, a car becomes unavailable for further renting.
- When a car is returned, it becomes available for renting once again.
* Statistics
- All cars in the car pool sorted by number of days they were rented.
- The list of clients sorted descending by the number of cars they have rented.
'''
class UI:
def __init__(self, carService, clientService, rentalService):
self._carService = carService
self._clientService = clientService
self._rentalService = rentalService
def deleteClient(self):
'''
When we delete a client, we delete their rentals
'''
try:
clientID = input("Client id= ")
self._rentalService.deleteAllRentals(clientID)
#1. Find menthod
except RepositoryException as re:
print(re)
#All cars in the car pool sorted by number of days they were rented.
#0 days for cars that were never rented
def _mostRentedCars(self):
result = self._rentalService.mostRentedCars()
for r in result:
print(r)
#car info -> number of day
def _rentCar(self):
try:
# 1. Determine the client(get client ID)
clientID = input("Client id= ")
client = self._clientService(clientID)
# 2. Determine the car(get car ID)
carID = input("Car id= ")
car = self._carService.getCar(carID)
# 3. Validation
# 4. Create rental
rent = Rental(100, date(), date(), client, car)
self._rentalService.addRental(rent)
except RepositoryException as re:
print(re)
def start(self):
'''
Start program, display menu, read user input, call other methods....
'''
pass
|
5d6d3b599649c44a78d2598db3542accf92ce100 | mfarukkoc/8-queen-problem | /hillclimb.py | 5,686 | 4 | 4 | # -*- coding: utf-8 -*-
import random
class Board:
def __init__(self, n, board_map):
for i, q in enumerate(board_map):
if(q >= n):
print('error: queen is out of boundry on column {}: (val:{})'.format(i,q))
board_map[i] = random.randrange(n)
print('replaced randomly with {}'.format(board_map[i]))
self.__n = n
self.__board_map = board_map # initializing board columns
self.h = heuristic_value(self.__board_map)
@property
def board_map(self):
return self.__board_map
@property
def n(self):
return self.__n
def move(self, column, val):
if(column >= self.n or val >= self.n):
return
self.__board_map[column] = val
def print_board(self):
board = ''
for i in range(self.__n):
for j in range(self.__n):
if(self.__board_map[j] == self.__n - i - 1):
board+='Q '
else:
board+='- '
board+='\n'
h = 'h={} Queens Conflicting'.format(self.h)
print(board + h)
def steepest_climb(self): # choose randomly between the steepest moves.
min_h = self.h
moves = []
temp_map = list(self.__board_map)
for i, val in enumerate(temp_map):
for j in range(self.__n):
temp_map[i] = j
heuristic = heuristic_value(temp_map)
if heuristic <= min_h:
min_h = heuristic
if(j != self.__board_map[i]):
moves += [{'col':i, 'val':j, 'h':heuristic}]
temp_map = list(self.__board_map)
best_moves = [move for move in moves if move['h'] == min_h]
if(self.h <= min_h or len(best_moves)==0):
return False
self.h = min_h
x = random.choice(best_moves)
self.__board_map[x['col']] = x['val']
return True
def stochastic_climb(self): # choose randomly between the ascending moves.
min_h = self.h
moves = []
temp_map = list(self.__board_map)
for i, val in enumerate(temp_map):
for j in range(self.__n):
temp_map[i] = j
heuristic = heuristic_value(temp_map)
if heuristic < min_h:
if(j != self.__board_map[i]):
moves += [{'col':i, 'val':j, 'h':heuristic}]
temp_map = list(self.__board_map)
if(len(moves)==0):
return False
x = random.choice(moves)
self.h = x['h']
self.__board_map[x['col']] = x['val']
return True
def random_restart_climb(self, show = False): # use steepest_climb function until solution found, if not restart from random state
restart, count = 0, 0
while(self.h != 0):
while(self.steepest_climb()==True):
count +=1
if(show == True):
self.print_board()
if(self.h == 0):
break
restart += 1
self.__board_map = random_board(self.__n)
self.h = heuristic_value(self.__board_map)
if(show == True):
print('randomized board')
self.print_board()
return (restart,count)
def heuristic_value(board_map): # helper function to calculate heuristic value(total conflicting queens)
h = 0
for i, val1 in enumerate(board_map):
for j, val2 in enumerate(board_map[i+1:]):
if(conflict(i,j+i+1,val1,val2)):
h += 1
return h
def conflict(column1, column2, val1, val2): # helper function to determine if two queen conflicting
if column2 < column1: # swap columns so column1 has lesser value
(column1, column2) = (column2, column1)
if(val1 == val2): # check queens horizontal
return True
coldif = column2 - column1
if(abs(val1 - val2) == coldif): # check queens diagonal
return True
return False
def random_board(n): # creating random board
board = []
for i in range(n):
board.append(random.randrange(n))
return board
print('This program solve N-Queens problem by hill-climbing methods')
print('program provides Steepest hill climb, random-restart hill climb and stochastic hill climb')
choice = input('Randomly Generated Problems (Y/N):').upper()
repeats = 1
if(choice[0] != 'Y'):
initial = input('Enter board(spaces between):').split(' ')
initial = list(map(int,initial)) # convert chars to int
if(choice[0] == 'Y'):
n = input('Enter board size N: ')
while(int(n) < 4):
n = input('Enter board size N (minimum 4): ')
repeats = input('Enter how many tests you want:')
while(int(repeats) < 1):
repeats = input('Tests can not be less than 1:')
n = int(n)
repeats = int(repeats)
print('RR:Random Restart, S:Steepest, ST:Stochastic')
method = input('Enter method(s) (spaces between): ').upper().split(' ')
stepbystep = input('Step by Step solution(Y/N)): ').upper()
for x in range(repeats):
if(choice[0] == 'Y'):
initial = random_board(n)
board_initial = Board(len(initial), initial)
print('\nInitial board')
board_initial.print_board()
for m in method:
board = Board(int(board_initial.n), list(board_initial.board_map))
restart = -1
moves = 0
if(m == 'RR'):
print('\nRandom Restart Hill Climb')
(restart,moves) = board.random_restart_climb(stepbystep[0] == 'Y')
elif(m == 'ST'):
print('\nStochastic Hill Climb')
while(board.stochastic_climb()==True):
moves = 1 + moves
if(stepbystep[0] == 'Y'):
board.print_board()
elif(m == 'S'):
print('\nSteepest Hill Climb')
while(board.steepest_climb()==True):
moves = 1 + moves
if(stepbystep[0] == 'Y'):
board.print_board()
else:
continue
print('Final State:')
board.print_board()
statistics = '{} moves'.format(moves)
if(restart!= -1):
statistics = '{} restarts, '.format(restart) + statistics
print(statistics)
|
4edc6fa78b171007555266e932b53aad2cc30d52 | mmanishh/codilitysolution | /stackqueue/paranteses.py | 921 | 4.09375 | 4 | def check_parentheses(a):
inputs = a.split()
print(inputs)
stack = []
for i,input in enumerate(inputs):
if input == '{' or input=='(' or input=='[':
stack.append(input)
print(i,stack)
if input == '}' or input==')' or input==']':
if len(stack) <=0:
return False
elif not is_matching(stack.pop(),input):
return False
print('final:',stack)
if len(stack) <=0:
return True
else:
return False
def is_matching(char1,char2):
if char1 == '(' and char2==')':
return True
elif char1 == '{' and char2=='}':
return True
elif char1 == '[' and char2==']':
return True
else:
return False
if __name__ == "__main__":
if check_parentheses('{ ( ) } ( ) [ ]'):
print("balanced")
else :
print("not balanced")
|
4d9d13f611730f765601f4fc684337c3fd909f60 | KermanJR/URI | /Uri1066.py | 604 | 3.625 | 4 | def main():
par = 0
imp = 0
posit = 0
neg = 0
Z = 0
while Z < 5:
x = int(input())
if x % 2 == 0:
par = par + 1
if x % 2 != 0:
imp = imp + 1
Z = Z + 1
if x == 0:
Z = Z + 1
if x > 0:
posit = posit + 1
Z = Z + 1
if x < 0:
neg = neg + 1
print("{} valor(es) par(es)".format(par))
print("{} valor(es) impar(es)".format(imp))
print("{} valor(es) positivo(s)".format(posit))
print("{} valor(es) negativo(s)".format(neg))
main()
|
77aa420758f3df45f589d4f052f92f04b5e380f7 | LeeInHaeng/algorithm | /프로그래머스(Python3)/level1/두 정수 사이의 합.py | 166 | 3.609375 | 4 | def solution(a, b):
sum=0
if b>a:
for x in range(a,b+1):
sum+=x
else:
for x in range(b,a+1):
sum+=x
return sum |
dcdc74ab2be3afe4bc085d2855caf59b68cbf7c0 | atsin6/Fibonacci_numbers | /Fibonacci-numbers.py | 226 | 4.15625 | 4 | #fibonacci Numbers : 0,1,1,2,3,5,8,13,21,34,55,........
x = 0
y = 1
a = int(input('Enter how many fibonacci numbers you want to be printed:',))
for i in range(a):
print(x)
print(y)
x = x + y
y = y + x
|
d7ddf1eb5af4e487709083065f81a0c8c8cfa62c | shichao-an/ctci | /chapter2/question2.2.py | 952 | 4.03125 | 4 | from __future__ import print_function
from linked_list import create_list, restore_list
def nth_to_last(head, k):
"""nth to last node (recursive)
If k is greater than the length of the linked list, return head node
"""
if head is None or k == 0:
return None
elif nth_to_last(head.next, k - 1) == head.next:
return head
else:
return nth_to_last(head.next, k)
def nth_to_last2(head, k):
"""Use counter and print the element"""
if head is None:
return 0
i = nth_to_last2(head.next, k) + 1
if i == k:
print(head.data)
return i
def _test():
pass
def _print():
a1 = [1, 2, 3, 4, 5, 6]
l1 = create_list(a1)
print(nth_to_last(l1, 0))
print(nth_to_last(l1, 1).data)
print(nth_to_last(l1, 3).data)
print(nth_to_last(l1, 6).data)
print(nth_to_last(l1, 7).data)
nth_to_last2(l1, 4)
if __name__ == '__main__':
_test()
_print()
|
e96be88c1043d9219b520298322566099a59e9c7 | pmarcol/Python-excercises | /Python - General/List/31-40/excercise36.py | 318 | 3.640625 | 4 | """
Write a Python program to get variable unique identification number or string.
"""
"""
SOLUTION:
"""
myVars = [True, 100, 3.14, 'test']
testVar1 = 'test'
testVar2 = 'test'
print(format(id(myVars), 'x'))
print(format(id(testVar1), 'x'))
print(format(id(testVar2), 'x')) # the last two ones will have the same ids |
a3e678d9ab83d20ec6502b19f781b60805006b0e | sherifkandeel/hackerrank | /Algorithms/Strings/easy/Funny_String.py | 428 | 3.671875 | 4 | import math
def is_funny(s, r):
for i in range(1,len(s)):
s_diff = math.fabs(ord(s[i]) - ord(s[i-1]))
r_diff = math.fabs(ord(r[i]) - ord(r[i-1]))
if s_diff != r_diff:
return False
return True
cases = int(raw_input())
for c in range (0, cases):
s = raw_input()
r = s[::-1]
funny = is_funny(s, r)
if funny:
print "Funny"
else:
print "Not Funny"
|
40ae43f47dc4bf0aacba285271bca05b7bee1353 | nickfang/classes | /projectEuler/webScraping/problemTemplates/383.py | 424 | 3.5625 | 4 | # Divisibility comparison between factorials
#
#
#Let f5(n) be the largest integer x for which 5x divides n.
#For example, f5(625000) = 7.
#
#
#Let T5(n) be the number of integers i which satisfy f5((2·i-1)!) < 2·f5(i!) and 1 ≤ i ≤ n.
#It can be verified that T5(103) = 68 and T5(109) = 2408210.
#
#
#Find T5(10^18).
#
#
import time
startTime = time.time()
print('Elapsed time: ' + str(time.time()-startTime)) |
28873ab23768ff48c7831c51f330e615f97d0565 | montaro/CtCI-6th-Edition-Python | /chapter1/1.2-check_permutation.py | 1,303 | 3.78125 | 4 | import unittest
from collections import Counter
def check_permutation(word1, word2):
if len(word1) != len(word2):
return False
word1 = sorted(word1)
word2 = sorted(word2)
if word1 == word2:
return True
else:
return False
def check_permutation_2(word1, word2):
if len(word1) != len(word2):
return False
c1 = Counter(word1)
c2 = Counter(word2)
return c1 == c2
class Test(unittest.TestCase):
dataT = (
('abcd', 'bacd'),
('3563476', '7334566'),
('wef34f', 'wffe34'),
)
dataF = (
('abcd', 'd2cba'),
('2354', '1234'),
('dcw4f', 'dcw5f'),
)
def test_check_permutation(self):
# true check
for test_strings in self.dataT:
self.assertTrue(check_permutation(*test_strings))
# false check
for test_strings in self.dataF:
self.assertFalse(check_permutation(*test_strings))
def test_check_permutation_2(self):
# true check
for test_strings in self.dataT:
self.assertTrue(check_permutation_2(*test_strings))
# false check
for test_strings in self.dataF:
self.assertFalse(check_permutation_2(*test_strings))
if __name__ == "__main__":
unittest.main()
|
fd8762faea1d66a13ed24b6b3696c6873c4154e0 | alcoccoque/Homeworks | /hw3/ylwrbxsn-python_online_task_3_exercise_3/task_3_ex_3.py | 1,746 | 4.46875 | 4 | """
Write a Python-script that:
1. Searches for files by a given pattern (pattern can include: *, ?)
2. Displays the search result
3. Gets access rights for each file that is found and displays the result
The script should have 2 obligatory functions:
- finder - a generator function searches for files by a given pattern
in a given path returns an absolute path of a found file.
- display_result - displays founded files and files' permission
by a given list of absolute paths (You can find an example below).
Example call:
python task_3_ex_3.py /usr/bin -p '?ython*'
Example result:
...
/usr/bin/python3.6m -rwxr-xr-x
/usr/bin/python3.7m -rwxr-xr-x
Found 12 file(s).
Note: use of glob module is prohibited.
Hint: use os.walk, stat, fnmatch
"""
import argparse
import os
import stat
import fnmatch
def finder(path, pattern):
"""Searches for files by a given pattern.
:param path: Absolute path for searching.
:param pattern: Can consist *, ?.
:return: absolute path of found file.
"""
result = []
for file in os.listdir(path):
if fnmatch.fnmatch(file, pattern):
result.append(path + '/' + file)
return result
def display_result(file_paths):
"""Displays founded file paths and file's permissions."""
for file_path in file_paths:
print(file_path, stat.filemode(os.stat(file_path).st_mode))
print(f"Found {len(file_paths)} file(s).")
def main():
parser = argparse.ArgumentParser()
parser.add_argument('path', type=str, help="path")
parser.add_argument('-p', help="pattern")
args = parser.parse_args()
display_result(finder(args.path, args.p))
if __name__ == '__main__':
main()
|
6f83b0f126ae0ecc4fd331c40d24c92ec96ddf94 | saidatta/Project-euler | /lib/Problems_1_100/Euler041.py | 265 | 3.5 | 4 | import prime
from itertools import permutations
# Pan-digital primes are 4 or 7 digits. Others divisible by 3
for perm in permutations(range(7, 0, -1)):
num = 0
for n in perm: num = num * 10 + n
if prime.is_prime(num):
print(num)
break
|
79ef1ff3ba38596b2dd1ee8c8a1e2aae5532f740 | MazanYan/pHash-image-recognition | /raw_algorithms_python/HashAlgorithms.py | 4,577 | 3.6875 | 4 | from functools import reduce
from PIL import Image
import numpy as np
# Class to get images from some folder and hash them with simple pHash algorithm
class HashBuilder:
def __init__(self, path):
self.images_path = path
"""
Compresses image object into 8x8 square array to be used in saving as a new file or recoloring as two-colored image
for further hash building
The method saves initial colors with saving only each 7th row/column of image array
:param (image) an object of Image class
:return 8x8 numpy image array of uint8 type
"""
@staticmethod
def __compress__(image: "Image"):
width, height = image.size
rows_to_leave = range(0, height + 1, int(height / 7))
columns_to_leave = range(0, width + 1, int(width / 7))
image_array = np.array(image)
new_image_array = np.array(
[np.array([image_array[i][j] if len(image_array[i][j]) == 3 else image_array[i][j][:3]
for j in columns_to_leave])
for i in rows_to_leave])
return new_image_array.astype(np.uint8)
"""
Rewrites compressed image 8x8 array making him have only two colors - black and white
Finds average brightness of image and discretizes all other colors,
making each point with smaller brightness black
and making each point with greater brightness white
:param (compressed_image) 8x8 numpy image array of uint8 type that is already compressed by __compress__ method
:return two-colored 8x8 numpy image array of uint8 type
"""
@staticmethod
def __two_colored__(compressed_image):
all_array_points = np.array(reduce(lambda res_array, row: res_array + list(row), compressed_image, []))
average_brightness = np.linalg.norm(sum(all_array_points))
new_array = np.array([np.array(
[np.array([0, 0, 0]) if np.linalg.norm(compressed_image[i][j]) < average_brightness else np.array([255, 255, 255])
for j in range(len(compressed_image))])
for i in range(len(compressed_image[0]))])
return new_array.astype(np.uint8)
"""
Saves compressed image as image file. Is used for tests only
:param (compressed_array) 8x8 numpy image array of uint8 type
:param (name_to_save) image name with path to be saved in
:return None
"""
@staticmethod
def __save_compressed__(compressed_array: "np.array np.uint8 type", name_to_save):
image = Image.fromarray(compressed_array.astype(np.uint8))
image.save(str(name_to_save))
"""
Builds hash of compressed two colored 8x8 numpy image array
Hashes each point into bytearray depending of its' color:
black point gets hashed into \0 symbol,
white point gets hashed into \1 symbol
:param (compressed_array) 8x8 numpy image array of uint8 type
:return bytearray sequence of \0 and \1 symbols
"""
@staticmethod
def __build_hash__(compressed_array: "two colors image array"):
all_array_points = np.array(reduce(lambda res_array, row: res_array + list(row), compressed_array, []))
bytearr = "".join(["\0" if (el - np.array([255, 255, 255])).any() else "\1" for el in all_array_points])
return bytearr.encode()
"""
Composition of "private" class methods used to create image hash
Opens image in class folder firstly, then compresses it,
then discretizes colors array making him hav only two colors, then builds hash
:param (image_name) name of image file to be imported from class image folder
:return tuple of image name with path and hash of input image
"""
def hash_image(self, image_name: "str"):
return self.images_path + image_name, self.__build_hash__(self.__two_colored__(self.__compress__(Image.open(self.images_path + image_name))))
# Checking how similar two hashes are
class CheckHash:
# def __init__(self):
# self.
"""
Calculates Hemming distance over two hashes and outputs difference percent
:param (dict_hash1) the first single-element dict with file name key and hash value as value
:param (dict_hash2) the second single-element dict with file name key and hash value as value
:return hemming distance
"""
@staticmethod
def similarity_percent(hash1, hash2):
hemming_distance = reduce(lambda accum, element: accum+1 if element[0]!=element[1] else accum, zip(list(hash1), list(hash2)), 0)
# 8x8 numpy array
image_size = 64
return 1 - hemming_distance/image_size
|
625d6d7af86693494b3afea155ae3308557ca12e | clamli/ml_algorithms | /knn_kdtree/myutil.py | 562 | 3.59375 | 4 | import numpy as np
def get_median(data):
"""input:
list : one-dimension feature
output:
int/float : middle value
---------
"""
data.sort()
half = len(data) // 2
return data[half]
def eucli_distance(point_1, point_2):
"""input:
list : point_1, point_2
output:
float : distance between two points
---------
"""
# print "point_1=",point_1
# print "point_1=",point_2
sum_of_dist = 0
for i1, i2 in zip(point_1, point_2):
sum_of_dist += (i1 - i2)**2
return np.sqrt(sum_of_dist)
|
5919a6170b192cd9f4eb0d2aff467855c82ecab3 | AndreiZavo/Graph-Algorithms | /Lab_1/main.py | 2,297 | 4.03125 | 4 | import random
from repo import GraphFile, Graph
from service import GraphService
from ui import UI
'''
This function creates a random graph which will be stored in a file.
It uses two inputs from the user, a number of vertices and a number of edges
'''
def create_random_graph():
number_of_vertices = int(input("Type the number of vertices: "))
number_of_edges = int(input("Type the number of edges: "))
probable_id_for_vertex = list(range(number_of_vertices))
probable_cost_for_vertex = []
for index in range(number_of_edges + 1):
new_cost = random.randrange(0, number_of_edges + 100, 2)
probable_cost_for_vertex.append(new_cost)
random_file = open("random_graph", 'w+')
first_line = str(number_of_vertices) + " " + str(number_of_edges) + " \n"
random_file.write(first_line)
for line_index in range(number_of_edges):
start_vertex_id = random.randrange(len(probable_id_for_vertex))
start_vertex = str(probable_id_for_vertex[start_vertex_id])
end_vertex_id = random.randrange(len(probable_id_for_vertex))
end_vertex = str(probable_id_for_vertex[end_vertex_id])
cost_id = random.randrange(len(probable_cost_for_vertex))
cost = str(probable_cost_for_vertex[cost_id])
line = start_vertex + " " + end_vertex + " " + cost + '\n'
random_file.write(line)
random_file.close()
'''
From the start of the application the user has two choices
To use a random graph or to use a specific one
'''
def choice():
print("If you want to work with a random graph press 1")
print("If you want to work with a specific graph press 2")
command = input(">>> ")
if command == '1':
create_random_graph()
repo = GraphFile("random_graph", Graph.read_line, Graph.write_line, Graph.read_first_line,
Graph.write_first_line)
service = GraphService(repo)
console = UI(service)
console.ui_main()
elif command == '2':
repo = GraphFile("graph", Graph.read_line, Graph.write_line, Graph.read_first_line, Graph.write_first_line)
service = GraphService(repo)
console = UI(service)
console.ui_main()
else:
raise TypeError("Please choose one of the above")
choice()
|
fb40cfb7161067d0a5200fcb88117e6c010bb6f8 | gandastik/365Challenge | /365Challenge/sortArrayByParityII.py | 661 | 4.09375 | 4 | #60. Mar 1, 2021 - Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
# Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
# Return any answer array that satisfies this condition.
def sortArrayByParityII(nums: List[int]) -> List[int]:
odd = []
even = []
ret = []
for i in nums:
if(i % 2 == 0):
even.append(i)
else:
odd.append(i)
for i in range(len(nums)//2):
ret.append(even[i])
ret.append(odd[i])
return ret
nums = [int(x) for x in input().split()]
print(sortArrayByParityII(nums)) |
8dd2ce714e3e02a71db859de475023f399670fa2 | BScheihing/03Tarea | /P2.py | 1,494 | 3.90625 | 4 | '''
Este script resuelve el sistema de Lorenz usando
el integrador dopri5 de la libreria scipy.integrate.
Los parametros asociados al sistema de Lorenz estan
fijos en la implementacion, para obtener la solucion
conocida como el Atractor de Lorenz.
La funcion f define el sistema con los parametros ya
fijados. Luego el script integra (x,y,z) desde t=0
hasta t=100 y crea una figura con la trayectoria en
3D. Al final del script se guarda una de sus vistas
en una imagen .eps.
'''
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import ode
from mpl_toolkits.mplot3d import Axes3D
def f(t, xyz):
dx = 10.0 * (xyz[1] - xyz[0])
dy = xyz[0] * (28.0 - xyz[2]) - xyz[1]
dz = xyz[0] * xyz[1] - 8.0/3.0 * xyz[2]
return [dx, dy, dz]
tf = 100.
N_steps = 10000
dt = tf/N_steps
x=np.zeros(N_steps+1)
y=np.zeros(N_steps+1)
z=np.zeros(N_steps+1)
xyz0 = [1, 1, 1]
t=np.linspace(0, 10, N_steps+1)
n=1
solver = ode(f)
solver.set_integrator('dopri5', atol=1E-6, rtol=1E-4)
solver.set_initial_value(xyz0)
while solver.successful() and solver.t < tf and n<=N_steps:
solver.integrate(solver.t+dt)
t[n] = solver.t
x[n] = solver.y[0]
y[n] = solver.y[1]
z[n] = solver.y[2]
n+=1
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
ax.plot(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('Atractor de Lorenz, $(x_0,y_0,z_0) = (1,1,1)$')
plt.savefig('Lorenz.eps')
plt.show()
|
1b16499d81c7e42482b47ee5735680a6559b0efc | PaweenJabberry/Practice | /Python/LongestWord.py | 886 | 4.375 | 4 | # Longest Word
#
# Have the function LongestWord(sen) take the sen parameter being passed
# and return the largest word in the string. If there are two or more words that
# are the same length, return the first word from the string with that length.
# Ignore punctuation and assume sen will not be empty.
#
# Examples
# Input: "fun&!! time"
# Output: time
#
# Input: "I love dogs"
# Output: love
#
import re
def LongestWord(sen):
# Search only characters
allWord = ""
allWord = " ".join(re.split("[^a-zA-Z]", sen))
# Find longest word and return
maxLength = 0
for x in allWord.split():
if(len(x) > maxLength):
sen = str(x).strip()
maxLength = len(x)
return sen
# Example Test
A = "I love dogs"
print("Input: \n I love dogs")
print("Output: \n",LongestWord(A))
A = "fun&!!!lil time"
print("Input: \n fun&!!!lil time")
print("Output: \n",LongestWord(A)) |
05bfcb97a9dabab31be6cf195e50a16df9a2abb8 | jkjit/pyLearning | /com/jkpy/dictionary/dictionary_Sample.py | 1,182 | 4.15625 | 4 | # my_dict = dict({1:'apple', 2:'ball'})
# print(my_dict)
# print(type(my_dict))
#
# my_dict1 = dict([(1,'apple'), (2,'ball')])
# print(my_dict1)
# print(type(my_dict1))
my_dict = {'name': 'jack', 'age': 20}
print(my_dict)
print(my_dict['name'])
print(my_dict.get('name'))
print(my_dict.get('age'))
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
print(squares.pop(3))
print(squares)
print(squares.popitem())
print(squares.popitem())
print(squares)
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
print((squares.items()))
print(squares.keys())
print(squares.values())
print(squares)
print(squares.popitem())
print(squares)
squares.__delitem__(2)
print(squares)
squares.clear()
print(squares)
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
squares.__dir__()
# print(squares.__dir__())
print(squares.__getitem__(1))
squares.__setitem__(1,20)
print(squares)
if squares.__contains__(6):
print("dictionary contains the value specified")
else: print("Doesnt have this key")
squares.setdefault(1)
print(squares.__len__())
print(len(squares))
str2 = squares.copy()
print(str2)
print("Salary not found: "+ str2.get('salary','UselessFellow'.upper()))
print(str2) |
e3366659693861186f18404c47a1a59e1d04d74e | qsyPython/Python_play_now | /wangfuhao/04-share/01-GUI.py | 8,390 | 4.0625 | 4 | print('------------------label-button-----------------')
import tkinter as tk
#
# window = tk.Tk()
# window.title('my window')
# window.geometry("200x100")
#
# var = tk.StringVar()
#
# l = tk.Label(window,textvariable=var,bg='green',font=('Arial',12),width=15,height=2)
# l.pack()
# # l.place #自己指定位置
#
# on_hit = False
#
# def hit_me():
# global on_hit
# if on_hit == False:
# on_hit = True
# var.set('you hit me')
# else:
# on_hit = False
# var.set('')
#
# b = tk.Button(window,text='hit me',width=15,height=2,command=hit_me)
# b.pack()
#
# window.mainloop()
print('------------------entry&Text输入框和文本框-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# # e = tk.Entry(window, show="*") #不需要等于None就行
# e = tk.Entry(window, show="1")
# e.pack()
#
# def insert_point():
# var = e.get()
# t.insert('insert', var)
#
# def insert_end():
# var = e.get()
# t.insert('end', var)
# # t.insert(2.2, var) #插入到具体的地方 行.列
#
# b1 = tk.Button(window, text='insert point', width=15,height=2, command=insert_point)
# b1.pack()
#
# b2 = tk.Button(window, text='insert end',command=insert_end)
# b2.pack()
#
# t = tk.Text(window, height=2)
# t.pack()
#
# window.mainloop()
print('------------------listbox列表部件-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# var1 = tk.StringVar()
#
# l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
# l.pack()
#
# def print_selection():
# value = lb.get(lb.curselection())
# var1.set(value)
#
# b1 = tk.Button(window, text='print selection', width=15,height=2, command=print_selection)
# b1.pack()
#
# var2 = tk.StringVar()
# var2.set((11,22,33,44))#设定初始值
#
# lb = tk.Listbox(window, listvariable=var2)
#
# list_items = [1,2,3,4]
#
# for item in list_items:
# lb.insert('end', item) #插入一个列表的数据
#
# lb.insert(1, 'first') #按索引插入
# lb.insert(2, 'second')
# lb.delete(2)
# lb.pack()
#
# window.mainloop()
print('------------------Radiobutton 选择按钮-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# var = tk.StringVar()
# l = tk.Label(window, bg='yellow', width=20, text='empty')
# l.pack()
#
# def print_selection():
# l.config(text='you have selected ' + var.get())
#
# r1 = tk.Radiobutton(window, text='Option A',
# variable=var, value='A',
# command=print_selection)
# r1.pack()
#
# r2 = tk.Radiobutton(window, text='Option B',
# variable=var, value='B',
# command=print_selection)
# r2.pack()
#
# r3 = tk.Radiobutton(window, text='Option C',
# variable=var, value='C',
# command=print_selection)
# r3.pack()
#
# window.mainloop()
print('------------------Scale 尺度-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# l = tk.Label(window, bg='yellow', width=20, text='empty')
# l.pack()
#
# def print_selection(v):#v是默认的传入值
# l.config(text='you have selected ' + v)
#
# s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
# length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
# #resolution=0.01保留两位小数
# # tickinterval=2 隔几个显示下数字
#
# s.pack()
#
# window.mainloop()
print('------------------Checkbutton 勾选项-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# l = tk.Label(window, bg='yellow', width=20, text='empty')
# l.pack()
#
# def print_selection():
# if (var1.get() == 1) & (var2.get() == 0):
# l.config(text='I love only Python ')
# elif (var1.get() == 0) & (var2.get() == 1):
# l.config(text='I love only C++')
# elif (var1.get() == 0) & (var2.get() == 0):
# l.config(text='I do not love either')
# else:
# l.config(text='I love both')
#
# var1 = tk.IntVar()
# var2 = tk.IntVar()
#
# c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
# command=print_selection)#选定是1 未选定是0
# c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
# command=print_selection)
# c1.pack()
# c2.pack()
#
# window.mainloop()
print('------------------Canvas 画布-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# canvas = tk.Canvas(window, bg='blue', height=100, width=200)
# # image_file = tk.PhotoImage(file='ins.gif')
# #anchor 锚点: 上 左 下 右 依次是 N W S E 中间是center所以nw(西北)可以理解为ios中0.0点
# # image = canvas.create_image(10, 10, anchor='nw', image=image_file)
# x0, y0, x1, y1= 50, 50, 80, 80
# line = canvas.create_line(x0, y0, x1, y1)
# oval = canvas.create_oval(x0, y0, x1, y1, fill='red') #画圆
# arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180) #扇形
# rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
# canvas.pack()
#
# def moveit():
# canvas.move(rect, 0, 2)
#
# b = tk.Button(window, text='move', command=moveit).pack()
#
# window.mainloop()
print('------------------Menubar 菜单-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# l = tk.Label(window, text='', bg='yellow')
# l.pack()
# counter = 0
# def do_job():
# global counter
# l.config(text='do '+ str(counter))
# counter+=1
#
# menubar = tk.Menu(window)
# filemenu = tk.Menu(menubar, tearoff=1) #tearoff能不能分开的区别 0 和 1 mac上看不出区别
# menubar.add_cascade(label='File', menu=filemenu)
# filemenu.add_command(label='New', command=do_job)
# filemenu.add_command(label='Open', command=do_job)
# filemenu.add_command(label='Save', command=do_job)
# filemenu.add_separator()
# filemenu.add_command(label='Exit', command=window.quit)
#
# editmenu = tk.Menu(menubar, tearoff=0)
# menubar.add_cascade(label='Edit', menu=editmenu)
# editmenu.add_command(label='Cut', command=do_job)
# editmenu.add_command(label='Copy', command=do_job)
# editmenu.add_command(label='Paste', command=do_job)
#
# submenu = tk.Menu(filemenu)
# filemenu.add_cascade(label='Import', menu=submenu, underline=0)
# submenu.add_command(label="Submenu1", command=do_job)
#
# window.config(menu=menubar)
#
# window.mainloop()
print('------------------Frame 框架-----------------')
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
# tk.Label(window, text='on the window').pack()
#
# frm = tk.Frame(window)
# frm.pack()
# frm_l = tk.Frame(frm,)
# frm_r = tk.Frame(frm)
# frm_l.pack(side='left')
# frm_r.pack(side='right')
#
# tk.Label(frm_l, text='on the frm_l1').pack()
# tk.Label(frm_l, text='on the frm_l2').pack()
# tk.Label(frm_r, text='on the frm_r1').pack()
# tk.Label(frm_r, text='on the frm_r2').pack()
# window.mainloop()
print('------------------Messagebox 弹窗-----------------')
# from tkinter import messagebox
# window = tk.Tk()
# window.title('my window')
# window.geometry('200x200')
#
# def hit_me():
# tk.messagebox.showinfo(title='Hi', message='1111111')
# tk.messagebox.showwarning(title='Hi', message='2222')
# tk.messagebox.showerror(title='Hi', message='33333')
# print(tk.messagebox.askquestion(title='Hi', message='askquestion')) # return 'yes' , 'no'
# print(tk.messagebox.askyesno(title='Hi', message='askyesno')) # return True, False
# print(tk.messagebox.askokcancel(title='Hi', message='askokcancel')) # return True, False
#
# tk.Button(window, text='hit me', command=hit_me).pack()
# window.mainloop()
print('------------------pack/grid/place 放置位置-----------------')
# window = tk.Tk()
# window.geometry('200x200')
#
# #pack方式
# # tk.Label(window, text='1').pack(side='top')
# # tk.Label(window, text='1').pack(side='bottom')
# # tk.Label(window, text='1').pack(side='left')
# # tk.Label(window, text='1').pack(side='right')
#
# #grid方式 (格子的方式)
# # for i in range(4):
# # for j in range(3):
# # tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)
#
# #place方式
# # tk.Label(window, text=1).place(x=20, y=10, anchor='nw')
#
# window.mainloop() |
a1cde60ed5ac3b8093d684070e0165b9fb28ac15 | RobbertSinclair/Chess | /main.py | 9,019 | 3.5625 | 4 | import pygame
import time
from piece import *
pygame.init()
#create the window
screen = pygame.display.set_mode((800,800))
#Set up colours
WHITE = (255, 255, 255)
BLACK = (40,40,40)
GREEN = (0,128,0)
ORANGE = (255, 69, 0)
board = [[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
#Define the areas to fill the board
def board_fill(width = 800, height = 800):
positions = []
zero_start = True
the_height = 0
while the_height < height:
i = 0
if zero_start:
the_start = 0
else:
the_start = 100
while i < width:
new_tuple = (the_start + i, the_height, 100, 100)
positions.append(new_tuple)
i += 200
the_height += 100
zero_start = not zero_start
return positions
def input_board(pieces, width=800, height=800):
input_squares = {}
the_height = 0
input_squares["check"] = False
input_squares["check_attacker"] = 0
input_squares["check_moves"] = []
piece_locations = {piece.getPosition(): piece for piece in pieces}
for i in range(8):
the_position = 0
for j in range(8):
if (j,i) in piece_locations.keys():
the_piece = piece_locations[(j,i)]
else:
the_piece = 0
input_squares[(j, i)] = {"input": pygame.Rect(the_position, the_height, 100, 100),
"rect": (the_position, the_height, 100, 100),
"piece": the_piece}
the_position += 100
the_height += 100
return input_squares
def set_up_board():
#Place Pawns
pieces = []
for i in range(8):
pieces.append(Pawn(i,1,side=1))
pieces.append(Pawn(i,6))
#Place Rooks
pieces.append(Rook(0,0,1))
pieces.append(Rook(7,0,1))
pieces.append(Rook(0,7))
pieces.append(Rook(7,7))
#Place Knights
pieces.append(Knight(1,0,1))
pieces.append(Knight(6,0,1))
pieces.append(Knight(1,7))
pieces.append(Knight(6,7))
#Place Bishops
pieces.append(Bishop(2,0,1))
pieces.append(Bishop(5,0,1))
pieces.append(Bishop(2,7))
pieces.append(Bishop(5,7))
#Place Kings
pieces.append(King(4,0,1))
pieces.append(King(4,7))
#Place Queen
pieces.append(Queen(3,0,1))
pieces.append(Queen(3,7))
return pieces
pieces = set_up_board()
input_board = input_board(pieces)
side_pieces = {0: [piece for piece in pieces if piece.getSide() == 0],
1: [piece for piece in pieces if piece.getSide() == 1],
"white_king": [piece for piece in pieces if str(piece) == "K" and piece.getSide() == 0][0],
"black_king": [piece for piece in pieces if str(piece) == "K" and piece.getSide() == 1][0]
}
def draw_piece(the_piece, place_dictionary=input_board):
location = the_piece.getPosition()
if location == (-1, -1):
return (-100, -100)
else:
the_position = place_dictionary[location]["rect"]
return(the_position[0] + 8, the_position[1] + 8)
#caption
pygame.display.set_caption("Chess")
x = 0
y = 0
side_turn = 0
gameExit = False
selected = (-1, -1)
while not gameExit:
event = pygame.event.poll()
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
for key in input_board:
if key != "check" and key != "check_moves" and key != "check_attacker":
if input_board[key]["input"].collidepoint(event.pos):
the_piece = 0
print(f"{key} clicked")
if selected == [key]:
selected = (-1, -1)
elif key in selected:
piece_location = input_board[the_position]["piece"].getPosition()
#Taking manouver
print("The value of the piece at {0} is {1}".format(key, input_board[key]["piece"]))
if input_board[key]["piece"] != 0:
print("This has run")
if input_board[key]["piece"].getSide() != input_board[the_position]["piece"].getSide():
taken_piece_index = pieces.index(input_board[key]["piece"])
input_board[key]["piece"].setPosition(-1, -1)
pieces[taken_piece_index].setPosition(-1,-1)
print(f"The position of the taken piece is {pieces[taken_piece_index].getPosition()}")
print(f"The result of draw_piece({pieces[taken_piece_index]}) is {draw_piece(pieces[taken_piece_index])}")
#the_pieces.pop(taken_piece_index)
#Move the piece
piece_index = pieces.index(input_board[the_position]["piece"])
input_board[the_position]["piece"] = 0
pieces[piece_index].setPosition(key[0], key[1])
the_king = pieces[piece_index].getEnemyKing(side_pieces)
input_board[key]["piece"] = pieces[piece_index]
selected = (-1, -1)
if str(input_board[key]["piece"]) == "K":
the_moves = input_board[key]["piece"].getAllowedMoves(input_board, side_pieces, side_turn)
else:
the_moves = input_board[key]["piece"].getAllowedMoves(input_board, side_pieces)
kingPos = the_king.getPosition()
if kingPos in the_moves:
input_board["check_attacker"] = input_board[key]["piece"]
print("The attacking piece is {0}".format(input_board["check_attacker"]))
if str(input_board["check_attacker"]) == "Q" or str(input_board["check_attacker"]) == "R" or input_board["check_attacker"] == "B":
input_board["check_moves"] = input_board["check_attacker"].getDangerMoves(kingPos) + [input_board["check_attacker"].getPosition()]
elif str(input_board["check_attacker"]) == "N" or str(input_board["check_attacker"]) == "P":
input_board["check_moves"] = [input_board["check_attacker"].getPosition()]
else:
input_board["check_moves"] = input_board["check_attacker"].getAllowedMoves(input_board, side_pieces)
print(input_board["check_moves"])
input_board["check"] = True
else:
input_board["check_attacker"] = 0
input_board["check_moves"] = []
input_board["check"] = False
#Change the side turn
if key != piece_location:
if side_turn == 0:
side_turn = 1
else:
side_turn = 0
else:
the_piece = input_board[key]["piece"]
selected = [key]
if the_piece != 0 and the_piece.getSide() == side_turn:
the_position = the_piece.getPosition()
if str(the_piece) != "K":
selected = selected + the_piece.getAllowedMoves(input_board, side_pieces)
else:
selected = selected + the_piece.getAllowedMoves(input_board, side_pieces, side_turn)
screen.fill(WHITE)
the_positions = board_fill()
for position in the_positions:
screen.fill(BLACK, position)
if selected != (-1, -1):
for select in selected:
screen.fill(GREEN, input_board[select]["rect"])
if input_board["check"]:
screen.fill(ORANGE, input_board[the_king.getPosition()]["rect"])
for piece in pieces:
the_image = pygame.image.load(piece.get_icon())
if draw_piece(piece) != (-100, -100):
screen.blit(the_image, draw_piece(piece))
pygame.display.flip()
pygame.quit()
|
5838e3917920808c9790cc93a1cb94abafb27e3b | ksomemo/Competitive-programming | /yukicoder/problems/level3.0/0572/0572.py | 375 | 3.546875 | 4 | def main():
n = int(input())
m = int(input())
def argmax(xs):
return sorted(enumerate(xs),
key=lambda x: x[1])[-1]
code = [
list(map(int, input().split()))
for _ in range(m)
]
from pprint import pprint
pprint(code)
for c in code:
print(argmax(c))
if __name__ == '__main__':
main()
|
34910c05c75b315bc803ba219586d60b8ab0f4b0 | vabbybansal/Java | /Others/codes/DFS_state_locally_trav 695. Max Area of Island.py | 2,693 | 3.78125 | 4 | # Learning
# 1) Baking it further - varible sum in recursion function passed over locally, no global class variable used
# 2) used constant space by changing the input - marking visited node as -1
# Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
#
# Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
#
# Example 1:
#
# [[0,0,1,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,1,1,0,0,0],
# [0,1,1,0,1,0,0,0,0,0,0,0,0],
# [0,1,0,0,1,1,0,0,1,0,1,0,0],
# [0,1,0,0,1,1,0,0,1,1,1,0,0],
# [0,0,0,0,0,0,0,0,0,0,1,0,0],
# [0,0,0,0,0,0,0,1,1,1,0,0,0],
# [0,0,0,0,0,0,0,1,1,0,0,0,0]]
# Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
# Example 2:
#
# [[0,0,0,0,0,0,0,0]]
# Given the above grid, return 0.
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if len(grid) == 0:
return 0
areaCurrentMax = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
area = self.startDFS(row, col, grid, 0)
if area > areaCurrentMax:
areaCurrentMax = area
return areaCurrentMax
def startDFS(self, row, col, grid, currentSum):
# Check for validity
if row < 0 or col < 0 or row >= len(grid) or col >= len(grid[0]):
return currentSum
# check if visited
if grid[row][col] == -1 or grid[row][col] == 0:
return currentSum
# Mark visited
grid[row][col] = -1
# increment sum
currentSum += 1
# Traverse in all directions
currentSum = self.startDFS(row+1, col, grid, currentSum)
currentSum = self.startDFS(row-1, col, grid, currentSum)
currentSum = self.startDFS(row, col+1, grid, currentSum)
currentSum = self.startDFS(row, col-1, grid, currentSum)
return currentSum
obj = Solution()
print obj.maxAreaOfIsland([[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]])
print obj.maxAreaOfIsland([[0,0,0,0,0,0,0,0]]) |
4a9d536187abe7763af32704ef898eac453fb8fe | KushalkumarUmesh/Internal-Initiative | /GoalSheet/empDash_Goalsheet_OnlineExam/realapp/shared/readconfig/appconfig.py | 1,258 | 3.53125 | 4 | import openpyxl
class AppConfig(object) :
def __init__(self, configInfile) :
self.configInfile = configInfile
self.attribute = {} # Dict of Attributes
self.readConfigFile()
#Reading the file, and save keyValue pairs, convert everything into String
def readConfigFile(self) :
conf_wb = openpyxl.load_workbook(self.configInfile)
ws = conf_wb.worksheets[0]
c_row = 0
circuitBreaker = 100
while circuitBreaker :
c_row += 1
circuitBreaker -= 1
c = ws.cell(row=c_row, column=1).value
v = ws.cell(row=c_row, column=2).value # Value
if c :
c=str(c) # Convert to String, just to be sure
c= c.strip() # Remove white space
v=str(v) # All Values are also treated as strings, its for the program to ensure that its correct number
v= v.strip() # Remove white space
if c == "END" : break
if v :
self.attribute[c] = v
else :
print("Variable{0} is does not have a value.format(c)")
return(1)
else :
continue
return (0) |
2f6b1f2e00b169f38bdfff98008525405b3856e5 | ayumitanaka13/python-basic | /basic/base14.py | 603 | 3.796875 | 4 | # セットの関数
s = {'a', 'b', 'c', 'd'}
t = {'c', 'd', 'e', 'f'}
u = s | t # 和集合
u = s.union(t) # 和集合
print(u)
u = s & t # 積集合
u = s.intersection(t)
print(u)
u = s - t # 差集合
u = s.difference(t)
print(u)
u = s ^ t
u = s.symmetric_difference(t)
print(u)
s |= t # => s = s | t => sがsとtの和集合=>sにtの要素が入る
print(s)
# issubset, issuperset, isdisjoint
s = {'apple', 'banana'}
t = {'apple', 'banana', 'lemon'}
u = {'cherry'}
print(s.issubset(t))
print(s.issuperset(t))
print(t.isdisjoint(s))
print(t.isdisjoint(u)) |
b08287d65dddc19f8087fc1c88a7df9155c55060 | azhu51/leetcode-practice | /contest/easy_5396.py | 468 | 3.65625 | 4 |
# https://leetcode-cn.com/contest/biweekly-contest-26/problems/consecutive-characters/
class Solution:
def maxPower(self, s: str) -> int:
prev = ""
max = -1
res = 0
for word in s:
if word != prev:
res = 1
if res >= max:
max = res
if word == prev:
res = res + 1
if res >= max:
max = res
prev = word
return max
s = Solution()
print(s.maxPower(s = "hooraaaaaaaaaaay")) |
3ceed8b359fe0b704bed8029f9493d41eac70be6 | DynamiteJohnny/final_project_methods | /proyecto.py | 3,059 | 3.78125 | 4 | import ciw
import math
print("\nMétodos Cuantitativos y simulación\nAlumnos:\n\tShara Teresa González Mena\n\tEsteban Quintana Cueto\n\tJuan Luis Suarez Ruiz\n")
print("\n Proyecto final: Simulación de un sistema de colas\n")
l = float(input("\n Introduce el valor de lambda: "))
miu = float(input("\n Introduce el valor de miu: "))
servers = int(input("\n Introduce el número de servidores: "))
# Define what the system looks like by creating a network object: number of servers, arrival distribution (lambda)
# and service distribution (miu)
System = ciw.create_network(
# Specify that the distribution of arrivals is exponential
Arrival_distributions = [['Exponential', l]],
Service_distributions = [['Exponential', miu]],
Number_of_servers = [servers]
)
p = l / (servers * miu)
aux = l / miu
aux1 = 0
for n in range(servers):
aux1 += pow(aux, n) / math.factorial(n)
aux2 = pow(aux, servers) / (math.factorial(servers) * (1 - p))
p0 = 1 / (aux1 + aux2)
lq = (pow(aux, servers) * p0 * p) / (math.factorial(servers) * pow(1 - p, 2))
wq = lq / l
ws = wq + 1 / miu
ls = l * ws
print("\n---- MEDIDAS DE DESEMPEÑO -------\n")
print("\tlambda=%f \n\tmiu=%f \n\tNumero de Servidores=%d" % (l, miu, servers))
print("p=%f p0=%f Ls=%f Lq=%f Ws=%f Wq=%f\n" % (p, p0, ls, lq, ws, wq))
# Set a seed
ciw.seed(1)
# Object Sim is created with three nodes: arrival node where customers are created (Sim.nodes[0]), service node where
#customers queue up to receive service (Sim.nodes[1]) and the exit node where customers leave the system (Sim.nodes[-1])
Sim = ciw.Simulation(System)
clients = int(input("\n Clientes: "))
# The time is based on the unit of time used for calculating the miu and the lambda
Sim.simulate_until_max_customers(clients, progress_bar=False)
records = Sim.get_all_records()
records.sort()
Sim.write_records_to_file('simulation.txt', headers=True)
# After the simulation, the Sim object remains in the same state as it reached at the end so it can give you information
service_start = [r.service_start_date for r in records]
queue_size_at_departure = [r.queue_size_at_departure for r in records]
arrival_date = [r.arrival_date for r in records]
exit_date = [r.exit_date for r in records]
print("\n---- CLIENTES -----\n")
#De la guia de la libreria
service_time = [r.service_time for r in records]
waiting_time = [r.waiting_time for r in records]
mediaservicio = sum(service_time) / len(service_time)
mediaespera = sum(waiting_time) / len(waiting_time)
mediacola = sum(queue_size_at_departure) / len(queue_size_at_departure)
for i in range(len(records)):
print("Cliente %d -> t espera: %0.4f | t servicio: %0.4f | Llegada: %0.4f | Salida: %0.4f" % (i, waiting_time[i], service_time[i], arrival_date[i], exit_date[i]))
print("\n---- ESTADÍSTICAS ----\n")
print("Máximo tiempo de espera: %f" % max(waiting_time))
print("Mínimo tiempo de espera: %f" % min(waiting_time))
print("Promedio de tiempo de servicio: %f" % mediaservicio)
print("Promedio de tiempo de espera: %f" % mediaespera)
print("Promedio de fila: %f" % mediacola)
print("\n")
|
90bb31c28ba80ddc6c6081f383682b969eccb176 | iamtu/leetcode | /graph/dfs.py | 819 | 3.8125 | 4 | from __future__ import print_function
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs_recursive(visited, graph, node):
if node not in visited:
print (node, end= ' ')
visited.add(node)
for neighbour in graph[node]:
dfs_recursive(visited, graph, neighbour)
# Driver Code
dfs_recursive(visited, graph, 'A')
print ('\n')
def dfs_stack(graph, node):
stack = [node]
visited = set()
while stack:
cur_node = stack.pop()
print (cur_node, end=' ') #visit node
visited.add(cur_node)
for child in graph[cur_node]:
if child not in visited:
stack.append(child)
dfs_stack(graph, 'A') |
5347a67c5f048e17c39753684dba43dc18a492ba | V-Plum/ITEA | /homework_9/pw_manager_json.py | 12,420 | 3.65625 | 4 | """
This program requires Tkinter and PySimpleGUI to run, because of used GUI
To install Tkinter use your terminal and enter:
$ sudo apt-get install python3-tk
To install PySimpleGUI use your terminal and enter:
$ pip install PySimpleGUI
"""
import string
import PySimpleGUI as sg
import secrets
import json
ukr = "абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ"
char_set = string.ascii_letters + string.digits + string.punctuation + ukr + " "
# char_set = string.ascii_letters + string.digits + string.punctuation + " "
file_name = ""
file_key = ""
def main():
layout = [[sg.Text('Do you want to work with file or with text?')],
[sg.Button('File'), sg.Button('Text')]]
window = sg.Window('Choose scenario', layout)
while True:
event, values = window.read()
window.close()
if event == 'Text':
encryption()
exit()
elif event is None:
exit()
elif event == 'File':
file_decoded = open_create_file()
names_list = list(file_decoded.keys())
layout = [[sg.Text('Search is case sensitive:')],
[sg.Input(size=(40, 1), enable_events=True, key='-INPUT-')],
[sg.Text('Select to show, edit or delete password:')],
[sg.Listbox(names_list, size=(40, 10), enable_events=True, key='-LIST-')],
[sg.Button('Add'), sg.Button('Save'), sg.Button('Exit')]]
window = sg.Window('Passwords', layout)
while True:
event, values = window.read()
if event == '-LIST-' and len(values['-LIST-']):
item = "".join(values['-LIST-'])
item_value = file_decoded[item]
modified_item = modify_item(item, item_value)
if modified_item:
for key in modified_item:
if key == item and modified_item[item] != "":
confirm = sg.PopupYesNo(f"Do you want to overwrite {key}?", title="Record Exist!")
if confirm == "Yes":
file_decoded.update(modified_item)
elif key == item and modified_item[item] == "":
file_decoded.pop(item)
else:
confirm = sg.PopupYesNo(f"Do you want to add new record {key}?", title="New record")
if confirm == "Yes":
file_decoded.update(modified_item)
names_list = list(file_decoded.keys())
window['-LIST-'].update(names_list)
if event == "Add":
new_item = modify_item("Add", "Password")
if new_item:
for key in new_item.keys():
if key in file_decoded.keys():
confirm = sg.PopupYesNo(f"Do you want to overwrite {key}?", title="Record Exist!")
if confirm == "Yes":
file_decoded.update(new_item)
else:
file_decoded.update(new_item)
names_list = list(file_decoded.keys())
window['-LIST-'].update(names_list)
if event in (None, 'Exit'): # always check for closed window
save = sg.PopupYesNo("Do you want to save file before exit?", title="Save?")
if save == "Yes":
window.close()
encrypt_and_save(file_decoded)
exit()
if save == "No":
window.close()
exit()
if save is None:
continue
if event == 'Save':
encrypt_and_save(file_decoded)
if values['-INPUT-'] != '': # if a keystroke entered in search field
search = values['-INPUT-']
new_values = [x for x in names_list if search in x] # do the filtering
window['-LIST-'].update(new_values) # display in the listbox
else:
# display original unfiltered list
window['-LIST-'].update(names_list)
window.close()
def open_create_file():
global file_name
while True:
file_name = sg.PopupGetFile('Please enter a file name')
if not file_name:
exit()
try:
file = open(file_name, "r+")
break
except FileNotFoundError:
create = sg.PopupYesNo(f'File {file_name} not found. Do you want to create it?')
if create == "Yes":
file = open(file_name, "w+")
break
elif create in (None, "No"):
continue
file_content = file.read()
if file_content:
file_decoded = decode_file(file_content)
else:
file_decoded = {}
return file_decoded
def decode_file(file_content):
global file_key
layout = [[sg.Text('Please enter a key to decrypt the file'), sg.InputText(key="entered_key")],
[sg.Button('Ok', bind_return_key=True), sg.Button('Cancel')]]
window = sg.Window("Decrypt file", layout)
while True:
event, values = window.read()
if event in (None, "Cancel"):
exit()
if event == 'Ok' or event.startswith('Enter'):
key_word = values["entered_key"]
while len(key_word) < len(file_content):
key_word = key_word + values["entered_key"]
key_word = key_word[:len(file_content)]
decoded_json = decode(file_content, key_word)
try:
decoded_file = json.loads(decoded_json)
except json.decoder.JSONDecodeError:
sg.Popup('Key is wrong')
continue
file_key = values["entered_key"]
window.close()
return decoded_file
def modify_item(item, item_value):
layout = [[sg.Text('Service name:')],
[sg.InputText(item, size=(40, 1), key=0)],
[sg.Text(f'Password (leave blank to delete {item} from list):')],
[sg.InputText(item_value, size=(40, 1), key=1)],
[sg.Button('Generate random password'), sg.Button('Ok'), sg.Button('Cancel')]]
window = sg.Window(f'{item} Password', layout)
while True:
event, values = window.read()
if event in (None, "Cancel"):
window.close()
return
if event == 'Ok':
item = values[0]
item_value = values[1]
if not item:
sg.Popup('Name can not be empty')
continue
if not item_value:
delete = sg.PopupYesNo(f'This will delete {item} from your list. Continue?', title="Warning!")
if delete == "Yes":
window.close()
modified_item = {item: item_value}
return modified_item
if delete == "No" or delete is None:
continue
window.close()
modified_item = {item: item_value}
return modified_item
if event == "Generate random password":
item_value = generate_password()
window[1].update(item_value)
def generate_password(pass_size=8):
char_set = ""
layout = [[sg.Text('Enter password size:')],
[sg.InputText(pass_size, size=(20, 1), key=0)],
[sg.Checkbox('English lowercase', default=True, key="lower"), sg.Checkbox('English UPPERCASE', default=True, key="upper")],
[sg.Checkbox('digits', default=True, key="digits"), sg.Checkbox('Special symbols', default=True, key="specials"), sg.Checkbox('Ukrainian symbols', key="ukr")],
[sg.Button('Ok'), sg.Button('Cancel')]]
window = sg.Window('Generate Password', layout)
while True:
event, values = window.read()
if event in (None, "Cancel"):
window.close()
return
if event == 'Ok':
if values["lower"]:
char_set += string.ascii_lowercase
if values["upper"]:
char_set += string.ascii_uppercase
if values['digits']:
char_set += string.digits
if values["specials"]:
char_set += "~!@$%^&*()_-+="
if values["ukr"]:
char_set += "абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ"
if not values[0] or not char_set:
sg.Popup('Size and character set can not be empty')
continue
else:
pass_size = int(values[0])
window.close()
password = ''.join(secrets.choice(char_set) for i in range(pass_size))
return password
def encrypt_and_save(decoded_file):
global file_key
layout = [[sg.Text('Please enter a new key to encrypt the file'), sg.InputText(file_key)],
[sg.Button('Ok', bind_return_key=True), sg.Button('Cancel')]]
window = sg.Window("Encrypt and save file", layout)
while True:
event, values = window.read()
if event in (None, "Cancel"):
sg.Popup("File NOT saved")
window.close()
return
if event == 'Ok' or event.startswith('Enter'):
new_file_key = values[0]
if new_file_key:
file_key = new_file_key
window.close()
break
else:
sg.Popup('Key is wrong')
to_encode = json.dumps(decoded_file)
print(to_encode)
print(type(to_encode))
key_word = file_key
while len(key_word) < len(to_encode):
key_word = key_word + file_key
key_word = key_word[:len(to_encode)]
print(key_word)
encoded_file = encode(to_encode, key_word)
print(encoded_file)
with open(file_name, 'w+') as f:
f.write(encoded_file)
sg.Popup("File saved")
def create_names_list(file_decoded):
names_list = [item[0] for item in file_decoded]
return names_list
def encryption():
layout = [[sg.Text('Enter text to code'), sg.InputText()],
[sg.Text('Enter key'), sg.InputText()],
[sg.Radio('Encode', "RADIO1", default=True, size=(10, 1)), sg.Radio('Decode', "RADIO1")],
[sg.Button('Ok'), sg.Button('Cancel')]]
window = sg.Window('Encrypt your text!', layout)
while True:
event, values = window.read()
if event in (None, 'Cancel'):
exit()
if event is 'Ok':
to_code = values[0]
key = values[1]
direction = values[2]
window.close()
break
while len(key) < len(to_code):
key = key + key
key = key[:len(to_code)]
if direction:
result = encode(to_code, key)
elif not direction:
result = decode(to_code, key)
layout = [[sg.Text('Resulting text is:')],
[sg.InputText(result)],
[sg.Button('Close')]]
window = sg.Window('Vigenere result', layout)
while True:
event, values = window.read()
if event in (None, 'Close'):
break
window.close()
def encode(text, key):
coded = ""
for i in range(0, len(text)):
to_code_sym_index = char_set.find(text[i])
key_sym_index = char_set.find(key[i])
char_row = char_set[key_sym_index:] + char_set[:key_sym_index]
done_sym = char_row[to_code_sym_index]
coded = coded + done_sym
return coded
def decode(text, key):
decoded = ""
for i in range(0, len(text)):
key_sym_index = char_set.find(key[i])
char_row = char_set[key_sym_index:] + char_set[:key_sym_index]
to_decode_sym_index = char_row.find(text[i])
done_sym = char_set[to_decode_sym_index]
decoded = decoded + done_sym
return decoded
if __name__ == "__main__":
main()
|
97343ea451d8731fe499a844b405e90d46b99238 | novigit/learn_ete3 | /06_check_monophyly.py | 3,034 | 3.671875 | 4 | #!/usr/bin/env python
from ete3 import Tree
t = Tree("((((((a, e), i), o),h), u), ((f, g), j));")
print(t)
# /-a
# /-|
# /-| \-e
# | |
# /-| \-i
# | |
# /-| \-o
# | |
# /-| \-h
# | |
# | \-u
# --|
# | /-f
# | /-|
# \-| \-g
# |
# \-j
# check if all vowels are monophyletic, and if not, what their phyly is
print(t.check_monophyly(values=["a","e","i","o","u"], target_attr="name"))
## (False, 'polyphyletic', {Tree node 'h' (-0x7fffffffee25ea2a)})
# check if subset of vowels are monophyletic
print(t.check_monophyly(values=["a","e","i","o"], target_attr="name"))
## (True, 'monophyletic', set())
# these vowels are paraphyletic (a specific case of polyphyly)
print(t.check_monophyly(values=["i", "o"], target_attr="name"))
# (False, 'paraphyletic', {Tree node 'e' (0x117646a2), Tree node 'a' (0x1176469b)})
## .get_monophyletic
## returns a list of nodes that are monophyletic in a certain trait
## trait is usually defined as an attribute of the tree node
t = Tree("((((((4, e), i), o),h), u), ((3, 4), (i, june)));")
print(t)
# /-4
# /-|
# /-| \-e
# | |
# /-| \-i
# | |
# /-| \-o
# | |
# /-| \-h
# | |
# | \-u
# --|
# | /-3
# | /-|
# | | \-4
# \-|
# | /-i
# \-|
# \-june
# annotate the tree
# colors is a dictionary
colors = {
"a":"red",
"e":"green",
"i":"yellow",
"o":"black",
"u":"purple",
"4":"green",
"3":"yellow",
"1":"white", "5":"red",
"june":"yellow"
}
# .get() is a dictionary method that returns the value (the color) of the requested key (the leaf)
# the second argument of .get() states the value that should be returned ("None"), if the requested key (the leaf) is not found
# the for loop below adds a color to a leaf, leaf by leaf
for leaf in t:
leaf.add_features(color=colors.get(leaf.name, "none"))
# just printing t doesnt show the features
print(t)
# requires the .get_ascii() method
print(t.get_ascii(attributes=["name", "color"], show_internal=False))
# /-4, green
# /-|
# /-| \-e, green
# | |
# /-| \-i, yellow
# | |
# /-| \-o, black
# | |
# /-| \-h, none
# | |
# | \-u, purple
# --|
# | /-3, yellow
# | /-|
# | | \-4, green
# \-|
# | /-i, yellow
# \-|
# \-june, yellow
# find nodes that are monophyletic for containing either green or yellow
print("Green-yellow clusters:")
for node in t.get_monophyletic(values=["green","yellow"], target_attr="color"):
print(node.get_ascii(attributes=["color","name"], show_internal=False))
# Green-yellow clusters:
# /-green, 4
# /-|
# --| \-green, e
# |
# \-yellow, i
# /-yellow, 3
# /-|
# | \-green, 4
# --|
# | /-yellow, i
# \-|
# \-yellow, june
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.