blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
892718dbb986a43065c93d4faa91331260ddb7eb | Ali-Doggaz/CandidateDocsParser-To1PDF-Converter | /To_PDF_Converter.py | 4,059 | 3.515625 | 4 | from PIL import Image
import os
from fpdf import FPDF
import win32com.client
ROOT = os.path.abspath(os.curdir)
WDFORMATPDF = 17
PPTTOPDF = 32
def convert_image_to_pdf(File_Path, name):
try:
image1 = Image.open(File_Path)
im1 = image1.convert('RGB')
im1.save('PDF_Converted_Files' + os.sep + f'{name}.pdf')
except:
print("Could not open document " + File_Path)
def convert_doc_to_pdf(name):
"""
:param name: (string) Name of the file to convert. (i.e: test.doc, Resume_Mohamed.docx)
Converts docx, doc, dotm, docm, odt, and rtf files to readable pdf. The resulting PDF will have the same name
as the original file. Moreover, it will be stored in the "PDF_Converted_Files' folder.
"""
try:
in_file = ROOT + os.sep + "Files" + os.sep + name
word = win32com.client.Dispatch('Word.Application')
word.Visible = 0 # ADD IN CASE DOCUMENT OPENS EVERY TIME
doc = word.Documents.Open(in_file)
doc.SaveAs(ROOT + os.sep + "PDF_Converted_Files" + os.sep + f"{name}.pdf", WDFORMATPDF)
doc.Close()
word.Quit()
except:
print("Could not open document " + 'Files' + os.sep + name)
def convert_txt_to_pdf(name):
"""
:param name: (string) Name of the file to convert. (i.e: test.txt, Resume_Mohamed.txt)
Converts .txt files to readable pdf. The resulting PDF will have the same name
as the original file. Moreover, it will be stored in the "PDF_Converted_Files' folder.
"""
try:
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
f = open("Files" + os.sep + name, "r")
for x in f:
pdf.cell(200, 10, txt=x, ln=1, align='C')
pdf.output("PDF_Converted_Files" + os.sep + f"{name}.pdf")
except:
print("Could not open document " + 'Files' + os.sep + name)
def convert_powerpoint_to_pdf(name):
"""
:param name: (string) Name of the file to convert. (i.e: Motivation.ppt, Resume_Mohamed.pptx)
Converts .ppt and .pptx files to readable pdf. The resulting PDF will have the same name
as the original file. Moreover, it will be stored in the "PDF_Converted_Files' folder.
"""
try:
in_file = ROOT + os.sep + "Files" + os.sep + name
powerpoint = win32com.client.Dispatch("Powerpoint.Application")
deck = powerpoint.Presentations.Open(in_file, WithWindow=False)
deck.SaveAs(ROOT + os.sep + "PDF_Converted_Files" + os.sep + f"{name}.pdf",
PPTTOPDF) # formatType = 32 for ppt to pdf
deck.Close()
powerpoint.Quit()
except:
print("Could not open document " + 'Files' + os.sep + name)
def Convert_Files_To_PDFs():
"""
Converts all files in the folder "Files" to PDF.
Compatible file types: jpg,jpeg,png,docx,doc,dotm,docm,odt,rtf,txt,pdf
Remark: Incompatible file types will be ignored, and an error message with the file's name
will be displayed in the console.
"""
for name in os.listdir("Files"):
if (name.endswith('.jpeg') or name.endswith('.jpg') or name.endswith('.png')):
convert_image_to_pdf('Files' + os.sep + name, name)
elif name.endswith('pdf'):
in_file = ROOT + os.sep + "Files" + os.sep + name
os.rename(in_file, "PDF_Converted_Files/" + os.sep + f"{name}.pdf")
elif name.endswith(".docx") or name.endswith(".dotm") or name.endswith(".docm") or name.endswith('.doc') or \
name.endswith(".odt") or name.endswith(".rtf"):
convert_doc_to_pdf(name)
elif name.endswith(".txt"):
convert_txt_to_pdf(name)
elif name.endswith(".ppt") or name.endswith(".pptx"):
convert_powerpoint_to_pdf(name)
else:
print("[ERROR] File format incompatible: " + 'Files' + os.sep + name)
|
ad0d9a4cbc5e6d196e6b869388c023f710e78b81 | Saccha/Exercicios_Python | /secao06/ex10.py | 254 | 3.734375 | 4 | '''
10. Faça um programa que calcule e mostre a soma dos 50 primeiros números pares.
'''
a1 = int(input('Digite o a1: '))
n = int(input('Digite o n: '))
r = int(input('Digite o r: '))
an = a1 + ((n - 1) * r)
sn = (((a1 + an) * n) / 2)
print(an, sn)
|
362ba708fe9e379838e8a6855e447255fe0acc17 | ysads/usp-math | /mac0338/L5E2.py | 240 | 3.609375 | 4 | def quocient(n):
if n == 1:
return 1
return 11 * quocient(n-1) + 12
def print_quocient(n):
print(n, "=>", quocient(n))
print_quocient(n=1)
print_quocient(n=2)
print_quocient(n=3)
print_quocient(n=4)
print_quocient(n=5)
|
771dfc60fc0222c226a1cf39ea6733ee1bb696df | Vasiliy1982/repo24122020 | /python/DZ_Python_№5_2.py | 447 | 3.953125 | 4 | # DZ_Python_№5_2
metrs = int(input("Введите некоторое количество метров:"))
mili = metrs * 0.000621371
inch = metrs * 0.0254
yard = metrs * 0.9144
print("Если хотите перевести метры в мили введите 1, если в дюймы 2 в ярды 3")
choice = input()
if choice == "1":
print(mili)
if choice == "2":
print(inch)
if choice == "3":
print(yard) |
c8bf90b9f830dcbe59e7f8f74102c2cb7825514a | VarshaRadder/APS-2020 | /Code library/126.Sum vs XOR.py | 410 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:12:05 2020
@author: Varsha
"""
import math
import os
import random
import re
import sys
def sumXor(n):
b=bin(n)[2:]
t=0
for i in range(len(b)-1,-1,-1):
if b[i]=='0':
t+=1
if n>0:
return 2**t
else:
return 1
n = int(input().strip())
result = sumXor(n)
print(result) |
400baf9caaa32f60d1ca54bd06e38714fa2ad73e | stwcloudy/LeetCode | /Medium/92. Reverse Linked List II.py | 959 | 3.75 | 4 | """
思路:
类似与全部链表反转的题,为了处理头结点翻转,加入一个虚头结点
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head or not head.next:
return head
dummy = ListNode(-1)
dummy.next = head
pre = dummy
diff = n - m
m -= 1
while m:
pre = pre.next ##翻转前的结点
m -= 1
print diff
cur = pre.next
for i in range(diff):
if cur.next:
post = cur.next
cur.next = post.next
post.next = pre.next
pre.next = post
return dummy.next
|
f55472b846f47dbae145f1e7b1e8eec97211fff3 | zevelijah/My-Homework | /H1.py | 479 | 3.71875 | 4 | def meadian(Alist):
check_list = type(Alist) is list
if check_list != True:
return 'list only'
val = 0
for x in Alist:
val += 1
VAL = val/2
if VAL.is_integer() == False:
Alist.sort()
VAL = int(VAL)
return Alist[VAL]
if VAL.is_integer() == True:
Alist.sort()
val0 = VAL-1
val0 = int(val0)
print(type(val0))
return Alist[VAL]
return None
print(meadian([2, 1, 3, 4])) |
b6f4b5e43c059b441a01897b3537cdea6d36ef75 | Sjj1024/Sjj1024 | /src/utils/test.py | 150 | 3.859375 | 4 | import copy
a = [1, 2, 3]
b = [4, 5, a]
c = copy.copy(b)
c[1] = 7
c[2].append(6)
print(b)
d = copy.deepcopy(b)
d[1] = 8
d[2].append(9)
print(b)
|
4865132c9fd49b5d68fb4136d8d94a094cf1677f | adam-hotait/information_retrieval | /boolean_search.py | 2,651 | 3.90625 | 4 | import time
### Modèle de recherche booléen
"""
Using infix form allow us not to use parenthesis
What do to when we read something in the request?
- word => get posting
- NOT => get the complementary of the recursive call result
- AND => get the intersection of the two next recursive call results
- OR => get the union of the two next recursive call results
example:
AND teletype OR console debugging
"""
class NotExpr(Exception):pass
def get_complementary_posting(posting, collection_size):
return set(range(1,collection_size+1)).difference(posting)
def get_posting(word, index, wordDic):
try:
return set(doc[0] for doc in index[wordDic[word]])
except KeyError:
return set()
def analyse_expr(request, index, wordDic, collection_size):
current = request.pop(0)
# NOT
if current == 'NOT':
# right after the negation is a word
nextword = request.pop(0).lower()
# we build the posting of this word
posting = get_posting(nextword, index, wordDic)
# return the complement
return get_complementary_posting(posting, collection_size)
# OR
elif current == 'OR':
# deal with the first expression
first = analyse_expr(request, index, wordDic, collection_size)
# deal with the second expression
second = analyse_expr(request, index, wordDic, collection_size)
# return the union of the postings
return first.union(second)
# AND
elif current == 'AND':
# deal with the first expression
first = analyse_expr(request, index, wordDic, collection_size)
# deal with the second expression
second = analyse_expr(request, index, wordDic, collection_size)
# return the intersection of the expression
return first.intersection(second)
# it's a word
else:
return get_posting(current.lower(), index, wordDic)
def boolean_search(query: str, collection_size: int, index: dict, wordDic:dict, time_it=False):
"""
Boolean search algorithm implementation.
:param query: boolean expression describing the query
:param collection_size: number of documents in the collection
:param index: inverted index of the collection
:param wordDic: word to wordID dictionnary
:param time_it: boolean to enable performance measures
:return:
"""
request = query.split()
if time_it:
timeBeginningRequest = time.time()
res = sorted(list(analyse_expr(request, index, wordDic, collection_size)))
if time_it:
return res, time.time() - timeBeginningRequest
else:
return res |
c28a1783ecf0a10b8ef5ba0563617a96b09d5883 | ZongLin1105/PythonTest | /6-F.py | 136 | 3.59375 | 4 | n = eval(input())
a = 1
#print(1, end=" ")
b = 1
#print(1, end=" ")
i = 3
while i <= n:
a, b = b, a+b
i += 1
print(b, end=" ") |
666cbfa0941b36c547c062502655527859bb65e5 | deepakbhavsar43/Python-to-ML | /13_01_2020_Duck_Typing_and_Decorator/Decorater_for_Function.py | 632 | 4.09375 | 4 | # Python program to illustrate
# closures
# import logging
# logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
def log_func(*args):
# logging.info( 'Running "{}" with arguments {}'.format(func.__name__, args))
print(func(*args))
# Necessary for closure to work (returning WITHOUT parenthesis)
return log_func
@logger
def add(x, y):
return x + y
@logger
def sub(x, y):
return x - y
# add_logger = logger(add)
# sub_logger = logger(sub)
#
# add_logger(3, 3)
# add_logger(4, 5)
#
# sub_logger(10, 5)
# sub_logger(20, 10)
add(3,3)
add(4,5)
sub(10,5)
sub(20,10) |
a8b6d64839870a169c29d84fb3fd0da3cc14288d | baaaam771/algorithm_question | /2단계/9498.py | 252 | 3.859375 | 4 | num = int(input())
def score(i):
if 90 <= i <= 100:
return "A"
elif 80 <= i < 90:
return "B"
elif 70 <= i < 80:
return "C"
elif 60 <= i < 70:
return "D"
else:
return "F"
print(score(num))
|
8c8a0a8d6c0917b5197bed42ad87d7fc28f2e68e | zhangtianyu07/store | /day16test/TestBank.py | 3,216 | 3.53125 | 4 | import unittest
from Bank_addUser import Bank
from Address import Address
from User import User
class TestAddUser(unittest.TestCase): # 类就是单元测试的子类
bank = None
user = None
address = None
def setUp(self) -> None:
self.bank = Bank()
self.user = User()
self.address = Address()
def test_AddUser(self):
# 1.准备测试数据
self.user.setAccount("asd12345")
self.user.setUsername("zyu")
self.user.setPassword(123456)
self.address.setCountry("中国")
self.address.setProvince("中国")
self.address.setStreet("中国")
self.address.setDoor("s008")
#预期结果
JG = 1
# 调用被测方法
status = self.bank.bank_addUser(self.user.getAccount(),self.user.getUsername(),self.user.getPassword(),self.address.getCountry(),self.address.getProvince(),self.address.getStreet(),self.address.getDoor())
status = int(status)
# 断言
self.assertEqual(JG,status)
def test_AddUser1(self):
# 1.准备测试数据
self.user.setAccount("12345670")
self.user.setUsername("zyu")
self.user.setPassword(123456)
self.address.setCountry("中国")
self.address.setProvince("中国")
self.address.setStreet("中国")
self.address.setDoor("s008")
#预期结果
JG = 2
# 调用被测方法
status = self.bank.bank_addUser(self.user.getAccount(),self.user.getUsername(),self.user.getPassword(),self.address.getCountry(),self.address.getProvince(),self.address.getStreet(),self.address.getDoor())
status = int(status)
# 断言
self.assertEqual(JG,status)
# def test_AddUser2(self):
# # 1.准备测试数据
# self.user.setAccount("12345670")
# self.user.setUsername("zyu")
# self.user.setPassword(123456)
# self.address.setCountry("中国")
# self.address.setProvince("中国")
# self.address.setStreet("中国")
# self.address.setDoor("s008")
#
# #预期结果
# JG = 2
# # 调用被测方法
# status = self.bank.bank_addUser(self.user.getAccount(),self.user.getUsername(),self.user.getPassword(),self.address.getCountry(),self.address.getProvince(),self.address.getStreet(),self.address.getDoor())
# status = int(status)
#
# # 断言
# self.assertEqual(JG,status)
def test_AddUser3(self):
# 1.准备测试数据
self.user.setAccount("12345670")
self.user.setUsername("zyu")
self.user.setPassword(123456)
self.address.setCountry("中国")
self.address.setProvince("中国")
self.address.setStreet("中国")
self.address.setDoor("s008")
#预期结果
JG = 3
# 调用被测方法
status = self.bank.bank_addUser(self.user.getAccount(),self.user.getUsername(),self.user.getPassword(),self.address.getCountry(),self.address.getProvince(),self.address.getStreet(),self.address.getDoor())
status = int(status)
# 断言
self.assertEqual(JG,status)
|
cefb4d3c6e71bd41d09290df042a4e6e531bd8c4 | stephanephanon/data_structures | /queue.py | 8,233 | 4.375 | 4 | """
Implement a queue api in python
"""
from abc import ABCMeta, abstractmethod
# --------------------------------
# Queue API
# --------------------------------
from linked_lists import LinkedList
class QueueException(Exception):
"""
QueueABC should raise QueueException for queue errors such as:
1. no element for first
2. no element to dequeue
"""
pass
class QueueABC(metaclass=ABCMeta): # pragma: no cover
"""
The queueABC provides the api for a queue data structure (FIFO)
It also supports the python methods len() and next()
"""
@abstractmethod
def enqueue(self, x):
"""
Add an element to the back of the queue
:param x: object to add
:return:
:raise: TypeError if nothing is queued
"""
pass
@abstractmethod
def dequeue(self):
"""
Remove and return the element at the front of the queue
:return: element at front
:raise: QueueException if empty queue
"""
pass
@abstractmethod
def first(self):
"""
Examine and return the element at the front of the queue
:return: first element
:raise: QueueException if empty queue
"""
pass
@abstractmethod
def is_empty(self):
"""
Return true if queue is empty else False
:return: True or False
"""
pass
@abstractmethod
def size(self):
"""
Return the number of elements in the queue
:return: number of elements
"""
pass
# ----------------------------------------
# Implementation: ArrayQueue
# ----------------------------------------
class CircularArrayQueue(QueueABC):
"""
Implements queuing with a python list for FIFO operations
Note: for the purpose of the exercise, we
pretend that python list does not support arbitrary inserts
"""
def __init__(self, max_queue_size):
"""
Initialize a CircularArrayQueue
:param max_queue_size: max number of items we store in queue
:return:
"""
if max_queue_size <= 0:
raise QueueException("Max_queue_size must be > 0")
self._max_queue_size = max_queue_size
self._array = [None]*max_queue_size
# index of first element
self._front_index = 0
# index of next rear element
self._rear_index = 0
# number of items in the queue
self._count = 0
def first(self):
"""
Examine and return the element at the front of the queue
:return: first element
:raise: QueueException if empty queue
"""
# if there is nothing in the queue then raise an exception
if self.is_empty():
raise QueueException("Cannot fetch first from empty queue")
# fetch our item
return self._array[self._front_index]
def enqueue(self, x):
"""
Add an element to the back of the queue.
Note: this method will wrap around and delete the
items in the front of the line if the queue is full.
:param x: object to add
:return:
:raise: TypeError if nothing is queued
"""
self._array[self._rear_index] = x
self._rear_index = (self._rear_index + 1) % self._max_queue_size
if self._count < self._max_queue_size:
self._count += 1
def __len__(self):
"""
Return the length of the queue
:return: number of elements
"""
return self._count
def size(self):
"""
Return the number of elements in the queue
:return: number of elements
"""
return self._count
def dequeue(self):
"""
Remove and return the first element in the queue
:return: first element
"""
# if there is nothing in the queue then raise an exception
if self.is_empty():
raise QueueException("Cannot dequeue from empty queue")
# fetch our item
ret = self._array[self._front_index]
self._array[self._front_index] = None
self._front_index = (self._front_index + 1) % self._max_queue_size
if self._count > 0:
self._count -= 1
return ret
def is_empty(self):
"""
Return true if queue is empty else False
:return: True or False
"""
return True if self._count == 0 else False
def is_full(self):
"""
Return true if the queue is full.
:return: True or False
"""
return True if self._count == self.max_queue_size else False
@property
def max_queue_size(self):
return self._max_queue_size
# ----------------------------------------
# Implementation: Python List Queue
# ----------------------------------------
class PythonListQueue(QueueABC):
"""
Implementation of the queue data structure
using a python list for FIFO operations
"""
def __init__(self):
self._list = []
def enqueue(self, x):
"""
Add an element to the back of the queue
:param x: object to add
:return:
:raise: TypeError if nothing is queued
"""
self._list.append(x)
def dequeue(self):
"""
Remove and return the element at the front of the queue
:return: element at front
:raise: QueueException if empty queue
"""
try:
return self._list.pop(0)
except IndexError:
raise QueueException("Cannot dequeue from empty queue")
def first(self):
"""
Examine and return the element at the front of the queue
:return:
:raise: QueueException if empty queue
"""
try:
return self._list[0]
except IndexError:
raise QueueException("Cannot fetch first from empty queue")
def is_empty(self):
"""
Return true if queue is empty else False
:return: True or False
"""
return True if len(self._list) == 0 else False
def __len__(self):
"""
Return the length of the queue
:return: number of elements
"""
return len(self._list)
def size(self):
"""
Return the number of elements in the queue
:return: number of elements
"""
return len(self._list)
# ----------------------------------------
# Implementation: LinkedListQueue
# ----------------------------------------
class LinkedListQueue(QueueABC):
"""
Implementation of the queue data structure
using a linked list for FIFO operations
"""
def __init__(self):
self._list = LinkedList()
def first(self):
"""
Examine and return the element at the front of the queue
:return: first element
:raise: QueueException if empty queue
"""
# if there is nothing in the queue then raise an exception
if self.is_empty():
raise QueueException("Cannot fetch first from empty queue")
return self._list.first.element
def enqueue(self, x):
"""
Add an element to the back of the queue.
:param x: object to add
:return:
:raise: TypeError if nothing is queued
"""
self._list.insert_last(x)
def __len__(self):
"""
Return the length of the queue
:return: number of elements
"""
return len(self._list)
def size(self):
"""
Return the number of elements in the queue
:return: number of elements
"""
return len(self._list)
def dequeue(self):
"""
Remove and return the first element in the queue
:return: first element
"""
# if there is nothing in the queue then raise an exception
if self.is_empty():
raise QueueException("Cannot dequeue from empty queue")
return self._list.delete_first()
def is_empty(self):
"""
Return true if queue is empty else False
:return: True or False
"""
return True if len(self._list) == 0 else False
|
9a98e18099eddd25de0b0d0c7fc3f2faa637af22 | udhayprakash/PythonMaterial | /python3/13_OOP/d_magicmethods/06_context_manager.py | 1,247 | 3.703125 | 4 | """
Purpose: Context Manager
"""
# context mangers
# Method 1
f = open("06_context_manager.txt", "w")
f.write("I am good")
f.close()
# Method 2
with open("06_context_manager.txt", "w") as f:
f.write("I am good")
##############################################
class ManagedFile:
def __init__(self, file_name, mode="r"):
self.name = file_name
self.file_operation_mode = mode
def __repr__(self):
return f"{self.name} in {self.file_operation_mode}"
def __enter__(self):
self.file = open(self.name, self.file_operation_mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# f1 = ManagedFile('06_context_manager.txt', 'w')
# print(f1)
with ManagedFile("06_context_manager.txt", "w") as f1:
print(f1)
f1.write("I am good")
###########################################################
class CM:
def __enter__(self):
print("Raing Erro 1")
raise OSError()
return self
def __exit__(self, exc_type, exc_val, exc_tab):
pass
c = CM()
with c:
try:
print("raining valueError2")
raise ValueError()
except ValueError:
print("excepty caght")
|
a9cab26fb0e6fcefeb476360b74548dd72034ca7 | Shashank-1801/Python | /CoinCents/coinProblem-Itr.py | 1,911 | 3.515625 | 4 | """
Author : shekhars@usc.edu
Date: July 12, 2016
"""
import datetime
infy = 99999
p = [infy]*infy
lastCoinUsed = [infy]*infy
p[0] = 0
def coinProb(c):
for j in range(1, c+1):
if c == 0:
return 0
elif c < 1:
return infy
else:
# calculation for coin 1
if (j-1) < 0:
use_1 = infy
else:
use_1 = p[j-1]
# calculation for coin 10
if (j - 10) < 0:
use_10 = infy
else:
use_10 = p[j - 10]
# calculation for coin 30
if (j - 30) < 0:
use_30 = infy
else:
use_30 = p[j - 30]
# calculation for coin 40
if (j - 40) < 0:
use_40 = infy
else:
use_40 = p[j - 40]
# find min of the coins
minVal = min(use_1, use_10, use_30, use_40)
if minVal == use_1:
lastCoinUsed[j] = 1
elif minVal == use_10:
lastCoinUsed[j] = 10
elif minVal == use_30:
lastCoinUsed[j] = 30
else:
lastCoinUsed[j] = 40
# total coins used will be 1 + coin used earlier
coins = 1 + minVal
p[j] = coins
#print(j)
return coins
def main():
print("Coin problem for homework assignment-iterative Solution")
a = datetime.datetime.now()
# print("Coins needed are : " + str(coinProb(21)))
for c in range(1, 61):
print("For " + str(c) + ", Coins needed are : " + str(coinProb(c)))
rem = c
while rem != 0:
print(lastCoinUsed[rem], end=",")
v = lastCoinUsed[rem]
rem = rem - v
print()
b = datetime.datetime.now()
print(b-a)
if __name__ == "__main__":
main()
|
b8c78a295e14e3ad89901c5fc4db4511c15db46d | Ashutosh-gupt/HackerRankAlgorithms | /Sam and sub-strings.py | 1,919 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Problem Statement
Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the
first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one.
If the sub-string is S, Sam has to throw 'S' candies into an initially empty box. At the end of the game, Sam has to
find out the total number of candies in the box, T. As T can be large, Samantha asks Sam to tell T % (109+7) instead.
If Sam answers correctly, he can keep all the candies. Sam can't take all this Maths and asks for your help.
"""
__author__ = 'Danyang'
MOD = 1e9 + 7
class Solution(object):
def solve_TLE(self, cipher):
"""
O(N^2)
:param cipher: the cipher
"""
A = map(int, list(cipher))
f = A[0]
num = A[0]
sig = 1
for i in xrange(1, len(A)):
num = 10 * num + A[i]
sig *= 10
temp = num
temp_sig = sig
while temp_sig >= 1:
f += temp
f %= MOD
temp %= temp_sig
temp_sig /= 10
return int(f)
def solve(self, cipher):
"""
O(N)
example: 1234
1
12, 2
123, 23, 3
1234, 234, 34, 4
:param cipher:
:return:
"""
pre = [0 for _ in cipher]
pre[0] = int(cipher[0])
for i in xrange(1, len(cipher)):
pre[i] = (pre[i - 1] * 10 + int(cipher[i]) * (i + 1)) % MOD
s = 0
for elt in pre:
s = (s + elt) % MOD
return int(s)
if __name__ == "__main__":
import sys
f = open("0.in", "r")
# f = sys.stdin
solution = Solution()
# construct cipher
cipher = f.readline().strip()
# solve
s = "%s\n" % (solution.solve(cipher))
print s,
|
34aaaaa4eaa6462507714e0c06e8a74da1bef391 | fengbingchun/Python_Test | /demo/simple_code/test_None.py | 814 | 3.8125 | 4 | # Blog: https://blog.csdn.net/fengbingchun/article/details/119358832
var = None; print(var) # None
if var is None:
print("var has a value of None") # print
else:
print("var:", var)
print(type(None)) # <class 'NoneType'>
a = ''; print(a == None) # False
b = []; print(b == None) # False
c = 0; print(c == None) # False
d = False; print(c == None) # False
L = [None] * 5; print(L) # [None, None, None, None, None]
def func():
x = 3
obj = func(); print(obj) # None
def func2():
return None
obj2 = func2(); print(obj2) # None
def func3():
return
obj3 = func3(); print(obj3) # None
def func4(x, y=None):
if y is not None:
print("y:", y)
else:
print("y is None")
print("x:", x)
x = [1, 2]; obj4 = func4(x) # y is None
y = [3, 4]; obj4 = func4(x, y) # y: [3, 4]
|
b260822a12567805bbafae6d84e10babe96df8df | stellayk/Python | /ch04/4_3_Tuple.py | 286 | 3.734375 | 4 | t=(10, )
print(t)
t2=(1,2,3,4,5)
print(t2)
print(t2[0], t2[1:4], t2[-1])
for i in t2:
print(i, end=' ')
if 6 in t2:
print("There's 6 in t2")
else:
print("No 6")
lst=list(range(1,6))
t3=tuple(lst)
print(t3)
print(len(t3), type(t3))
print(t3.count(3))
print(t3.index(4)) |
0e6a1bc72bc1206a40348d688669147fe575f691 | michzio/Python---Public-Transport-Shortest-Path-Dijsktra-and-Hamilton-Cycle-Search | /python/simulated_annealing.py | 11,356 | 3.734375 | 4 | #-*-coding:utf-8-*-
import random
import math
from public_transport import Connection
class SimulatedAnnealing:
""" Klasa implementująca algorytm heurystyczny symulowanego wyrzażania."""
INITIAL_TEMPERATURE = 150000
INITIAL_TEMPTERATURE_LENGTH = 100
COOLING_RATIO = 0.99
INFINITY = float("inf")
def __init__(self, graph):
""" Konstruktor obiektu. """
self.graph = graph
# mapowanie indeks -> wierzchołek grafu
# self.index_to_node = self.graph.vertices();
def optimal_hamiltonian_cycle(self):
""" Metoda znajdująca optymalny (minimalny) cykl Hamiltona w grafie. """
best_travel_time, edge_cycle = self.search_min_hamiltionian_cycle()
if best_travel_time is None or best_travel_time < 0:
return (None, None)
printable_cycle = ""
# rekonstrukcja optymalnego cyklu
for edge in edge_cycle:
printable_cycle += str(edge.source())
if type(edge) is Connection:
printable_cycle += "(" + str(edge.line_number()) + ")"
printable_cycle += "->"
# appending connection from last to first node
printable_cycle += str(edge_cycle[-1].target())
if type(edge_cycle[-1]) is Connection:
printable_cycle += "(" + str(edge_cycle[-1].line_number()) + ")"
return (best_travel_time, printable_cycle)
def search_min_hamiltionian_cycle(self):
""" Metoda pomocnicza wykonująca algorytm poszukiwania cyklu.
Implementacja algorytmu symulowanego wyrzażania. """
# 1. PERMUTACJA POCZĄTKOWA
permutation = [node for node in self.graph.vertices()] # wypełniamy wierzchołkami
random.shuffle(permutation) # przetasowanie permutacji wierzchołków
# 2. INICJALIZACJA TEMPERATURY I POCZĄTKOWEGO ROZWIĄZANIA
# parametry sterujące algorytmem
T = self.INITIAL_TEMPERATURE
temperature_length = self.INITIAL_TEMPTERATURE_LENGTH
# bieżące rozwiązanie
curr_solution = permutation
curr_travel_time = self.hamiltonian_cycle_travel_time(curr_solution)
# najlepsze rozwiązanie
best_solution = curr_solution
best_travel_time = curr_travel_time
# 3. PĘTLA OBNIŻANIA TEMPERATURY (SCHŁADZANIA)
while True:
if len(curr_solution) < 4: break
# 4. PĘTLA PRÓB WYGENEROWANIA NOWEGO ROZWIĄZANIA DLA DANEJ TEMPERATURY
for i in range(temperature_length):
# generowanie nowego rozwiązanie
new_solution, vi_idx, vj_idx = self.generate_new_solution(curr_solution)
# obliczenie różnicy czasu pomiędzy starym i nowym rozwiązaniem
time_delta = self.travel_time_change(curr_travel_time, new_solution, vi_idx, vj_idx)
if time_delta <= 0:
# <0 nowe rozwiązanie ma lepszy czas przejazdu
# =0 obydwie permutacje nie są cyklem lub taki sam czas przejazdu
# 5.1 AKCEPTUJĘ NOWĄ PERMUTACJĘ
curr_solution = new_solution
curr_travel_time += time_delta
# bieżąca permutacja jest najlepsza
best_solution = curr_solution
best_travel_time = curr_travel_time
else:
# >0 nowe rozwiązanie ma gorszy czas przejazdu
# lub nie jest cyklem
# 5.2 AKCEPTUJĘ NOWĄ PERMUTACJĘ Z PEWNYM PRAWDOPODOBIEŃSTWEM
# im gorszy czas przejazdu tym mniejsze prawdopodobieństwo
# im wyższa temperatura tym większe prawdopodobieństwo
# losowanie wartości [0,1)
rand_num = random.random()
# sprawdzenie czy wylosowana wartość mniejsza od wyznaczonego
# prawdopodobieństwa akceptacji rozwiązania gorszego
if rand_num < self.probability(time_delta, T):
# AKCEPTUJĘ GORSZE ROZWIĄZANIE
curr_solution = new_solution
curr_travel_time += time_delta
# 6. SCHŁADZANIE - OBNIŻANIE TEMPERATURY
T *= self.COOLING_RATIO
# zwiększenie liczby prób dla niższych temperatur
length_ratio = 5.0 if self.INITIAL_TEMPERATURE/T > 5.0 else self.INITIAL_TEMPERATURE/T
temperature_length = int(self.INITIAL_TEMPTERATURE_LENGTH*length_ratio)
if T <= 1: # warunek końca pętli
break
# 7. KONIEC - najlepsze rozwiązanie to best_travel_time, best_solution
if best_travel_time == self.INFINITY:
return (None, None)
edge_cycle = []
# 8. REKONSTRUKCJA CYKLU HAMILTONA NA PODSTAWIE PERMUTACJI WIERZCHOŁKÓW
for i in range(len(best_solution)):
vi = best_solution[i]
vj = best_solution[(i+1)%len(best_solution)]
best_edge = None
for edge in self.graph.get_edges_from(vi):
if best_edge == None or best_edge.weight() > edge.weight():
best_edge = edge
if not best_edge: # brak połączenia pomiedzy wierzchołkiem vi - vj
return (None, None)
edge_cycle.append(best_edge)
return (best_travel_time, edge_cycle)
def generate_new_solution(self, old_solution):
""" Metoda pomocnicza, które generuje nowe rozwiązanie (permutacje)
na podstawie starego. Algorytm generowania nowej permutacji:
1. Losowe wygenerowanie indeksów vi_idx, vj_idx z przedziału [0, len(permutation))
2. Zamiana par wierzchołków (vi, vi+1) oraz (vj, vj+1) tak by otrzymać
pary (vi, vj) oraz (vi+1, vj+1)
3. Odwrócenie kolejności elementów permutacji (vi+1, ..., vj) -> (vj, ..., vi+1) """
new_solution = old_solution[:] # przekopiowanie permutacji
if len(new_solution) < 4: return new_solution # za mało elementów by wylosować 2 pary
# 1. losowanie indeksów vi_idx < vj_idx
n = len(new_solution)
vi_idx = random.randrange(0, n-1) %n #
while True:
vj_idx = (random.randrange(0, n-(vi_idx+1)) + (vi_idx+2) ) % n
if vi_idx != vj_idx and vi_idx != ((vj_idx+1)%n):
break
print("Wylosowano pary indeksów (vi, vi+1) = (%d, %d) oraz (vj, vj+1) = (%d,%d)" %
(vi_idx, (vi_idx+1)%n, vj_idx, (vj_idx+1)%n))
# 2. zamiana par wierzchołków (vi, vi+1) i (vj, vj+1)
# otrzymując parę (vi, vj) oraz (vi+1, vj+1)
# czyli swap(vi+1, vj)
(new_solution[(vi_idx+1)%n], new_solution[vj_idx]) = (new_solution[vj_idx],new_solution[(vi_idx+1)%n])
# 3. odwróceie kolejności elementów podlisty (vi+1,...vj) -> (vj, ..., vi+1)
new_solution[((vi_idx+1)%n+1):vj_idx] = new_solution[((vi_idx+1)%n+1):vj_idx][::-1]
self.print_permutation(old_solution)
self.print_permutation(new_solution)
return (new_solution, vi_idx, vj_idx)
def travel_time_change(self, old_travel_time, new_solution, vi_idx, vj_idx):
""" Metoda pomocincza, która oblicza zmianę czasu przejazdu pomiędzy starym, a nowym rozwiązaniem.
1. stare rozwiązanie nie było poprawnym cyklem, nowa permutacja może nim być, ale nie musi
(potrzeba na nowo wyznaczyć długość cyklu dla permutacji wierzchołków)
2. stare rozwiązanie było poprawnym cyklem, po zmianie nowa permutacja może być poprawnym
cyklem, ale nie musi."""
time_delta = 0
# 1. stara permutacja nie była cyklem
if old_travel_time == self.INFINITY:
# obliczamy czas przejścia nowej permutacji
new_travel_time = self.hamiltonian_cycle_travel_time(new_solution)
# obliczenie zmiany czasu
# a) INFINITY - INFINITY == 0, obie permutacje nie są cyklem
# b) new_time - INFINITY < 0, nowa permutacja jest cyklem
time_delta = new_travel_time - old_travel_time
else:
# 2. stara permutacja była cyklem
# wyznaczenie różnicy przyrostowo ze wzoru:
# time_delta = time(vi, vi+1) + time(vj,vj+1) - time(vi,vj) - time(vi+1,vj+1)
# jeżeli którakolwiek z nowych krawędzi nie istnieje to time_delta = INFINITY
n = len(new_solution)
time_new_edge_i = self.graph.weight_between(new_solution[vi_idx], new_solution[(vi_idx+1)%n])
time_new_edge_j = self.graph.weight_between(new_solution[vj_idx], new_solution[(vj_idx+1)%n])
if time_new_edge_i == self.INFINITY or time_new_edge_j == self.INFINITY:
time_delta = INFINITY - old_travel_time # należy odjąć czas starego cyklu
else:
# obydwa cykle poprawne - obliczmy różnicę czasów
time_old_edge_i = self.graph.weight_between(new_solution[vi_idx], new_solution[vj_idx])
time_old_edge_j = self.graph.weight_between(new_solution[(vi_idx+1)%n], new_solution[(vj_idx+1)%n])
time_delta = time_new_edge_i + time_new_edge_j - time_old_edge_i - time_old_edge_j
# możliwe wyniki:
# time_delta == 0, obie prmutacje nie są cyklami, lub czas się nie zmienił
# time_delta << 0, nowa permutacja jest cyklem, a stara nie
# time_delta < 0, obie permutacje są cyklami, nowa ma krótszy czas
# time_delta > 0, obie pertmuacje są cyklami, nowa ma dłuższy czas
# time_delta >> 0, nowa permutacja nie jest cyklem, stara była cyklem
return time_delta
def hamiltonian_cycle_travel_time(self, permutation):
""" Metoda pomocnicza zwracająca czas przejazdu dla danego cyklu.
Jeżeli dla przekazanej permutacji wierzchołków cykl nie istnieje
(brak którejś z krawędzi) to metoda zwraca INFINITY."""
travel_time = 0
# pętla po kolejnych parach wierzchołków
for i in range(len(permutation)):
vi = permutation[i]
vj = permutation[(i+1)%len(permutation)]
# zapytanie o czas przejazdu między vi - vj
edge_travel_time = self.graph.weight_between(vi,vj)
# jeżeli INFINITY to brak krawędzi
if edge_travel_time == self.INFINITY:
return self.INFINITY
travel_time += edge_travel_time
return travel_time
def print_permutation(self, permutation):
""" Wypisanie permutacji."""
print("-".join(permutation))
def probability(self, time_delta, T):
""" Prawdopodobieństwo akceptacji nowej permutacji cyklu. Zależy od:
1. różnica czasu przejazdu między nowym i starym cyklem
im większe wydłużenie czasu to mniejsze prawdopodobieństwo
2. temperatura - im wyższa tym większe prawdopodobieństwo
Zwracana wartość jest w przedziale (0,1] bo exp(negative_x). """
if time_delta < 0: return 1
return math.exp(-time_delta/T)
|
64faf6249e898c02a3e128d4203ef6ee6960de48 | gustavomarquezinho/python | /study/w3resource/exercises/python-basic/001 - 030/python-basic - 023.py | 334 | 3.828125 | 4 | # 023 - Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.
def copyString(pString, pTimes):
return (pString[:2 if len(pString) >= 2 else 1] * pTimes)
print(copyString('Copy', 2), copyString('C', 4)) |
06daa0343aab1cb3e7b8fe944b3f201233e97df2 | Exlius/compsci-jmss-2016 | /tests/t1/sum2.py | 508 | 4.09375 | 4 | # copy the code from sum1.py into this file, THEN:
# change your program so it keeps reading numbers until it gets a -1, then prints the sum of all numbers read
# write a program that reads in 10 numbers, then prints the sum of those
total = 0
run = True
while run:
try:
x = int(input("Input a number: "))
if x == -1:
run = False
else:
total = total + x
except ValueError:
print("Please input number in its numerical form")
print(total)
|
dec5ec1137ad0f6ff5d28d7185585ade92408416 | linpan/LPTHW | /ex18.py | 390 | 3.5 | 4 | #! /usr/bin/env python
#coding:utf-8
def print_two(*args):
arg1,arg2 = args
print "arg1: %r,arg2: %r" % (arg1,arg2)
def print_two_again(arg1,arg2):
print "arg1: %r,arg2: %r" % (arg1,arg2)
def print_one(arg1):
print "arg1: %r" % arg1
def print_none():
print "I got nothing."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
|
1ee00e18dcc6e32b7191e16fb8c7a4b2765f67df | kaci65/Nichola_Lacey_Python_By_Example_BOOK | /Maths/multiply.py | 179 | 4.09375 | 4 | #!/usr/bin/python3
"""Ask user input (float). Multiply the float by 2"""
import math
num = float(input("Enter a number with lots of decimal places: "))
mul = num * 2
print(mul)
|
c5d0ef0e631224f8c93f53ee42fca19c57e457a1 | Ved005/project-euler-solutions | /code/gozinta_chains/sol_548.py | 734 | 3.65625 | 4 |
# -*- coding: utf-8 -*-
'''
File name: code\gozinta_chains\sol_548.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #548 :: Gozinta Chains
#
# For more information see:
# https://projecteuler.net/problem=548
# Problem Statement
'''
A gozinta chain for n is a sequence {1,a,b,...,n} where each element properly divides the next.
There are eight gozinta chains for 12:
{1,12} ,{1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}.
Let g(n) be the number of gozinta chains for n, so g(12)=8.
g(48)=48 and g(120)=132.
Find the sum of the numbers n not exceeding 1016 for which g(n)=n.
'''
# Solution
# Solution Approach
'''
'''
|
5efc1815cddf8ffb52f04200529466fc2ec6d4f2 | HugoArts/gunge | /media.py | 5,521 | 3.875 | 4 | #! /usr/bin/env python
"""classes for loading media files
this file contains classes to load and store media files.
The files can be loaded lazily, or at any time you see fit.
"""
import os, pygame
class ResourceLoader(dict):
"""ResourceLoader - base class for loading resources
files are stored in a dictionary with the filename as key. by default, files are
loaded the moment you try to access them, but you can also pre-load files.
since all basic functionality is in ResourceLoader, derived classes only have to implement the load method.
If they want to do some postprocessing on the resources, you can implement a locate method which calls
the base locate method to retrieve the file, and then does the processing.
"""
def __init__(self, paths, set_as_global=True):
"""ResourceLoader(paths) -> ResourceLoader
paths is a tuple of directories to search through
"""
self.paths = list(paths) if isinstance(paths, (list, tuple, set)) else [paths]
def __missing__(self, key):
"""indexing operation -> [resource]
Key is usually the filename of something. What is returned depends on the filetype being loaded
"""
dict.__setitem__(self, key, self.locate(key))
return dict.__getitem__(self, key)
def __setitem__(self, key, value):
"""raise a RuntimeError.
it is not legal to set items in the dictionary to a different value.
It is essentially an immutable dictionary, since its contents depend on outside resources.
"""
raise RuntimeError("The ResourceLoader class does not support assignment")
def locate(self, filename):
"""locate(filename) -> [resource]
locate finds a file, then uses the load function to load it.
It raises a FileError if the file is not found in any path. If you want to do any post-processing
on a loaded resource, override this method in your class, call the base class method, then process away
"""
resource = None
for path in self.paths:
try:
resource = self.load(os.path.join(path, filename))
except IOError, pygame.error:
#error, probably file not found. Try the next path
continue
else:
#no error? then we can quit and return the found resource
break
else:
#This means we didn't break out of the loop, and found nothing but errors
raise IOError("could not open file %s (paths: %s)" % (filename, self.paths))
return resource
def load(self, filename):
"""load(self, filename) -> None
this method is the one to override if you want to derive from this class.
it is used by the base class to load all files.
"""
return open(filename)
def preload(self, *filenames):
"""preload(self, *filenames) -> None
this can be used to preload some files before you actually need them.
This can be usefull to prevent latencies during a game. Since you don't
need the resources just yet, nothing is returned.
"""
for filename in filenames:
dict.__setitem__(self, filename, self.locate(filename))
class ImageLoader(ResourceLoader):
"""ImageLoader - used to load and access images."""
def load(self, filename):
"""load(filename, colorkey=None) -> pygame.Surface
note that colorkey must be either None or an RGB-tuple.
"""
return pygame.image.load(filename)
def locate(self, filename, alpha=False):
"""locate(filename, alpha=False) -> pygame.Surface
uses the base class locate to load the file, then performs a little post-processing.
If you need per-pixel alpha, you can't use indexing notation and you'll have to preload
with that option explicitly
"""
image = ResourceLoader.locate(self, filename)
if alpha:
image.convert_alpha()
else:
image.convert()
return image
def preload(self, *tuples):
"""preload(self, tuples) -> None
preloads a list of files. The arguments are all tuples with the filename
first, and an alpha argument second which specifies wether you want per-pixel alpha.
"""
for args in tuples:
self.resources[filename] = self.locate(*args)
class SoundLoader(ResourceLoader):
"""SoundLoader - used to load, access and play sounds
note that the class is not te be used for music. The pygame.mixer.music
module does a good enough job, and can use streaming (Bonus!!).
"""
def load(self, filename):
"""load(filename) -> pygame.mixer.Sound"""
return pygame.mixer.Sound(filename)
def locate(self, filename):
"""locate(filename) -> pygame.mixer.Sound
if the pygame.mixer module is not loaded, a dummy soundclass is returned
which does nothing.
"""
if not pygame.mixer:
return NoSound()
return ResourceLoader.locate(self, filename)
def play(self, filename, loops=0, maxtime=0):
"""play(self, file) -> pygame.mixer.Channel
plays the file, loading it if needed
"""
return self[filename].play(loops, maxtime)
class NoSound(object):
"""NoSound - used in case there is no sound available, with a dummy play method"""
def play(self):
"""play() -> None"""
pass
|
6b6b22bf5826250b31f10957e2d7b8b5ba33e667 | shannonmlance/leetcode | /club/trianglesAndSquares.py | 597 | 3.5625 | 4 | # Find the first 10 triangle numbers that equal square numbers.
def triangle(n):
s = 0
for i in range(1,n+1):
s += i
return s
def findCommon():
arr = []
si = 2
ti = 2
s = si*si
t = 1 + ti
while len(arr) < 10:
while t != s:
if t < s:
ti += 1
t += ti
if s < t:
si += 1
s = si*si
# arr.append((t,ti,si))
arr.append(t)
ti += 1
si += 1
s = si*si
t += ti
return arr
f = findCommon()
for i in f:
print(i)
|
f391f1c7de5c45405d66c63766132cf6a855eb15 | samantabueno/python | /CursoEmVideo/CursoEmVideo_ex084.py | 1,206 | 3.984375 | 4 | # Exercise to training list function
# Program that you put people and yours weights and them it returns who is lightest and fattest
people = []
crowd = []
lightest = 0
fattest = 0
while True:
people.append(str(input('Type a name: ')))
people.append(float(input('Type a weight: ')))
crowd.append(people[:])
people.clear()
#people.pop() limpa apenas o ultimo
while True:
cont = str(input('Continue:? [Y/N]')).upper()
if cont in 'YN':
break
if cont == 'N':
break
for pos, value in enumerate(crowd):
if pos == 0:
lightest = crowd[pos][1]
fattest = crowd[pos][1]
else:
if crowd[pos][1] < lightest:
lightest = crowd[pos][1]
elif crowd[pos][1] > fattest:
fattest = crowd[pos][1]
print('-='*20)
print(f'It were register {len(crowd)} people.')
print(f'The people lightest weight {lightest} kilos and them names are: ', end='')
for c in crowd:
if c[1] == lightest:
print(c[0], '', end='')
print()
print(f'The people fattest weight {fattest} kilos and them names are: ', end='')
for c in crowd:
if c[1] == fattest:
print(c[0], '', end='')
print()
print(crowd) |
bda2ad16890a1549898f0f67afcec2ec1aaea600 | Sucuri/tls-verify | /tls_verify.py | 3,060 | 3.640625 | 4 | # Test TLS certificate verification in Python 2.x and 3.x
# (c) Sucuri, 2016
from __future__ import print_function
import ssl
# Import from urllib.request (Python 3) or from urllib and urllib2 (Python 2)
try:
from urllib.request import urlopen
from urllib.error import URLError
from http.client import HTTPSConnection
from urllib.parse import urlparse
except ImportError:
from urllib import urlopen
from urllib2 import urlopen as urlopen2, URLError
from httplib import HTTPSConnection
from urlparse import urlparse
# Import the requests library if it's available
try:
import requests
except ImportError:
pass
# Test different methods (urlopen, urlopen2, HTTPSConnection, and Requests library)
def tryurlopen(url):
return urlopen(url).read()
def tryurlopenwithcontext(url):
return urlopen(url, context = ssl.create_default_context()).read()
def tryurlopen2(url):
return urlopen2(url).read()
def tryurlopen2withcontext(url):
return urlopen2(url, context = ssl.create_default_context()).read()
def tryhttpsconnection(url):
conn = HTTPSConnection(urlparse(url).netloc)
conn.request("GET", "/")
return conn.getresponse().read()
def tryhttpsconnectionwithcontext(url):
conn = HTTPSConnection(urlparse(url).netloc, context = ssl.create_default_context())
conn.request("GET", "/")
return conn.getresponse().read()
def tryrequests(url):
r = requests.get(url)
return r.text
# TLS certificate verification must fail for each URL;
# print "INCORRECT" if Python allows an invalid certificate
def printres(func, name, url):
try:
res = func(url)
print('{}: INCORRECT: expected error'.format(name))
except (URLError, ssl.CertificateError, ssl.SSLError, IOError) as e:
print('{}: correct'.format(name))
urls = {
'revoked': 'https://revoked.grc.com/',
'expired': 'https://qvica1g3-e.quovadisglobal.com/',
'expired2': 'https://expired.badssl.com/',
'self-signed': 'https://self-signed.badssl.com/',
'bad domain': 'https://wrong.host.badssl.com/',
'bad domain2': 'https://tv.eurosport.com/',
'rc4': 'https://rc4.badssl.com/',
'dh480': 'https://dh480.badssl.com/',
'superfish': 'https://superfish.badssl.com/',
'edellroot': 'https://edellroot.badssl.com/',
'dsdtestprovider': 'https://dsdtestprovider.badssl.com/'}
# Find available methods
methods = {'urlopen': tryurlopen, 'HTTPSConnection': tryhttpsconnection}
if 'urlopen2' in dir():
methods['urlopen2'] = tryurlopen2
if 'create_default_context' in dir(ssl):
methods['urlopen w/context'] = tryurlopenwithcontext
methods['HTTPSConnection w/context'] = tryhttpsconnectionwithcontext
if 'urlopen2' in dir():
methods['urlopen2 w/context'] = tryurlopen2withcontext
if 'requests' in dir():
methods['requests'] = tryrequests
# Test each URL for each method
for methodsname, method in methods.items():
print('=== ' + methodsname + ' ===')
for name, url in urls.items():
printres(method, name, url)
|
ec41c743e14c8c74f28b7a90d66c7582b51de985 | yanshengjia/algorithm | /leetcode/Bit Manipulation/338. Counting Bits.py | 1,012 | 3.640625 | 4 | """
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Solution:
x &= (x-1) bitwise AND 与,remove the least significant 1 of x
"""
# Time: O(n*sizeof(int))
# Space: O(n)
class Solution:
def countBits(self, num: int) -> List[int]:
res = []
for i in range(num+1):
res.append(self.count_one(i))
return res
def count_one(self, n):
count = 0
while n != 0:
n &= (n-1)
count += 1
return count |
272022b6aae0ea2529e0fdeb8649d98bdde016f1 | liuyan2020520/python_pycharm1 | /面向对象作业.py | 1,317 | 3.65625 | 4 | class Fish:
colour = 'red,yellow,white'
eye = 2
mouth = 1
def eat(self):
print("鱼喜欢吃虾")
def live(self):
print("鱼生活在水里,总是游来游去")
f=Fish()
print(f.eat())
class GreenApples:
colour='green'
def grow(self):
print('绿萝喜欢水,多浇水长得很快')
def root(self):
print('绿萝的气根发达,可以水培种植')
g = GreenApples()
print(g.root())
class CocaCola:
colour = 'brown'
def taste(self):
print('可口可乐甜中带苦的味道,很受人们的喜爱')
class SpongeBobSquarePants:
colour = 'yellow'
eyes = 2
mouth =2
def live(self):
print('海绵宝宝生活在海洋深处')
def frieng(self):
print('海绵宝宝和派大星是好朋友')
def disposition(self):
print('海绵宝宝是一个积极乐观,善良友好,可爱的海绵')
class ZhaoLiYing:
height = 165
constellation = '天秤座'
features = 'beautiful'
def tv_programs(self):
print("赵丽颖饰演了《花千骨》,《知否知否应是绿肥红薯》等优秀的影视作品")
def undergo(self):
print('赵丽颖在农村长大,从跑龙套开始学习表演,经过自己的努力成为了现在当红的影视明星') |
5015846435714e7f605363c6967956949dbbe382 | terki0000/Rock-paper-scissors | /RPS.py | 4,185 | 3.890625 | 4 | import random
moves = ['rock', 'paper', 'scissors']
class Player:
def __init__(self):
self.score = 0
self.mm = Player.move(self)
self.cm = Player.move(self)
def move(self):
return moves[0]
def learn(self, mm, cm):
self.mm = mm
self.cm = cm
class Randomizer(Player):
def move(self):
return random.choice(moves)
class Human(Player):
def move(self):
try:
usermove = input("Please type rock or paper or scissors")
while usermove not in moves:
print("rong, Please try again")
usermove = input("Please type rock or paper or scissors")
except KeyboardInterrupt:
print('Thanks for playing.')
exit()
return usermove
class Reflector(Player):
def move(self):
return self.cm
class Cycler(Player):
def move(self):
if self.mm is moves[0]:
self.mm = moves[1]
elif self.mm is moves[1]:
self.mm = moves[2]
elif self.mm is moves[2]:
self.mm = moves[0]
return self.mm
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Repeater(Player):
def move(self):
return moves[0]
class Game:
def __init__(self, p1, p2):
self.score = 0
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print (f"Player 1: {move1} Player 2: {move2}")
if beats(move1, move2):
self.p1.score += 1
print('Player 1 win!')
elif beats(move2, move1):
self.p2.score += 1
print('Player 2 win!')
else:
print("tie, tie, tie.")
print(f"""Score:
Player 1 | Player 2
{self.p1.score} {self.p2.score}""")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def play_game(self):
print("match start!")
for round in range(1, 6):
print(f"Round {round}:")
self.play_round()
if self.p1.score > self.p2.score:
print(f"""Player 1 (human Won!)
Final score:Player 1: {self.p1.score} | Player 2 {self.p2.score}
Game Over.""")
elif self.p2.score > self.p1.score:
print(f"""Player 2 (computer won!)
Final Score: Player 1: {self.p1.score} | Player 2 {self.p2.score}
Game Over.""")
else:
print(f"""tie, tie, tie.
Final Score: Player1 = {self.p1.score} | Player2= {self.p2.score}
Game Over""")
def start_game():
if __name__ == '__main__':
print('Welcome to RPS.')
while True:
try:
playerlist = int(input("enter random(1),cycler(2)\
repeater(3),reflector(4),(0) to quit"))
if playerlist == 4:
game = Game(Human(), Reflector())
game.play_game()
break
if playerlist == 1:
game = Game(Human(), Randomizer())
game.play_game()
break
if playerlist == 2:
game = Game(Human(), Cycler())
game.play_game()
break
if playerlist == 3:
game = Game(Human(), Repeater())
game.play_game()
break
if playerlist == 0:
print('Goodbye.')
exit()
game.play_game()
break
except ValueError:
print('Envalid number. Please try again.')
continue
except KeyboardInterrupt:
print('Thanks for playing.')
exit()
start_game()
|
836c44e235b3ff761d3d9f1dbeffabd026f39ec8 | Irek-coder/Text-adventure | /character.py | 1,801 | 3.6875 | 4 | class Character():
def __init__(self,char_name,char_description):
self.name=char_name
self.description = char_description
self.conversation=None
def describe(self):
print(self.name+" is here!")
print(self.description)
def set_conversation(self,conversation):
self.conversation=conversation
def talk(self):
if self.conversation is not None:
print("["+self.name+" says]: "+self.conversation)
else:
print(self.name+" doesn't want to talk to you.")
def fight(self, combat_item):
print(self.name+" doesn't want to fight with you")
return True
class Enemy(Character):
def __init__(self, char_name, char_description):
super().__init__(char_name,char_description)
self.weakness=None
self.worth=None
def fight(self, combat_item):
if combat_item==self.weakness:
print("You fend "+self.name+" off with the "+combat_item)
return True
else:
print(self.name+" crushes you, puny adventurer")
return False
def set_weakness(self,weakness):
self.weakness=weakness
def get_weakness(self):
return self.weakness
def set_worth(self,worth):
self.worth=worth
def bribe(self,amount):
if amount>=self.worth:
print("Successful bribe")
return True
else:
print("Unsuccesful bribe! "+self.name+" is offended and wants to fight! ")
return False
class Friend(Character):
def __init__(self,char_name,char_description):
super().__init__(char_name,char_description)
def hug(self):
print(self.name+" hugs you! ")
|
3a0b56b7a03b1408741509b5f90039b70c6f1e60 | maddiecousens/Coding-Challenge-Practice | /Linked Lists/MC_AddToEnd.py | 577 | 3.890625 | 4 | class Node(object):
def __init__(self,data):
self.data = data
self.next = None
class Solution(object):
def display(self,head):
current = head
while current:
print current.data,
current = current.next
def addToEnd(self,head,data):
#Complete this method
new_node = Node(data)
if head:
curr = head
while curr.next:
curr = curr.next
curr.next = new_node
else:
head = new_node
return head |
67e017a9f2001de74f7db1bee49f6d7f87393dcf | lil-lab/cerealbar | /agent/environment/environment_objects.py | 3,137 | 4.46875 | 4 | """ Contains definitions for objects in the environment.
Classes:
ObjectType (Enum): Different types that objects can have.
EnvironmentObject (ABC): Abstract class for a generic object environment.
RotatableObject (EnvironmentObject): Abstract class for an object that has a rotation property.
"""
from abc import ABC
from enum import Enum
from typing import Optional
from agent.environment import position
from agent.environment import rotation
class ObjectType(Enum):
""" Various types of objects in the environments. """
CARD: str = 'CARD'
TREE: str = 'TREE'
HUT: str = 'HUT'
LEADER: str = 'LEADER'
FOLLOWER: str = 'FOLLOWER'
WINDMILL: str = 'WINDMILL'
TOWER: str = 'TOWER'
PLANT: str = 'PLANT'
LAMPPOST: str = 'STREET_LAMP'
TENT: str = 'HOUSE_LVL1'
def __str__(self) -> str:
return self.value
class EnvironmentObject(ABC):
""" A generic environment object type.
Members:
_position (Position): The position of the object.
_type (ObjectType): The type of object.
"""
def __init__(self, object_position: Optional[position.Position], object_type: ObjectType):
self._position: Optional[position.Position] = object_position
self._type: ObjectType = object_type
def get_type(self) -> ObjectType:
""" Returns the type of the object. """
return self._type
def get_position(self) -> position.Position:
""" Returns the position of the object. """
return self._position
def __eq__(self, other) -> bool:
""" Compares two objects in the environment by checking the classes, types, and positions. """
if isinstance(other, self.__class__):
return self._type == other.get_type() and self._position == other.get_position()
else:
return False
def __ne__(self, other) -> bool:
return not self.__eq__(other)
def __str__(self):
return str(self._type) + '\t' + str(self._position)
class RotatableObject(EnvironmentObject, ABC):
""" An environment object that has a rotation property. Inherits from EnvironmentObject/
Members:
_rotation (Rotation): The rotation of the object.
"""
def __init__(self, object_position: Optional[position.Position], object_rotation: Optional[rotation.Rotation],
object_type: ObjectType):
super(RotatableObject, self).__init__(object_position, object_type)
self._rotation: Optional[rotation.Rotation] = object_rotation
def get_rotation(self) -> rotation.Rotation:
""" Returns the rotation of the object. """
return self._rotation
def __eq__(self, other) -> bool:
""" Equality operator also checks the rotation for the other object. """
if isinstance(other, self.__class__):
return self._position == other.get_position() and self._rotation == other.get_rotation()
return False
def __ne__(self, other) -> bool:
return not self.__eq__(other)
def __str__(self):
return super(RotatableObject, self).__str__() + '\t' + str(self._rotation)
|
bf86f28414b0d5f3f4762c5aeba6388dce43abbc | sairin1202/Leetcode | /2.py | 1,221 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoCells(self, l1, l2, c):
if l1 == None and l2 == None:
if c == 0:
return None
else:
new_node = ListNode(1)
return new_node
elif l1 == None:
val = (l2.val + c) % 10
c = (l2.val + c) // 10
new_node = ListNode(val)
new_node.next = self.addTwoCells(l1, l2.next, c)
elif l2 == None:
val = (l1.val + c) % 10
c = (l1.val + c) // 10
new_node = ListNode(val)
new_node.next = self.addTwoCells(l1.next, l2, c)
else:
val = (l1.val + l2.val + c) % 10
c = (l1.val + l2.val + c) // 10
new_node = ListNode(val)
new_node.next = self.addTwoCells(l1.next, l2.next, c)
return new_node
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
c = 0
res = self.addTwoCells(l1, l2, c)
return res |
e5638742780f1280a493a80b2c04e3d2052af0ee | thanhlong98kun/TTCS_TUAN2 | /Bai_5/main.py | 3,112 | 3.671875 | 4 | import curses
from curses import KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT
import time
import random
def game():
win = curses.initscr()
win.keypad(1) # Cho phep su dung cac phim dat biet nhu: up down left right
curses.curs_set(0) # Tat con tro nhap nhay
win.nodelay(1) # Vong lap van chay khi gap ham nhap 1 ki tu nhu win.getch()
max_y, max_x = win.getmaxyx()
head = [1, 1]
body = [head[:]] * 5
deadcell = body[-1][:]
direction = 0 # 0: right, 1: up, 2: down, 3: left
foodmade = False
running = True
while running:
win.border()
while not foodmade:
x, y = random.randrange(1, max_x - 1), random.randrange(1, max_y - 1)
if win.inch(y, x) == ord(' '):
foodmade = True
win.addch(y, x, ord('@'))
if deadcell not in body:
win.addch(deadcell[0], deadcell[1], ' ')
win.addch(head[0], head[1], 'X')
# Bat phim nhap vao va ghi vao key
key = win.getch()
# Neu nhan q thi se thoat khoi vong lap
if key == ord('q'):
running == False
# Bat su kien nhan phim di chuyen
if key == curses.KEY_RIGHT and direction != 3:
direction = 0
elif key == curses.KEY_UP and direction != 2:
direction = 1
elif key == curses.KEY_DOWN and direction != 1:
direction = 2
elif key == curses.KEY_LEFT and direction != 0:
direction = 3
# Tang vi tri dau con ran len phia truoc
if direction == 0:
head[1] += 1
elif direction == 1:
head[0] -= 1
elif direction == 2:
head[0] += 1
elif direction == 3:
head[1] -= 1
# Luc nay dau con ran van chua len toi truoc
# Kiem tra xem phia truoc co ky tu gi hay k
# Nếu có thì con rắn đã chạm biên or vào thân or thức ăn
if win.inch(head[0], head[1]) != ord(' '):
if win.inch(head[0], head[1]) == ord('@'):
foodmade = False
body.append(body[-1])
else:
running = False
deadcell = body[-1][:]
for i in range(len(body) - 1, 0, -1):
body[i] = body[i - 1][:]
body[0] = head[:]
win.refresh()
time.sleep(0.1)
win.clear()
win.nodelay(0)
message1 = 'Game Over'
message2 = 'You got ' + str(len(body) - 5) + ' points'
message3 = 'Press Space to play again'
message4 = 'Press Enter to quit'
win.addstr(int(max_y/2) - 1, int((max_x - len(message1))/2), message1)
win.addstr(int(max_y/2), int((max_x - len(message2))/2), message2)
win.addstr(int(max_y/2) + 1, int((max_x - len(message3))/2), message3)
win.addstr(int(max_y/2) + 2, int((max_x - len(message4))/2), message4)
win.refresh()
q = 0
while q not in [32, 10]:
q = win.getch()
if q == 32:
win.clear()
game()
elif q == 10:
curses.endwin()
if __name__ == '__main__':
game() |
aeb8cc5bfbe2d5ce4c5df3bee3deab3313ecf8e8 | M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes | /famous_quote.py | 980 | 4.09375 | 4 | # Printing a quote using \n and \t as well as quotation marks in printed text
print ('Winston Churchill once said, \n\t"What is the purpose of living \n\tif it be not to strive for noble causes \n\tand to make this muddled world a better place \n\tfor those who live in it after we are gone."')
famous_person = "Winston Churchill"
message = ( ' once said, \n\t"What is the purpose of living \n\tif it be not to strive for noble causes \n\tand to make this muddled world a better place \n\tfor those who live in it after we are gone."')
print (famous_person + message)
# Using a different name in the same message
famous_person_2 = "\nJustin Bieber has NOT"
print (famous_person_2 + message)
# Practicing the stripping functions
article = "\nHe, "
famous_person_2 = " Justin Bieber has NOT "
print (article + famous_person_2 + message)
print (article + famous_person_2.strip().title() + message)
print (article + famous_person_2.lstrip().upper() + message)
print (article + famous_person_2.rstrip().lower() + message) |
385b9c5a762173df74fe4c5a143c129a95aca908 | yunusemremeleks/mucitpark | /h3e4.py | 220 | 4.03125 | 4 | #Kullanıcın girdiği sayının faktöriyelini hesaplayan ve bunu ekranda gösteren program
x=int(input('bir sayı giriniz'))
carp=1
for oku in range(x):
carp=carp*(oku+1)
print(oku+1,'faktöriyel:',carp) |
e1f3ee0bfe205f7a6b35ad40aa5abf847e3d37a0 | MikeOcc/MyProjectEulerFiles | /Euler_8_357a.py | 621 | 3.546875 | 4 | #
#
# Euler Problem 357
#
#[]
from Functions import divisors,IsPrime,RofPrimes,RetFact
from time import time
def f(n):
if not IsPrime(1 + n):return False
if not IsPrime(2 + n/2):return False
D = divisors(n)
D = D[:len(D)/2]
#l = len(D)
for d in D:
if not IsPrime(d + n/d):return False
return True
st = time()
summ = 6
for i in xrange(45000001,50000001,2): #100000001):
if i%10 in [1,5,9]:
if f(2*i):
summ +=2*i
print i,2*i #, RetFact(i)
print "Sum of integers <=100,000,000 such that for every divisor d of n, d+n/d is prime is",summ
print "process time is",time()-st
|
a339d3140eaa5abd36ab01bcd80823ecc656f181 | q798010412/untitled2 | /6.23/双指针.py | 694 | 3.796875 | 4 | # 删除重复值
def delete(nums):
slow = 0
fast = 1
while fast < len(nums):
if nums[fast] == nums[slow]:
fast += 1
else:
slow += 1
nums[slow] = nums[fast]
fast += 1
return slow + 1, nums
# if __name__ == '__main__':
# n = delete([1, 1, 2, 2, 3, 3, 5, 5, 6, 6, 7, 7])
# print(n)
# 删除指定值
def delete_1(nums,data):
slow=0
fast=0
while fast < len(nums):
if nums[fast]==data:
fast+=1
else:
nums[slow]=nums[fast]
slow+=1
fast+=1
return slow,nums
if __name__ == '__main__':
n=delete_1([1,2,3,4,4,2],2)
print(n) |
23de34e9328b7f1d8b785551fea1ae749485d38d | chinnuz99/luminarpython | /data collections/students pssed.py | 290 | 3.875 | 4 | total_students=("anu","jiya","amal","adhul","nandu","aiswarya")
print("total students", total_students)
failed={"jiya","amal","nandu"}
print("failed students set",failed)
passed=set()
for i in total_students:
if i not in failed:
passed.add(i)
print("passed students are",passed) |
faa4c14b4911bff28b21c302ad153f56678310f7 | jboo1212/Algorithms-and-Classes | /Algorithms.py | 327 | 3.828125 | 4 | __author__ = 'Sorostitude'
# Takes a list and sorts it in O(log(n)) time.
def linear_sort(some_list):
for n in range(len(some_list)/2):
temp_var = some_list[n]
some_list[n] = some_list[-1 - n]
some_list[-1 - n] = temp_var
return some_list
x = [3, 4, 5, 6, 7, 8]
linear_sort(x)
print x
|
360354aecccfe4eb58428bf4a111ff0b5fe4f5e0 | pengjinfu/Python3 | /100 Question/3 question.py | 722 | 4.15625 | 4 | # usr/bin/python3
# -*- coding:utf-8 -*-
# Authour:Dreamer
# Tmie:2018.6.1
"""
题目3:一个整数,它加上100后是一个完全平方数,再加上268又是一个完全平方数,请问该数是多少?
程序分析:
1.先给定这个数的范围:10万以内
2.sqrt(i+100)= x --->x*x = (i+100)
3.sqrt(i+268)= y --->x*x = (i+268)
4.判断:x*x = (i+100)and x*x = (i+268)是否同时满足
5.打印输出:print(i)
"""
# 导入math包
import math
for i in range(10000):
# 要转换成整形
x = int (math.sqrt(i + 100)) # 利用数学平方函数
y = int (math.sqrt(i + 268))
if(x * x == i + 100) and (y * y == i + 268):
print("这个数就是:%d"%i)
|
cdfbccac264279d80224dbf5e8ebd7800862e55e | lanqing1/UC-Davis | /CSC110-python/Add two number in graph(dis).py | 2,307 | 3.953125 | 4 | from graphics import*
def main():
# Create a window
win = GraphWin("Shapes",400,150)
win.setBackground("lavender")
# Creat a rectangle
AddRect = Rectangle(Point(25,15),Point(80,40))
# Draw the rectangle "ADD"
AddRect.draw(win)
# Fill the rectangle with white
AddRect.setFill("white")
AddRect.setOutline("White")
# Add text"Add" inside the rectangle
Text(Point(51,28),"Add").draw(win)
# Draw symbol"+" and "="
SymbolRect1 = Rectangle(Point(100,60),Point(120,63))
SymbolRect1.setFill("black")
SymbolRect1.draw(win)
SymbolRect2 = Rectangle(Point(109,53),Point(112,70))
SymbolRect2.setFill("black")
SymbolRect2.draw(win)
SymbolRect3 = Rectangle(Point(220,55),Point(240,58))
SymbolRect3.setFill("black")
SymbolRect3.draw(win)
SymbolRect4 = Rectangle(Point(220,61),Point(240,64))
SymbolRect4.setFill("black")
SymbolRect4.draw(win)
# Create two rectangle
Rect1= Rectangle(Point(25,50),Point(80,75))
Rect1.setFill("white")
Rect1.setOutline("grey")
Rect1.setWidth(4)
Rect1.draw(win)
Rect2= Rectangle(Point(145,50),Point(200,75))
Rect2.setFill("white")
Rect2.setOutline("grey")
Rect2.setWidth(4)
Rect2.draw(win)
# Let the user input 2 number
entInput1 = Entry(Point(52,63),5)
entInput1.setFill("White")
entInput1.draw(win)
entInput2 = Entry(Point(172,63),5)
entInput2.setFill("White")
entInput2.draw(win)
blnRun = True
while blnRun == True:
# Gets X and Y coords.
ClickXY = win.getMouse()
ClickX = ClickXY.getX()
ClickY = ClickXY.getY()
if ClickX<80 and ClickX> 25 and ClickY<40 and ClickY>15:
fltInput1 = float(entInput1.getText())
fltInput2 = float(entInput2.getText())
fltAnswer = fltInput1 + fltInput2
strAnswer = str(fltAnswer)
ansText = Text(Point(280,60),strAnswer)
ansText.setSize(20)
ansText.setTextColor("salmon")
ansText.draw(win)
blnRun = False
win.getMouse()
win.close()
main()
|
00135e966cbadf8762efd9d6487a19ac57856766 | PSgale/AdventOfCode | /2019/06/number_of_orbits.py | 2,755 | 3.5625 | 4 | # Function to read the map
def load_map(file):
f = open("../data/" + file, "r")
# load galaxy to dictionary
map_ = {}
for x in f:
key, value = x.strip().split(")")
values = map_.get(key)
if values:
values.append(value)
map_.update({key: values})
else:
map_.update({key: [value]})
# Check planet not in orbit
map_copy = map_.copy()
for values in map_.values():
for el in values:
if map_copy.get(el):
map_copy.pop(el)
return map_, [*map_copy]
# calculate orbits in galaxy
def calculate_orbits_check_sum(map_, planet, orbits):
if map_.get(planet):
return orbits + sum(calculate_orbits_check_sum(map_, planet_on_orbit, orbits + 1) for planet_on_orbit in map_.get(planet))
else:
return orbits
def get_dist_to_santa(map_):
map_rev = {}
for planet in map_:
for orbit in map_.get(planet):
map_rev.update({orbit: planet})
# SAN path to COM
dict_san = {}
planet_now = 'SAN'
dist = 1
while planet_now:
planet_now = map_rev.get(planet_now)
if planet_now:
dict_san.update({planet_now: dist})
dist += 1
# YOU path to COM
dict_you = {}
planet_now = 'YOU'
dist = 1
while planet_now:
planet_now = map_rev.get(planet_now)
if planet_now:
dict_you.update({planet_now: dist})
dist += 1
# Find common path and distance between
dict_common = dict_san.keys() & dict_you.keys()
min_path = 99999
for planet in dict_common:
path_ = dict_san.get(planet) + dict_you.get(planet)
min_path = path_ if path_ < min_path else min_path
return min_path - 2
print("%%% Test 1 %%%")
map_, no_orbit = load_map("number_of_orbits_t1.txt")
orbits_check_sum = calculate_orbits_check_sum(map_, no_orbit[0], 0)
expected = 42
assert orbits_check_sum == expected, "Not expected result."
print("%%% Test 2 %%%")
map_, no_orbit = load_map("number_of_orbits_t2.txt")
orbits_check_sum = calculate_orbits_check_sum(map_, no_orbit[0], 0)
expected = 54
assert orbits_check_sum == expected, "Not expected result."
dist_to_santa = get_dist_to_santa(map_)
expected = 4
assert dist_to_santa == expected, "Not expected result."
print("%%% RUN %%%")
map_, no_orbit = load_map("number_of_orbits.txt")
orbits_check_sum = calculate_orbits_check_sum(map_, no_orbit[0], 0)
print('No orbit' + str(no_orbit))
expected = 106065
assert orbits_check_sum == expected, "Not expected result."
dist_to_santa = get_dist_to_santa(map_)
print(dist_to_santa)
|
fb0ae1c515c30a9e604de9b9f0460999d75df12b | voidrank/pythonLearning | /src/t51.py | 321 | 3.703125 | 4 | class Bird:
def __init__(self):
self.hungry = 1
def eat(self):
if self.hungry:
print 'Aaaaa'
self.hungry = 0
else:
'thank you'
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'squawk!'
def sing(self):
print self.sound
a = Bird()
a.eat()
a.eat()
b = SongBird()
b.eat() |
544605d8011a2b81ef7dbf1cb423dc7959f4494d | samieeme/TFSGS | /Platform_2/LES_III_newtwo-point/ensemble_velocity_2.py | 433 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 16:25:42 2020
@author: zayern
"""
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
# These are in unitless percentages of the figure size. (0,0 is bottom left)
left, bottom, width, height = [0.3, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
ax1.plot(range(10), color='red')
ax2.plot(range(6)[::-1], color='green')
plt.show() |
d3e169dc7d4792f426ac56c5751b3bd14e9576a3 | TheDecipherer/python_basics | /main.py | 2,664 | 4.0625 | 4 | # F to C converter
factor = 9 / 5
celsius = float(input('Enter the temperature in Celsius '))
fahrenheit = float((celsius * factor) + 32)
print('The temperature in Fahrenheit is {}'.format(str(fahrenheit)))
# Swap numbers
a = int(input('Enter number a: '))
b = int(input('Enter number b: '))
temp = a
a = b
b = temp
print('a and b are {}, {}'.format(str(a), str(b)))
# Name length problem
name = input('Enter your name: ')
length = len(name)
if length > 7:
print(name)
elif length > 4 & length < 6:
age = int(input('Enter your age: '))
print(str(age))
# Calculator
a = int(input('Enter number a: '))
b = int(input('Enter number b: '))
operator = input('Enter the operation: ')
if operator == '+':
print(str(a + b))
elif operator == '-':
print(str(a - b))
elif operator == '*':
print(str(a * b))
elif operator == '/':
print(str(a / b))
else:
print(str(a % b))
# Interest calculator
def calculator(input_pay):
built_in_interest = 0
if 20000 < input_pay < 50000:
built_in_interest = 10
elif 50000 < input_pay < 100000:
built_in_interest = 20
elif input_pay > 100000:
built_in_interest = 30
return built_in_interest
salary = int(input('Enter your salary: '))
if salary < 0:
salary = int(input('Please enter a positive number: '))
interest = float(calculator(salary))
print('Your income tax is {}'.format(str(interest * salary / 100)))
# Factorial
number = int(input('Enter the number: '))
factorial = 1
for i in range(1, number + 1):
factorial *= i
print('The factorial is {}'.format(str(factorial)))
# Password problem
def password_checker(input_password):
input_length = len(input_password)
if input_length > 6 and type(int(input_password[input_length - 1])):
print('Access Granted')
else:
input_password = input('Enter a valid password')
password_checker(input_password)
password = input('Please enter a password: ')
password_checker(password)
# FizzBuzz
user_input = input('Enter the numbers: ')
number_list = user_input.split(', ')
for i in range(0, len(number_list)):
if int(number_list[i]) % 3 == 0 and int(number_list[i]) % 5 == 0:
print('FizzBuzz')
elif int(number_list[i]) % 3 != 0 and int(number_list[i]) % 5 != 0:
print(str(int(number_list[i])))
else:
if int(number_list[i]) % 3 == 0:
print('Fizz')
else:
print('Buzz')
# Address book
names = input('Enter the names: ').split(', ')
numbers = input('Enter the phone numbers: ').split(', ')
address_book = dict(zip(names, numbers))
user = input('Enter the user name: ')
print(address_book[user])
|
d922804f95fd4263254f6b34c163ce5000e6b7a0 | matthew-erdman/week11 | /lab11/cleanstring.py | 1,525 | 4.0625 | 4 | """
Description: This program removes instances of a charcter from a string. A user
provides a string and a charcter, and the program recursively removes all occurrences
of the character from the string.
Author: Matthew Erdman
Date: 9/20/21
"""
def getChar():
"""
Purpose: Gets input from the user and validates that it is a single character.
Parameters: None.
Return Value: The user's chosen character.
"""
userChar = input("Char: ")
while True:
if len(userChar) == 1:
return userChar
print("Please enter a single character.")
userChar = input("Char: ")
def cleanString(rawStr, cleanChar):
"""
Purpose: Recursively removes all instances of a character from a string.
Parameters: The string which will have its characters searched/removed and
the charcter which will be removed from the string.
Return Value: The final string with selected characters removed.
"""
# reached first (final) charcter, return back up
if len(rawStr) == 1:
return rawStr[-1] if rawStr[-1] != cleanChar else ""
else:
cleanedString = cleanString(rawStr[:-1], cleanChar)
# build up string as each recursive call returns
if rawStr[-1] != cleanChar: # remove instances of character
cleanedString += rawStr[-1]
return cleanedString
def main():
rawStr = input("String: ")
cleanChar = getChar()
cleanedString = cleanString(rawStr, cleanChar)
print(cleanedString)
main()
|
29772d3022c0b9dc7d918d52123bda2175f34c19 | Noteee/fbrd | /game_inv.py | 3,055 | 3.953125 | 4 | # starting inventory
inv = {"rope": 1, "torch": 6, "gold_coin": 42, "dagger": 1, "arrow": 12}
# additional loot
dragon_loot = ["gold_coin", "dagger", "gold_coin", "gold_coin", "ruby"]
# raw inv display
def display_inventory(inv):
total = 0
for k, v in inv.items():
print("%d %s" % (v, k))
total += v
print("%s %d" % ("Total number of items: ", total))
# adding lists of items to inventory
def add_to_inventory(inv, added_items):
for i in added_items:
if i in inv:
inv[i] += 1
else:
inv.update({i: inv.get(i, 0) + 1})
# same as display but sorted and organised into a table, takes an argument of these two: count.asc or count.desc
# without argument its not sorting only organising into table
def print_table(*order):
total = 0
mlenght = len(max(inv, key=len))
separation = mlenght * 2 + 4
ascinv = sorted(inv.items(), key=lambda inv : inv[1], )
descinv = sorted(inv.items(),key=lambda inv : inv[1], reverse = True)
print("Inventory:")
print("{0:>{width}s} {1:>{width}s}".format("count", "item name", width = mlenght))
print("-" * separation)
if len(order) == 0:
for k, v in inv.items():
print("{0:>{width}d} {1:>{width}s}".format(v, k, width = mlenght))
total += v
print("-"*separation)
print("%s %d" % ("Total number of items: ", total))
elif len(order) == 1 and order[0] == "count.desc":
for k, v in descinv:
print("{0:>{width}d} {1:>{width}s}".format(v, k, width = mlenght))
total += v
print("-"*separation)
print("%s %d" % ("Total number of items: ", total))
elif len(order) == 1 and order[0] == "count.asc":
for k, v in ascinv:
print("{0:>{width}d} {1:>{width}s}".format(v, k, width = mlenght))
total += v
print("-"*separation)
print("%s %d" % ("Total number of items: ", total))
# exports the inventoy into a file takes the wished filename as an argument (without file-extension)
def export_inventory(filename='export_inventory'):
fw = open(filename+".csv", "w")
fw.write("item name,count\n")
for key, value in inv.items():
fw.write("%s,%d\n" % (key, value))
fw.close()
# reads a file and imports the data from it (takes filename as argument with file extension)
def import_inventory(filename):
fr = open(filename, "r")
importedlist = []
for i in fr:
importedlist.append(i.strip().split(","))
del importedlist[0]
for i in range (len(importedlist)):
if importedlist[i][0] in inv:
inv[importedlist[i][0]] += int(importedlist[i][1])
else:
inv.update({importedlist[i][0]: int(importedlist[i][1])})
fr.close()
# tests
display_inventory(inv)
add_to_inventory(inv, dragon_loot)
print_table("count.desc")
export_inventory()
import_inventory("export_inventory.csv")
print_table("count.desc")
# tests
|
0d622683b0bef3301468bb65b953cde44ab0c753 | pdelfino/crypto | /A1-livro/cap-4/q-3.py | 523 | 3.546875 | 4 | # recebe a,k e n -> fazendo a^k (mod n)
def potencia(base,expoente,mod):
if mod==1:
return 0
result = 1
for i in range(0,expoente):
result = (result*base)%mod
return (str(base)+"^"+str(expoente)+" (mod "+str(mod)+") equivale a: "+str(result))
#teste -> passo
# questões do livro resolvidas com o algoritmo da questão 11 - grupo controle: https://planetcalc.com/8326/
print (potencia(5,20,7))
print (potencia(7,1001,11))
print (potencia(2,130,263))
print (potencia(13,221,19))
|
eff87eb96344d2af9508183934d05cf066b84371 | franktank/py-practice | /fb/medium/78-subsets.py | 845 | 3.9375 | 4 | """
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
"""
"""
1 2 3 4
234 3 4
34 4
4
"""
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
res.append([])
for i in range(len(nums)):
for j in range(len(res)):
res.append(res[j] + [nums[i]])
return res
# Generate all cominbations of sets -> subsets!!
"""
First append an empty list to your results list
Iterate through nums:
Iterate through res each time:
Append a concatenation of res[j] + nums[i]
Return results
"""
|
4eeec70d9ee224ddd273e0a0f0f0ef5c4863985e | carolinemascarin/Code_First_Girls | /Class2/my_name.py | 346 | 3.859375 | 4 | def welcome():
print "What's your name?"
name = raw_input()
print "Hello {}!".format(name)
welcome()
print "Enter your first number:"
x = raw_input()
print "Enter your second number:"
y = raw_input()
#converting strings to int
x = int(x)
y = int(y)
def add(x,y):
print ("print the total: {0}".format(x + y))
add(x, y)
|
7ff6b5bf53e24467d2252f7f44dec5c960d39d40 | Rxdxxn/Instructiunea-FOR | /for6.py | 643 | 3.703125 | 4 | n=eval(input("introduceti un numar:"))
s1=0
for i in range(1,n+1):
s1+=i
print("s1=",s1)
n=eval(input("introduceti un numar:"))
s2=0
for i in range(1,n+1):
s2+=(i-1)*i
print("s2=",s2)
n=eval(input("introduceti un numar:"))
s3=1
pr=1
for i in range(2,n+1):
pr*=i
s3+=pr
print("s3=",s3)
n=eval(input("introduceti un numar:"))
s4=0
for i in range(1,n+1):
s4+=(10*i+2)
print("s4=",s4)
n=eval(input("introduceti un numar:"))
s5=0
for i in range(1,n+1):
s5+=n/(n+1)
print("s5=",s5)
n=eval(input("introduceti un numar:"))
s6=3
for i in range(2,n+1):
m=str(i)
s6+=int(str('2'+m))
print("s6=",s6) |
2a141ed0604d36f6d782236ebb0a931dc8e1cf14 | wt5ljon/py-toons | /toons.py | 6,219 | 3.515625 | 4 | #!/usr/bin/python
""" sqlite python read and write data from WB table in toons database """
# Import the required Python module
import sqlite3
# CONSTANTS
FIRST_YEAR = 1930
LAST_YEAR = 1988
SQL_BASE = 'SELECT * FROM WB '
MAX_TITLE_LENGTH = 28
def showMenu():
show = True
sql = ''
while show:
print "\n Options Menu"
print "---------------------"
print " A. Show All Records"
print " B. Show Last 10 Records"
print " C. Search By Title"
print " D. Search By Director"
print " E. Search By Character"
print " F. Search By Year of Release"
print " G. Search By Rating"
print " H. Sort By Release Date"
print " I. Sort By Viewing Date"
print " J. Custom SQL Statement"
print " K. Show Table Fields"
print " L. Add Table Entry"
print " Q. Quit"
option = raw_input("\n Choose an option: ")
if option == 'Q' or option == 'q':
show = False
elif option == 'A' or option == 'a':
sql = SQL_BASE
print "\n " + sql
exeSQL(sql)
elif option == 'B' or option == 'b':
sql = SQL_BASE
sql += "ORDER BY CDID DESC LIMIT 10"
print "\n " + sql
exeSQL(sql)
elif option == 'c' or option == 'C':
title = raw_input(" ENTER Title: ")
sql = SQL_BASE + 'WHERE Title LIKE "%' + title + '%"'
print "\n " + sql
exeSQL(sql)
elif option == 'D' or option == 'd':
director = raw_input(" ENTER Director: ")
sql = SQL_BASE + 'WHERE Director LIKE "%' + director + '%"'
sql += " ORDER BY RelDateTxt"
print "\n " + sql
exeSQL(sql)
elif option == 'E' or option == 'e':
char = raw_input(" ENTER Character: ")
sql = SQL_BASE + "WHERE Char1 LIKE '%" + char + "%'"
sql += " OR Char2 LIKE '%" + char + "%'"
sql += " OR Char3 LIKE '%" + char + "%'"
sql += " OR Char4 LIKE '%" + char + "%'"
sql += " ORDER BY RelDateTxt"
print "\n " + sql
exeSQL(sql)
elif option == 'F' or option == 'f':
year = raw_input(" ENTER Year: ")
sql = SQL_BASE + "WHERE RelDateTxt LIKE '%" + year + "%' ORDER BY RelDateTxt"
print "\n " + sql
exeSQL(sql)
elif option == 'G' or option == 'g':
while True:
rate = raw_input(" ENTER Rating (1, 2, 3): ")
if rate not in ['1', '2', '3']:
print " Invalid rating entered...try again"
else:
break
sql = SQL_BASE + "WHERE Rating=" + str(rate) + " ORDER BY RelDateTxt"
print "\n " + sql
exeSQL(sql)
elif option == 'H' or option == 'h':
sql = SQL_BASE + "ORDER BY RelDateTxt"
print "\n " + sql
exeSQL(sql)
elif option == 'I' or option == 'i':
sql = SQL_BASE + "ORDER BY ViewDateJul DESC"
print "\n " + sql
exeSQL(sql)
elif option == 'J' or option == 'j':
sql = raw_input(" ENTER SQL Statement: " + SQL_BASE)
print "\n " + SQL_BASE + sql
exeSQL(SQL_BASE + sql)
elif option == 'K' or option == 'k':
showTableFields()
elif option == 'L' or option == 'l':
showTableFields()
else:
print "Invalid option entered..."
def showTableFields():
print '\n WB Table Fields'
print '-'*22
lineText = " CDID: Integer\n"
lineText += " Title: Text\n"
lineText += " Char1: Text\n"
lineText += " Char2: Text\n"
lineText += " Char3: Text\n"
lineText += " Char4: Text\n"
lineText += " Director: Text\n"
lineText += " Type: Text\n"
lineText += " RelDateTxt: Text\n"
lineText += " RelDateJul: Real\n"
lineText += " ViewDateTxt: Text\n"
lineText += " ViewDateJul: Real\n"
lineText += " Page: Integer\n"
lineText += " Source: Text\n"
lineText += " Rating: Integer"
print lineText
print '-'*22
def showRecords(recordset):
print '-'*80
# count = 0
# size = len(recordset)
for record in recordset:
lineText = " " + str(record[0]).ljust(5) # ID
if len(record[1]) > MAX_TITLE_LENGTH:
title = record[1][:MAX_TITLE_LENGTH]
else:
title = record[1]
lineText += title.ljust(31) # Title
lineText += record[6].split()[-1].ljust(10) # Director
lineText += record[8].ljust(12) # Release Date
lineText += record[2].ljust(18) # Char1
lineText += record[7] # Type
print lineText
lineText = " "*6 + record[13].ljust(31) # Source
# lineText += str(record[14]).ljust(10) # Rating
lineText += " ".ljust(10) # Rating
lineText += record[10][0:10].ljust(12) # View Date
if record[3] != '':
lineText += record[3].ljust(18) # Char2
else:
lineText += ''.ljust(18)
lineText += str(record[12]) # Ref. Page
print lineText
if record[4] != '':
lineText = " "*59 + record[4] # Char3
print lineText
if record[5] != '':
lineText = " "*59 + record[5] # Char4
print lineText
print '-'*80
# count += 1
# size -= 1
# if count > 11 and size > 0:
# raw_input("\nPress ENTER to view next set of records ")
# count = 0
# print '\n' + '-'*80
def exeSQL(sql):
try:
cursor.execute(sql)
recordset = cursor.fetchall()
print "\n %d Records Returned" % len(recordset)
showRecords(recordset)
except sqlite3.OperationalError as e:
print " ERROR: " + e.message
finally:
raw_input("\n Press 'ENTER' to show main menu...")
# Main program execution starts here
# Create the database, a connection to it and a cursor
connection = sqlite3.connect('toons.db')
cursor = connection.cursor()
showMenu()
# Close the connection
cursor.close()
connection.close()
|
8e68279628e9d5680fa5c12ee8e1e43531c1b76f | pyaephyokyaw15/PythonFreeCourse | /chapter3/assignment.py | 91 | 4.03125 | 4 | x = 1
print("x is ",x)
x = x + 3
print("x is ", x )
x += 3 # x = x + 3
print("x is ", x ) |
668ff275f79e8d4918bbcc901b76502010171717 | jedly/python-programming | /alphabet.py | 157 | 4.21875 | 4 | cha = input("Enter a character: ")
if((cha>='a' and ch<= 'z') or (cha>='A' and ch<='Z')):
print(cha, "Alphabet")
else:
print(cha, "Not an Alphabet")
|
b8f93db6637fc266d0c8243283c8af05062ca70e | nrhorowitz/cs170-pogject | /algorithm/simAnn.py | 12,486 | 4.125 | 4 | """
simulatedAnnealing() takes in path, which is a list of pathPoints, points, which is a list of Points, currdropoffs, which is a dictionary that maps
a ta home index to the pathPoint. so if someone living in index 0, and was dropped off at index 3 of the path, it would contain
the mapping 0:3
it then changes path to be the calculated optimum. No return
adjacencyMatrix is an adjacency matrix of the graph
#avg edge weight is the averageedgeweight of the graph
"""
from random import randint
import random
import math
from pointsToIndices import costOfPoints
from copy import deepcopy
#an object represents each vertex in original graph
class Point:
def __init__(self, label, adjacentVertices, rawLabel):
self.rawLabel = rawLabel
self.label = label
self.adjacentVertices = adjacentVertices
#an object representing a point in the path
class pathPoint:
def __init__(self, point, dropoffs, copyPoint=False):
if copyPoint:
self.rawLabel = point.rawLabel
self.label = point.label
self.adjacentVertices = point.adjacentVertices
self.dropoffs = set(point.dropoffs)
else:
self.rawLabel = point.rawLabel
#int labeling graph vertices from 0 to |V| - 1
self.label = point.label
#list of vertices that this vertex has an edge to in the original graph LIST OF LABELS
self.adjacentVertices = point.adjacentVertices
#list of destinations for people dropped off here [cory, dwinelle] SET OF LABELS
self.dropoffs = set(dropoffs)
#path is list of pathPoints in order of the path. points is a list of points that represent the graph
def cost(path, adjacencyMatrix, final = False):
return costOfPoints(path, adjacencyMatrix, final)
#currdropoffs is a dictionary that is dropoff label to index in path
def simulatedAnnealing(path, points, currdropoffs, adjacencyMatrix, avgEdgeWeight = 0):
coolingRate = .9939
stopTemp = -avgEdgeWeight[0] / math.log(.1)
temp = -avgEdgeWeight[2]/math.log(.8)
worstChange, minChange = 0, float("-inf")
currCost = cost(path, adjacencyMatrix)
optimumdropoff = deepcopy(currdropoffs)
optimumCost = currCost
optimumPath = deepcopy(path)
print("Soda Sol:", currCost)
while(temp > stopTemp):
# print(currCost)
# for i in path:
# print(i.label, end = " ")
# print()
choice = randint(0, 1000)
currPath = path[:]
currdropoffsDict = deepcopy(currdropoffs)
#add a random vertex before place
if (choice >= 450):
# print("adding")
place = randint(1, len(path) - 1)
pointToAdd = points[random.choice(path[place - 1].adjacentVertices)]
pointToAdd = pathPoint(pointToAdd, [])
chance = randint(0, 10)
# print(path[place - 1].adjacentVertices, random.choice(path[place - 1].adjacentVertices), path[place - 1].adjacentVertices, place, chance, pointToAdd.adjacentVertices)
if (chance > 3):
if (path[place - 1].label in pointToAdd.adjacentVertices and path[place].label in pointToAdd.adjacentVertices):
# print(pointToAdd.label, place)
# print("adding vertex\n")
for i in currdropoffs.keys():
if currdropoffs[i] >= place:
currdropoffs[i] +=1
path = path[0:place] + [pointToAdd] + path[place:]
# print("updated")
# for i in path:
# print(i.label, sep = '')
else:
if (path[place - 1].label in pointToAdd.adjacentVertices and path[place - 1].label != path[place].label ):
prevCopy = pathPoint(points[(path[place - 1].label)], [])
for i in currdropoffs.keys():
if currdropoffs[i] >= place:
currdropoffs[i] +=2
path = path[0:place] + [pointToAdd] + [prevCopy] + path[place:]
# print("\n")
#remove vertices
elif (choice > 350 and len(path) >= 3):
place = randint(1, len(path) - 2)
numRemove = randint(1, len(path) // 3)
if len(path) - 1 - place < numRemove:
numRemove = randint(1, len(path) - 1 - place)
# print(place, numRemove, "removedata", len(path))
if (path[place - 1].label in path[place + numRemove].adjacentVertices or path[place - 1].label == path[place + numRemove].label):
# print("removing vertex\n")
currPath[place] = pathPoint(currPath[place], [], True)
currPath[place + numRemove] = pathPoint(currPath[place + numRemove], [], True)
currPath[place - 1] = pathPoint(currPath[place - 1], [], True)
if place > 2:
currPath[place - 2] = pathPoint(currPath[place - 2], [], True)
lostdropoffs = []
for i in range(place, place + numRemove):
lostdropoffs += path[i].dropoffs
if(lostdropoffs):
for i in lostdropoffs:
destination = randint(0,1)
# print(destination , place+numRemove != len(path) - 1)
if destination and place+numRemove != len(path) - 1:
path[place + numRemove].dropoffs.add(i)
currdropoffs[i] = place + numRemove
# print(i, "was moved to",place + + numRemove, path[place].dropoffs)
else:
path[place - 1].dropoffs.add(i)
currdropoffs[i] = place - 1
# print(i, "was moved to", place - 1)
for i in currdropoffs.keys():
if currdropoffs[i] >= place + numRemove:
currdropoffs[i] -=numRemove
path = path[:place] + path[place + numRemove:]
#merging two points into one if they are adjacent and equal
place -= 1
# for i in path:
# print(list(i.dropoffs), i.label)
if (path[place].label == path[place + 1].label and len(path) > 2):
currPath[place] = pathPoint(currPath[place], [], True)
currPath[place + 1] = pathPoint(currPath[place + 1], [], True)
for i in path[place + 1].dropoffs:
path[place].dropoffs.add(i)
currdropoffs[i] -=1
for i in currdropoffs.keys():
if currdropoffs[i] > place:
currdropoffs[i] -=1
path = path[:place + 1] + path[place + 2:]
#if they merged onto last point
if (place == len(path) - 1):
for i in path[place].dropoffs:
path[place - 1].dropoffs.add(i)
currdropoffs[i] -=1
path[place].dropoffs = set()
elif (choice > 349):
if randint(0, 8) == 2:
currdropoffs = deepcopy(optimumdropoff)
currCost = optimumCost
path = deepcopy(optimumPath)
else:
# print("moving DropOff\n")
randdropoff = list(currdropoffs.keys())[randint(0, len(currdropoffs) - 1)]
destination = randint(0, len(path) - 2)
place = currdropoffs[randdropoff]
# print(place, currdropoffs)
currPath[place] = pathPoint(currPath[place], [], True)
currPath[destination] = pathPoint(currPath[destination], [], True)
path[place].dropoffs.remove(randdropoff)
path[destination].dropoffs.add(randdropoff)
currdropoffs[randdropoff] = destination
# print(destination, randdropoff, place, currdropoffs)
# for i in range(len(path)):
# print(list(path[i].dropoffs), i)
# if destination:
# if (place < len(path) - 2):
# for i in range(len(path)):
# print(list(path[i].dropoffs), i)
# print(place, list(path[place].dropoffs), "dropoffs1", list(path[place + 1].dropoffs), randdropoff, currdropoffs)
# currPath[place + 1] = pathPoint(currPath[place + 1], [], True)
# path[place + 1].dropoffs.add(randdropoff)
# path[place].dropoffs.remove(randdropoff)
# currdropoffs[randdropoff] = place + 1
# # print(place, list(path[place].dropoffs),list(path[place + 1].dropoffs), "dropoffs2", randdropoff, currdropoffs)
# # for i in range(len(path)):
# # print(list(path[i].dropoffs), i)
# else:
# if (place != 0):
# for i in range(len(path)):
# print(list(path[i].dropoffs), i)
# print(place, list(path[place].dropoffs), "dropoffs3", list(path[place - 1].dropoffs), randdropoff, currdropoffs)
# currPath[place - 1] = pathPoint(currPath[place - 1], [], True)
# path[place - 1].dropoffs.add(randdropoff)
# path[place].dropoffs.remove(randdropoff)
# currdropoffs[randdropoff] = place - 1
# # print(place, list(path[place].dropoffs),list(path[place - 1].dropoffs), "dropoffs4", randdropoff, currdropoffs)
# # for i in range(len(path)):
# # print(list(path[i].dropoffs), i)
newCost = cost(path, adjacencyMatrix)
# print(newCost, currdropoffs)
# for i in path:
# print(i.label, end = ' ')
# for i in range(len(path)):
# print(list(path[i].dropoffs), i)
# print()
if newCost <= optimumCost:
optimumdropoff = deepcopy(currdropoffs)
optimumCost = newCost
optimumPath = deepcopy(path)
elif (newCost <= currCost):
currCost = newCost
# print("taken")
else:
rand = random.random()
# print(currCost, newCost, "costs")
if (worstChange > currCost - newCost):
worstChange = currCost - newCost
if minChange < currCost - newCost:
minChange = currCost - newCost
if rand < math.exp(-(newCost - currCost)/temp):
# print("temps", "Delta:", (newCost - currCost), "Temperature:", (temp), "rand:", rand, "prob:", math.exp(-float(newCost - currCost)/(temp)))
# print("taken")
currCost = newCost
# for i in range(len(path)):
# print(list(path[i].dropoffs), i)
else:
# print("not")
path = currPath
currdropoffs = currdropoffsDict
temp = temp * coolingRate
# sumError = 0
# for i in path:
# sumError += len(i.dropoffs)
# if(sumError >4):
# # print("HOLUP")
# # print(currdropoffs)
# for i in path:
# print(list(i.dropoffs), i.label)
# exit()
# for i in currdropoffs.keys():
# if (i not in path[currdropoffs[i]].dropoffs):
# print("HOLUP")
# print(list(sumHomes))
# print(currdropoffs)
# for i in path:
# print(list(i.dropoffs), i.label)
# exit()
cost(optimumPath, adjacencyMatrix, True)
print("final Solution Cost:", optimumCost)
# for i in range(len(optimumPath)):
# print(list(optimumPath[i].dropoffs), i)
return optimumPath
|
c800e5e9923477c555fde6f1797a4425ff605454 | dvjn/AdventOfCode2020 | /Day09/part1.py | 679 | 3.734375 | 4 | import sys
from itertools import combinations
def find_pair_sum(sequence, target):
bag = set(sequence)
for num1, num2 in combinations(bag, r=2):
if num1 != num2 and num1 + num2 == target:
return True
return False
def find_first_stantdout(sequence, preamble=25):
for i, current_number in enumerate(sequence[preamble:]):
if not find_pair_sum(sequence[i : preamble + i], current_number):
return current_number
def main():
with open(sys.argv[1], "r") as input_file:
sequence = [int(line.strip()) for line in input_file]
print(find_first_stantdout(sequence))
if __name__ == "__main__":
main()
|
225c053b5b304dc62532aca4685d13a9358f85b3 | emscherl/adventofcode | /03_dec/main.py | 683 | 3.546875 | 4 | with open('data.txt') as input:
lines = [line.rstrip() for line in input]
def tree_slope(x, y, tree_list):
count = 0
line = 0
trees = 0
while line < len(tree_list):
f = tree_list[line]
if f[count] == '#':
trees += 1
line += y
count += x
if count >= len(f):
count -= len(f)
return trees
trees_1 = tree_slope(1, 1, lines)
print(trees_1)
trees_2 = tree_slope(3, 1, lines)
print(trees_2)
trees_3 = tree_slope(5, 1, lines)
print(trees_3)
trees_4 = tree_slope(7, 1, lines)
print(trees_4)
trees_5 = tree_slope(1, 2, lines)
print(trees_5)
print(trees_1 * trees_2 * trees_3 * trees_4 * trees_5)
|
998475c17a2e2568a79a0a6285316ed76c56e381 | prpratheek/Interview-Problem-Statements-HacktoberFest2020 | /firstNonRepeatingCharacter.py | 274 | 3.546875 | 4 | def firstNonRepeatingCharacter(word):
d={}
for i in word:
if i in d:
d[i]+=1
else:
d[i]=1
for i in d:
if d.get(i)==1: #constant time
print(i)
break
else:
print("All letter are repeating")
firstNonRepeatingCharacter("anubhav sethi")
|
6674ac53ddfd9a334b2051611ee1177064823e68 | Rajshree208/demo1 | /pythonproject.py | 4,511 | 4.03125 | 4 | from time import sleep
import sys
def main():
print("Welcome to my first application in python")
sleep(1)
print("Please make a selection below")
sleep(1)
print("1.)Encrypt some text and store it in a file")
print("2.)Decrypt the data stored in the file")
print("3.)Convert my speech to text and then text to speech")
print("4.)Getting Bored...Let's play a game")
print("5.)Exit the program")
s=eval(input("Please make your selection:"))
if s==1:
Encryptmessage()
elif s==2:
Decryptmessage()
elif s==3:
sttts()
elif s==4:
game()
elif s==5:
sys.exit()
else:
print("U didnot choose from the valid options \nRestarting program")
main()
import getpass
def getPassword():
userPassword = ''
attempts = 3
counter = 0
print("This application is password protected, you have 3 attempts at the password before the system exits")
sleep(1)
storedPassword = 'rajshree'
userPassword = getpass.getpass('Enter password')
if userPassword == storedPassword:
main()
else:
while counter != 3:
print('That was incorrect! You have ' + str(attempts-counter) + ' attempts left:')
counter += 1
userPassword = input('Enter password')
if userPassword == storedPassword:
main()
if counter == 3:
print('Unrecognized user')
sleep(2)
sys.exit()
def Encryptmessage():
input1 = ''
continue1 = 'yes'
print("Any data entered here will be encrypted and written to a file")
while continue1 == 'yes':
prompt = input("Please enter what you want encrypted:")
for i in range(0, len(prompt)):
input1 = input1 + chr(ord(prompt[i]) - 2)
efile = open('encryptedfile.txt','r+')
efile.read()
efile.write(input1+"\n")
efile.close()
continue1 = input("Would you like to input anything else(yes or no):")
if continue1 == 'yes':
Encryptmessage()
elif continue1 == 'no':
print(prompt)
break
continue1 = input("Would you like to continue the program(yes or no)")
if continue1 == 'yes':
main()
else:
sys.exit()
def Decryptmessage():
output1=''
dfile=open('encryptedfile.txt','r')
for i in dfile:
dfile.seek(0)
readdata = dfile.read()
for x in range(len(readdata)):
output1 = output1 + chr(ord(readdata[x]) + 2)
print(output1)
dfile.close()
continue1 = input("Would you like to continue the program(yes or no)")
if continue1 == 'yes':
main()
else:
sys.exit()
import speech_recognition as sr
def sttts():
txt=''
r=sr.Recognizer()
with sr.Microphone() as source:
print('Say something')
audio=r.listen(source)
try:
txt=r.recognize_google(audio)
print('You had Spoken')
print(txt)
except:
print("Sorry can't hear you!!!")
sttts()
from gtts import gTTS
import os
tts=gTTS(text=txt,lang='hi')
tts.save('My_Audio3.mp3')
os.system('mpg321 My_Audio3.mp3')
os.system('start My_Audio3.mp3')
continue1 = input("Would you like to continue the program(yes or no)")
if continue1 == 'yes':
main()
else:
sys.exit()
from random import *
def game():
print('\n------------------GUESS THE NUMBER-----------------------\n')
print("Let's see how much smart u r in guessing a number....\n")
sleep(2)
x=randint(1,100)
d=''
count=0
while(True):
d=int(input('Enter a number of your choice'))
if d>x and 1<=(d-x)<=10:
print("Your guess is high")
elif d<x and 1<=(x-d)<=10:
print("Your guess is low")
elif (x-d)>10:
print("Your guess is too low")
elif (d-x)>10:
print("Your guess is too high")
else:
print("You guessed right")
break
count+=1
print("you were able to guess the number in %d attempts"%count)
continue1 = input("Would you like to continue the program(yes or no)")
if continue1 == 'yes':
main()
else:
sys.exit()
getPassword()
|
c3152e60ab655efbc5a18601af0cc7191780ea5a | srinijadharani/DataStructuresLab | /01/01_e_prime_numbers.py | 584 | 4.3125 | 4 | # 1e. Program to print the prime numbers up to a specified limit.
# take the start and end index from the user
start = int(input("Enter the start index: "))
end = int(input("Enter the stop index: "))
# function to check if the number is prime or not and then print it
def print_prime(start, end):
for num in range(start, end + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num, end = " ")
# function call
print_prime(start, end) |
bdde706e936077402bbff83ee9d49a0c700a8a9f | swathi697/File-based-key_value-datastore | /Operations_accessing.py | 1,575 | 4.125 | 4 | #here are the commands to demonstrate how to access and perform operations on a main file
import main_code as x
import json
#importing the main file("main_code" is the name of the file I have used) as a library
while(True):
print("Enter 1 for Insert, 2 for Find, 3 for Replace, 4 for Delete, 5 for Exit :\n")
n=int(input("Enter the Number :"))
if(n==1):
s1=input("Enter the key for create :")
s2=int(input("Enter the Value for create :"))
s3=int(input("Enter the Time to live value :"))
x.create(s1,s2,s3) #it creates the respective key and its value from the database(memory is also freed)
elif(n==2):
s1=input("Enter the Key for Finding its value :")
x.find(s1) #it returns the value of the respective key in Jasonobject format 'key:value'
elif(n==3):
s1=input("Enter the Key for replace :")
s2=int(input("Enter the Value for replace :"))
x.replace(s1,s2) #it replaces the initial value of the respective key with new value
elif(n==4):
s1=input("Enter the Key for delete :")
x.delete(s1) #it deletes the respective key and its value from the database(memory is also freed)
elif(n==5):
break
x.display()
x.creating_file()
#the code also returns other errors like
#"invalidkey" if key_length is greater than 32 or key_name contains any numeric,special characters etc.,
#"key doesnot exist" if key_name was mis-spelt or deleted earlier
#"File memory limit reached" if file memory exceeds 1GB
|
a72e2ca4b67ecb7bb88476cc72e9e13bdfc47583 | im-jonhatan/hackerRankPython | /introduction/Print_function.py | 137 | 3.515625 | 4 | if __name__ == '__main__':
n = int(input())
number = 1
while number <= n:
print(number, end="")
number += 1
|
01af9ebda37b9d558e31338d5218e121e14a9ce4 | Kv73396n/PythonExercises | /Exercise8.py | 498 | 3.96875 | 4 |
# coding: utf-8
# In[12]:
#Ashley Vargas, Karina Vargas
#8a
a = [1, 2, 3, 4]
#8b
b = a
#8c
b[1] = 5
#8d
print(a)
print(b)
#result: a: [1, 5, 3, 4]
#b :[1, 5, 3, 4]
#a had a value changed to the value listed for b[1].
#8e
c = a[:]
#8f
c[1] = 7
#8g
print(a)
print(c)
# result: a: [1, 5, 3, 4]
# c: [1, 7, 3, 4]
#Now only c had a value changed to 7 instead. List a stayed the same as before.
def set_first_element_to_zero(list):
d = a
d[0] = 1
print(set_first_element_to_zero(a))
|
b738473c0f4d635873218e4cc54ba7bfb48827b0 | priteshmehta/leetcode | /add_two_numbers.py | 1,230 | 3.90625 | 4 | #Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n1 = l1
n2 = l2
carry = 0
ans_linked_list = []
while n1 != None or n2 != None:
num1 = num2 = 0
if n1:
num1 = n1.val
n1 = n1.next
if n2:
num2 = n2.val
n2 = n2.next
new_num = num1 + num2 + carry
carry = 0
if new_num >= 10:
new_num = new_num%10
carry = 1
#print("rel: ", new_num, carry)
ans_linked_list.append(ListNode(new_num))
if carry == 1:
ans_linked_list.append(ListNode(carry))
head = ans_linked_list[0]
new_node = head
for node in ans_linked_list[1:]:
new_node.next = node
#print(new_node.val)
new_node = node
return head
#Input: (2 -> 4) + (5 -> 6 -> 4)
#Output: 7 -> 0 -> 5
l1 = ListNode(2)
n2 = ListNode(4)
l1.next = n2
#n3 = ListNode(3)
#n2.next = n3
l2 = ListNode(5)
n2 = ListNode(6)
l2.next = n2
n3 = ListNode(4)
n2.next = n3
addTwoNumbers(l1, l2)
|
6e9b86cb71610ce985357a6da3553fe9e01937c5 | rainamra/TA_Project | /Assignment.py | 1,463 | 3.828125 | 4 | def convertToRadians(degrees):
return(degrees * 3.14 / 180)
degrees = 150
radians = convertToRadians(degrees)
print ("Degrees :",degrees)
print ("Radians :",radians)
student1 = 80.0
student2 = 90.0
student3 = 66.5
student_scores = [80.0, 90.0, 66.5]
print("Student scores:")
for student_scores in student_scores:
print(student_scores)
average = (student1 + student2 + student3)/3
print("Average:", average)
class1 = 32
class2 = 45
class3 = 51
member1 = class1 // 5
member2 = class2// 7
member3 = class3 //6
print("Number of students in each group:")
print("Class 1:", member1)
print("Class 2:", member2)
print("Class 3:", member3)
leftover1 = 32 % 5
leftover2 = 45 % 7
leftover3 = 51 % 6
print("Number of students leftover:")
print("Class 1:", leftover1)
print("Class 2:", leftover2)
print("Class 3:", leftover3)
def convertToCirumference (pie_radius):
return (2 * pi * pie_radius)
pi = 3.14
pie_diameter = 55.4
pie_radius = pie_diameter / 2
circumference_msg = "Jimmy’s pie has a circumference:"
circumference = convertToCirumference (pie_radius)
print(circumference_msg, circumference)
def convertToWavelength (frequency):
return (speed/frequency)
meters = 20580
speed = meters / 60
frequency = 256
wavelength = convertToWavelength (frequency)
print("The speed (m/s):", speed)
print("The frequency (Hz):", frequency)
print("The wavelength (m):", wavelength)
xlist = ["aa", "bb", "cc"]
for i in [2, 1, 0]:
print(xlist[i], end=" ") |
d80aba0e8a17191ef3af977df4c1df8d2370f716 | mohit5335/python-programs | /database.py | 571 | 3.640625 | 4 | #program to fetch data from mtsql database in python
import mysql.connector as sql
mydb = sql.connect(host="localhost",user="username",passwd="*****",database="*****")
mycursor = mydb.cursor()
mycursor.execute("Select * from student") #enetr the aommand you want to fetch data of
result = mycursor.fetchall() #fetch all data from database
#result = mycursor.fetchone() #fetch first column from database
for i in result:
print(i) #print result of each row in different line
#print (result) print result in one line |
c2dafad1dc460b651b98f388b0f43d8b4ecb4a66 | h74zhou/leetcode | /Medium/148. Sort List.py | 628 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
arr = []
curr = head
while curr:
arr.append(curr.val)
curr = curr.next
arr.sort()
start = ListNode()
dummy = start
for i in arr:
newNode = ListNode(i)
start.next = newNode
start = start.next
return dummy.next
|
64bf3fb83d1f31caea2c5f326fc7f82278b5a580 | edwardjrolls/backgammon | /board.py | 15,025 | 3.53125 | 4 | import copy
import random
import numpy as np
from sys import stdin
"""
Note that a gamestate is given by a length 26 vector:
0 - 23: Each point on the board, with +ve values for home player (i.e. the next move)'s pieces, -ve for oppo
24: Hit pieces of player (+ve values)
25: Hit pieces of oppo (-ve values)
"""
"""
1 KNOWN BUG:
1) To end the game, if we have a piece at 1 and a rolle of (6,1), then the correct move is [(1,0),(0,-6)].
Only need a minor tweak & shouldn't make a difference to who wins
"""
# Flips a state after a move
def flipState(state):
return [state[i] for i in range(23,-1,-1)]+[state[25]]+[state[24]]
# Extends a state to 50 slots (24 for player A, 24 for player B, 2 dead zones)
def extendState(state):
return [max(state[i],0) for i in range(24)] + [min(state[i],0) for i in range(24)] + [state[24],state[25]]
# The board class, which requires as inputs an initial gamestate, and two strategies to play against each other
class Board:
# Initialise the board
def __init__(self,strategyA='random',strategyB='random',parametersA=None,parametersB=None,gamestate=None):
# If no gamestate given, then initialise the board
if not gamestate:
gamestate = self.newBoard()
self.gamestate = gamestate
self.strategyA=strategyA
self.strategyB=strategyB
self.parametersA=parametersA
self.parametersB=parametersB
# Allows a board to be printed. X for away player, O for home player
def __str__(self):
string = '-'*42+'\n'
string += '|' + ' '*40 + '|\n'
# Number the board
string+= '| '
for i in range(12,24):
string+=str(i).zfill(2)+' '
string+=' |\n'
# First row of upper board
string+= '| '
for i in range(12,24):
if abs(self.gamestate[i])>5:
string+=str(abs(self.gamestate[i]))
elif self.gamestate[i]>0:
string+='O'
elif self.gamestate[i]<0:
string+='X'
else:
string+='|'
string+=' '
string+=' |\n'
# Next 4 rows of upper board
for j in range(1,5):
string+='| '
for i in range(12,24):
if self.gamestate[i]>j:
string+='O'
elif self.gamestate[i]<-j:
string+='X'
else:
string+='|'
string+=' '
string+=' |\n'
#empty row
string += '|' + ' '*40 + '|\n'
# How many dead tokens
string += '|' + ' '*3 + 'X'*(-self.gamestate[25]) + ' '*(15+self.gamestate[25]) + ' '*4
string += ' '*(15-self.gamestate[24]) + 'O'*self.gamestate[24] +' '*3 + '|\n'
#empty row
string += '|' + ' '*40 + '|\n'
# Top 4 rows of lower board
for j in range(4,0,-1):
string+='| '
for i in range(11,-1,-1):
if self.gamestate[i]>j:
string+='O'
elif self.gamestate[i]<-j:
string+='X'
else:
string+='|'
string+=' '
string+=' |\n'
# Final row of lower board
string += '| '
for i in range(11,-1,-1):
if abs(self.gamestate[i])>5:
string+=str(abs(self.gamestate[i]))
elif self.gamestate[i]>0:
string+='O'
elif self.gamestate[i]<0:
string+='X'
else:
string+='|'
string+=' '
string+=' |\n'
# Number the board
string+= '| '
for i in range(11,-1,-1):
string+=str(i).zfill(2)+' '
string+=' |\n'
string += '|' + ' '*40 + '|\n'
string += '-'*42
return string
# Sets up a new board with standard piece placings
def newBoard(self):
gamestate = [0]*26
gamestate[0] = -2
gamestate[5] = 5
gamestate[7] = 3
gamestate[11] = -5
gamestate[12] = 5
gamestate[16] = -3
gamestate[18] = -5
gamestate[23] = 2
return gamestate
# Gives the new 'state' following a move of the form (start,finish)
def changeState(self,state,move):
if move[1]<0:
state[move[0]]-=1
elif state[move[0]]<1:
raise ValueError("No tiles exist at this space")
elif state[move[1]]<-1:
raise ValueError("Move onto a blocked tile")
elif state[move[1]]==-1:
state[move[1]]=1
state[25]-=1
state[move[0]]-=1
else:
state[move[1]]+=1
state[move[0]]-=1
# Find a list of legal moves for dice roll where the two dice are not equal, done in the order die1 then die2
def potentialMovesOrder(self,die1,die2):
firstMoveList = []
finalMoveList = []
state = copy.copy(self.gamestate)
# Make the first move
maxPiece = max([i for i in range(25) if state[i]>0])
if state[24]>0:
pieceStart = [24]
else:
pieceStart = [i for i in range(24) if state[i]>0]
for i in pieceStart:
stateCp = copy.copy(state)
move = (i,i-die1)
if (i+1>die1 and state[i-die1]>=-1) or (maxPiece==i and i+1<=die1) or (maxPiece<=5 and i+1==die1):
self.changeState(stateCp,move)
firstMoveList.append((move,stateCp))
# Make the second move
for firstMove,state in firstMoveList:
try:
maxPiece = max([i for i in range(25) if state[i]>0])
except ValueError:
finalMoveList = [[firstMove]]
break
if state[24]>0:
pieceStart = [24]
else:
pieceStart = [i for i in range(24) if state[i]>0]
for i in pieceStart:
move = (i,i-die2)
if (i+1>die2 and state[i-die2]>=-1) or (maxPiece==i and i+1<=die2) or (maxPiece<=5 and i+1==die2):
finalMoveList.append([firstMove,move])
if not len(firstMoveList):
return [[]]
elif not len(finalMoveList):
return [[mv[0]] for mv in firstMoveList]
else:
return finalMoveList
# Find a list of legal moves for a repeated dice roll
def potentialMovesRepeatedDice(self,die1):
movesDict={}
movesDict[()] = copy.copy(self.gamestate) # A move here is ((x,y),(a,b),(b,c))
movesList=[[]]
completeMove = []
while len(movesList)>0:
moves = movesList.pop()
state = copy.copy(movesDict[tuple(moves)])
minMoveMade = min([mv[0] for mv in moves]+[24])# Consider moves only less than the
#print(moves,movesList,minMoveMade,completeMove)
if state[24]>0: # If we have any hit pieces, get them on the board
move = (24,24-die1)
if state[24-die1]>=-1:
self.changeState(state,move)
moves.append(move)
if len(moves)<4:
movesList.append(moves)
else:
completeMove.append(moves)
movesDict[tuple(moves)] = state
else:
completeMove.append(moves)
else:
pieceStart=[i for i in range(minMoveMade+1) if state[i]>0]
try:
maxPiece = max([i for i in range(25) if state[i]>0])
except ValueError:
completeMove = [moves]
break
moveMade = False
for i in pieceStart:
movesCp = copy.copy(moves)
stateCp = copy.copy(state)
move = (i,i-die1)
if (i+1>die1 and state[i-die1]>=-1) or (maxPiece==i and i+1<=die1) or (maxPiece<=5 and i+1==die1):
self.changeState(stateCp,move)
movesCp.append(move)
if len(movesCp)<4:
movesList.append(movesCp)
else:
completeMove.append(movesCp)
moveMade=True
movesDict[tuple(movesCp)] = stateCp
if not moveMade:
completeMove.append(moves)
return completeMove
# Returns a list of legal moves
def legalMoveList(self,die1,die2):
# Find the places of where pieces start
if die1==die2:
moveList = self.potentialMovesRepeatedDice(die1)
else:
moveList = self.potentialMovesOrder(die1,die2)
moveList += self.potentialMovesOrder(die2,die1)
"""
for move in moveList:
move.sort(key = lambda x: 100*x[0]+x[1], reverse=True) # Order by first tile picked, then second tile
# Need to remove copies (still some cases where the endstate is the same)
newMoveList=[]
moveSet=set()
for move in moveList:
if tuple(move) not in moveSet:
newMoveList.append(move)
moveSet.add(tuple(move))
moveList = newMoveList
"""
maxMovesMade = max([len(moves) for moves in moveList])
moveList = [moves for moves in moveList if len(moves)==maxMovesMade]
return(moveList)
# Flips the board (call after a move to signify it is the opposition's move
def flipBoard(self):
self.gamestate = [-self.gamestate[i] for i in range(23,-1,-1)]+[-self.gamestate[25]]+[-self.gamestate[24]]
# Make a random move
def randomMove(self,die1,die2):
moveList = self.legalMoveList(die1,die2)
if len(moveList)>0:
return random.choice(moveList)
else:
return tuple()
# Import a player move from the input line
def inputPlayerMove(self):
moveMade=False
while not moveMade:
try:
move = tuple(map(int,stdin.readline().rstrip().split(',')))
moveMade=True
except ValueError:
print("Not recognised as a valid input. Please retry")
return move
# Allow the player to choose the move
def playerMove(self,die1,die2):
print(self)
moveList = self.legalMoveList(die1,die2)
legalMove = False
while not legalMove:
print("The roll is {} and {}".format(die1,die2))
print("Move format is a,b to move from a to b. Deadzone is 24.")
print("If no moves are possible just return (-1,-1). Please pick moves in order they would be made")
moves=[]
print("What is move 1?")
moves.append(self.inputPlayerMove())
print("What is move 2?")
moves.append(self.inputPlayerMove())
if die1 == die2:
print("What is move 3?")
moves.append(self.inputPlayerMove())
print("What is move 4?")
moves.append(self.inputPlayerMove())
moves.sort(key=lambda x: x[0],reverse=True) # So that this is compatable with how moves are generated for the legal move list
# Remove any non-moves
while (-1,-1) in moves:
moves.remove((-1,-1))
if moves in moveList:
legalMove=True
else:
print("\nMove is not legal. Please re-enter\n")
return moves
# Makes a move based on linear regression
def linRegressionMove(self,die1,die2,parameters):
moveList = self.legalMoveList(die1,die2)
if len(moveList)==0:
return tuple()
scoreList = []
regressionType = parameters[0]
beta = parameters[1]
for moves in moveList:
state = copy.copy(self.gamestate)
for move in moves:
self.changeState(state,move)
state = flipState(state)
if regressionType=='basic':
state = np.array([1]+state,ndmin=2)
elif regressionType=='extended':
state = extendState(state)
state = np.array([1]+state,ndmin=2)
else:
raise ValueError("regression type not recognised")
score = float(np.matmul(state,beta))
scoreList.append((moves,score))
scoreList.sort(key = lambda x:x[1]) #Sort by lowest score to highest score, as we have flipped the board
return scoreList[0][0]
# Chooses a move in the game, sending to other functions depending on what the strategy is
def chooseMove(self,die1,die2,strategy='random',parameters=None):
if strategy=='random':
move = self.randomMove(die1,die2)
elif strategy=='human':
move = self.playerMove(die1,die2)
elif strategy=='linRegression':
move = self.linRegressionMove(die1,die2,parameters)
return move
# Make a move
def makeMove(self,moves):
for move in moves:
self.changeState(self.gamestate,move)
# A turn in the game. Ask player A for a move, flip the board, ask player B for a move, flip the board
def turn(self):
# Player 1
state1 = copy.copy(self.gamestate)
die1,die2 = [random.randint(1,6),random.randint(1,6)]
move = self.chooseMove(die1,die2,self.strategyA,self.parametersA)
self.makeMove(move) # Include a sanity check here perhaps
if max(self.gamestate)<=0:
return 1,state1,None # 1 for player 1 winning
self.flipBoard()
#Player 2
state2 = copy.copy(self.gamestate)
die1,die2 = [random.randint(1,6),random.randint(1,6)]
move = self.chooseMove(die1,die2,self.strategyB,self.parametersB)
self.makeMove(move)
if max(self.gamestate)<=0:
return 2,state1,state2 # 2 for player 2 winning
self.flipBoard()
return 0,state1,state2
# The game environment
def game(self):
gameOver=0
history={1:[],2:[]} # A dictionary where the key is the player about to make the move and the value is the board state they face
while not gameOver:
gameOver,state1,state2 = self.turn()
history[1].append(state1)
if state2:
history[2].append(state2)
"""
if gameOver==1:
print("Congrats to player 1!")
else:
print("Congrats to player 2!")
"""
return gameOver,history
if __name__ == '__main__':
for i in range(1000):
eddie = Board()
eddie.game()
print(i)
|
5de0cd12c56ef097978830dfcc0b85ae971eee7b | mithun2k5/Python-Code | /Python-Projects/Insert Element As per given Index.txt | 168 | 3.53125 | 4 | lst1 = ['C','D','E','F','G']
lst2 = [3,0,4,1,2]
lst3 = []
for i in range(len(lst1)):
lst3.insert(lst2[i],lst1[i])
lst3
#Result:
['D', 'F', 'G', 'C', 'E'] |
a3991de953f8a181c082816f936edca9afb7e2d3 | AidenMarko/CP1404Practicals | /prac_04/list_exercises.py | 1,172 | 4 | 4 | """
CP1404/CP5632 Practical
List Exercises
"""
def main():
if check_username():
numbers = get_numbers()
print_numbers(numbers)
def get_numbers():
numbers = []
for i in range(0, 5, 1):
number = float(input("Number: "))
numbers = numbers + [number]
return numbers
def print_numbers(numbers):
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
average = sum(numbers)/len(numbers)
print("The average of the numbers is {}".format(average))
def check_username():
usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface',
'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer',
'bob']
print("Enter your username: ")
username = input(">>> ")
if username in usernames:
print("Username Accepted")
return True
else:
print("Username Declined")
return False
main()
|
b957d7c9ac58686bb337a7c3a18091512f428b8b | Moremar/advent_of_code_2020 | /day03/part1.py | 514 | 3.53125 | 4 | def count_trees(trees, dx, dy):
x, y, count = 0, 0, 0
while y + dy < len(trees):
x += dx
y += dy
count += trees[y][x % len(trees[0])]
return count
def solve(trees):
return count_trees(trees, 3, 1)
def parse(file_name):
trees = []
with open(file_name, 'r') as f:
for line in map(str.strip, f.readlines()):
trees.append([0 if c == '.' else 1 for c in line])
return trees
if __name__ == '__main__':
print(solve(parse('data.txt')))
|
02b4ddc812135197dea6e08db15f03fa16b547dd | subodhss23/python_small_problems | /easy_probelms/lexicographicall_first_and_last.py | 415 | 4.15625 | 4 | ''' Write a function that return the lexicographically first and lexicographically
last rearrangements of a string. Output the results in the follwing manner:'''
def first_and_last(string):
string_one = sorted(string)
string_two = string_one[::-1]
return [('').join(string_one), ('').join(string_two)]
print(first_and_last("marmite"))
print(first_and_last("bench"))
print(first_and_last("scoop")) |
05aeb36b0f1785a0e6f01f2b20e1a157862bba09 | ckbullock410/ProjEuler | /Python/euler7.py | 406 | 3.5 | 4 | import math
def euler7(n):
count = 3
focus = 5
while(count < n+1):
if (isPrime(focus)):
count += 1
focus += 2
print(focus-2)
def isPrime(x):
result = True
myList = [i for i in range(3, math.ceil(math.sqrt(x)) + 1, 2)]
for n in myList:
if ((x % n) == 0):
result = False
return result
euler7(10001) |
fe698311d4e8bf12a679f9bc00a31bfa645b0480 | williamxhh/leetcode_python | /2. Add Two Numbers/solution.py | 916 | 3.6875 | 4 | #encoding=utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret_head = ListNode(-1)
pre = ret_head
carry = 0
while l1 or l2 or carry:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
sum = l1_val + l2_val + carry
val = sum % 10
carry = sum / 10
pre.next = ListNode(val)
pre = pre.next
l1 = l1.next
l2 = l2.next
return ret_head.next
so = Solution()
a = ListNode(2)
a.next = ListNode(4)
a.next.next = ListNode(3)
b = ListNode(5)
b.next = ListNode(6)
b.next.next = ListNode(4)
so.addTwoNumbers(a, b)
|
024d7b4e99642cdbad79272961949d46a5a422f4 | Esot3riA/KHU-Algorithm-2019 | /1003_Quick_Sort.py | 543 | 3.6875 | 4 | def quick_sort(s, low, high):
if high > low:
pivot_point = partition(s, low, high)
quick_sort(s, low, pivot_point-1)
quick_sort(s, pivot_point+1, high)
return s
def partition(s, low, high):
pivot_item = s[low]
j = low
for i in range(low+1, high+1):
if s[i] < pivot_item:
j += 1
s[i], s[j] = s[j], s[i]
pivot_point = j
s[low], s[pivot_point] = s[pivot_point], s[low]
return pivot_point
arr = [3, 5, 2, 9, 10, 14, 4, 8]
quick_sort(arr, 0, 7)
print(arr)
|
88c184da9b91e8997c5aa455293573aa8a30dbc1 | raghav4bhasin/Assignment8 | /Question1.py | 583 | 4.3125 | 4 | # Q.1- Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def getArea(self):
area = math.pi * math.pow(self.radius, 2)
return area
def getCircumf(self):
circumf = (2 * math.pi) * self.radius
return circumf
rad = int(input("Enter the radius of Circle: "))
circ = Circle(rad)
print(" ")
print("Circumference: ",circ.getCircumf())
print("Area: ",circ.getArea())
|
83547ccc6d1a645025545c03292360dcd31ca7b9 | meelod/bank-account | /CheckingAccount.py | 797 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 18:58:58 2020
@author: meeps360
"""
from BankAccount import *
class CheckingAccount(BankAccount):
def __init__(self, name, checking_account_id, checking_balance, per_check_fee):
BankAccount.__init__(self, name, checking_account_id, checking_balance)
self.per_check_fee = per_check_fee
def calculateCheckFee(self, number_of_checks,):
return self.per_check_fee * number_of_checks
def __str__(self):
return BankAccount.__str__(self)
def getPerCheckingFee(self):
return self.per_check_fee
def setPerCheckingFee(self, per_fee):
self.per_check_fee = per_fee
def getBalance(self):
return self.checking_balance |
8b4ee9cabf65cbe32ec3acac404ff951cc0908b2 | leejin21/algProbSolve-PY | /programmars/hash/hash_2.py | 1,318 | 3.578125 | 4 | # 전화번호 목록
# 접두어 맞는 지 찾기
# 내 풀이
class Num:
def __init__(self):
self.link = [None]*10
self.end = False
def hash2(phone_book):
# 종료: 접두어 맞는 것 하나만 찾으면.
phone_book = sorted(phone_book)
head = Num()
for ph in phone_book:
temp = head
for i in range(len(ph)):
n = int(ph[i])
if temp.link[n] != None and temp.link[n].end == True:
return False
elif temp.link[n] == None:
temp.link[n] = Num()
temp = temp.link[n]
temp.end = True
return True
# 다른 사람 풀이1
def ans_hash2_1(phone_book):
# zip 이용하고 startwith
phone_book = sorted(phone_book)
for p1, p2 in zip(phone_book, phone_book[1:]):
if p2.startswith(p1):
return False
return True
# 다른 사람 풀이2
def ans_hash2_2(phone_book):
# hash 제대로 이용
hash_map = {}
for ph_num in phone_book:
hash_map[ph_num] = 1
for ph_num in phone_book:
temp = ""
for n in ph_num:
temp += n
if temp in hash_map and temp != ph_num:
return False
return True
phone_book = ['119', '97674223', '1195524421']
print(ans_hash2_1(phone_book))
|
d3feb5f11dfef2b1924bcea48acb7b160e69ae1a | navyanekkala/python-classes | /mymodule.py | 117 | 3.765625 | 4 | def add(a,b):
return a+b
def fact(n):
f=1
for i in range(1,n+1):
f *= i
return f
pi = 3.14
|
cafba5107c9eff8f6b3c624ac25ee6b1d1f0e557 | rudyabs/Materi-Purwadhika-Data_Science | /belajar_pandas/060-pandas_numpy_selection.py | 1,456 | 3.84375 | 4 | '''
menunjukan selection dengan
menggunakan contoh file fifa19
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df_main = pd.read_csv('data.csv')
# print(df['Name'])
df = df_main.copy()
'''
print(df['Overall'].max())
print(df['Overall'].min())
print(df['Overall'].mean())
print(df[df['Overall']==df['Overall'].max()])
print(df[df['Overall']==df['Overall'].max()]['Name'])
print(df[df['Overall']==df['Overall'].max()][['Name','Club']])
print(df[df['Overall']>=90][['Name','Position','Club']])
print(df[
['Name','Position','Club']]
[df['Overall']>=90]
)
print(
df[['Name','Position','Club']]
[df['Overall']>=90]
[df['Club']=='Real Madrid']
)
'''
# tanpa warning deklarasikan ke df
'''
df = df[['Name','Position','Club']][df['Overall']>=90]
df = df[df['Club']=='Real Madrid']
print(df)
print(df['Overall'])
dfTranspose = df.T
print(dfTranspose)
print(dfTranspose.index)
'''
young_good = df[df['Age']<25][df['Overall']>=85]
young_bad = df[df['Age']<25][df['Overall']<85]
old_good = df[df['Age']>=25][df['Overall']>=85]
old_bad = df[df['Age']>=25][df['Overall']<85]
plt.scatter(young_good['Age'], young_good['Overall'], c='red')
plt.scatter(young_bad['Age'], young_bad['Overall'], c='blue')
plt.scatter(old_good['Age'], old_good['Overall'], c='yellow')
plt.scatter(old_bad['Age'], old_bad['Overall'], c='green')
plt.grid(True)
plt.legend(['Young_Good', 'Young_Bad', 'Old_Good','Old_Bad'])
plt.show()
|
3b806cd3d4eb62cb1580cdb2e4ecc62d03836603 | vyxxr/python3-curso-em-video | /Mundo1/010.py | 288 | 3.828125 | 4 | '''
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar
Considere US$ 1,00 = R$ 3,27
'''
r = float(input('Quanto dinheiro você tem na carteira? R$'))
print('Com esse dinheiro, você consegue comprar U${:.2f}'.format(r / 3.27)) |
b5ed2359ff142a0037e666b10ae50dc7cf02b6d4 | NicHagen/project_euler | /prime.py | 1,236 | 4.46875 | 4 | def all_primes(num):
"""function that returns all primes up until num
Args:
num (integer): upper limit of numbers to find primes in
Returns:
list: list containing all the primes from 2 to num
"""
cand_list = list(range(3, num+1))
prime_list = [2,]
for j in prime_list:
for i in cand_list:
if i % j == 0:
cand_list.pop(cand_list.index(i))
if cand_list:
prime_list.append(cand_list[0])
return prime_list
import numpy as np
def eratosthenes(N):
"""eratosthenes sieve for creating prime numbers
Args:
N (integer): the maximum value to create prime numbers within
Returns:
numpy.ndarray: numpy array containing all the prime numbers <= N
"""
eratosthenes = True
# mask for prime numbers
mask = np.ones([N], dtype=bool)
if not eratosthenes:
# simple prime sieve
mask[:2] = False
for j in range(2, int(np.sqrt(N)) + 1):
mask[j*j::j] = False
else:
# Eratosthenes sieve
mask[:2] = False
for j in range(2, int(np.sqrt(N)) + 1):
if mask[j]:
mask[j*j::j] = False
return np.nonzero(mask)[0] |
71c27dd5faddf5262754eea98596b5e103e810e4 | glennneiger/POT1 | /Day1_Formattingoutput.py | 416 | 3.875 | 4 | #Approach 1
name,age,salary = "Rajesh",20,45.67
print(name,age,salary)
#Approach 2
name,age,salary = "Rajesh",20,45.67
print("Name is:",name)
print("Age is:",age)
print("Salary is:",salary)
# Approach 3
name,age,salary = "Rajesh",20,45.67
print("Name: %s Age: %d Salary: %g" % (name,age,salary))
#Approach 4
name,age,salary = "Rajesh",20,45.67
print("Name:{} Age:{} Salary:{}".format(name,age,salary))
|
65eb20dd5ee3289f5e200722232dee6d7409f656 | georgyjose/competitive_coding | /tcsninja/lefttriag.py | 191 | 3.625 | 4 | n = input()
for i in range(n):
for j in range(n):
if j==0 or (i==j and i<=n/2) or (i+j==n-1 and i>=n/2):
print "* ",
else:
print " ",
print "" |
4b314a3f2f88ac485bde911f1b9654a24b7fd95b | SocialFinanceDigitalLabs/AdventOfCode | /solutions/2020/pughmds/day01/Day 1.py | 1,092 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
import itertools
import math
testData = [
1721,
979,
366,
299,
675,
1456
]
def getCombinations(numberList, numberToChoose):
return list(itertools.combinations(numberList, numberToChoose))
def findTarget(numbersToCheck, target):
for group in numbersToCheck:
if sum(group) == target:
return math.prod(group)
return -1
def splitInput(filename):
inputValues = []
with open(filename, 'r') as fileStream:
fileText = fileStream.read()
inputStrings = fileText.split('\n')
inputValues = list(map(int, inputStrings))
return inputValues
resultList = getCombinations(testData,2)
testResult = findTarget(resultList, 2020)
if testResult == 514579:
print("Test passed!")
else:
print("Test failed!")
inputData = splitInput('day1.txt')
print(inputData)
resultList = getCombinations(inputData,2)
testResult = findTarget(resultList, 2020)
print(testResult)
resultList = getCombinations(inputData,3)
testResult = findTarget(resultList, 2020)
print(testResult)
|
fb97ae22a4dc865ef7a0cd3fe379058dad8cafb8 | albul-k/leetcode | /src/easy/min_stack.py | 1,809 | 3.515625 | 4 | """
Url: https://leetcode.com/problems/min-stack/
Author: Konstantin Albul
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
* MinStack() initializes the stack object.
* void push(int val) pushes the element val onto the stack.
* void pop() removes the element on the top of the stack.
* int top() gets the top element of the stack.
* int getMin() retrieves the minimum element in the stack.
Constraints:
* -2^31 <= val <= 2^31 - 1
* Methods pop, top and getMin operations will always be called on non-empty stacks.
* At most 3 * 104 calls will be made to push, pop, top, and getMin.
"""
# pylint: disable=too-few-public-methods
class MinStack:
"""solution
"""
# pylint: disable=no-self-use
def __init__(self):
"""init
"""
self.stack = []
self.min_val = []
def push(self, val: int) -> None:
"""push
Parameters
----------
val : int
value
"""
self.stack.append(val)
if not self.min_val:
val_ = val
else:
val_ = min(val, self.getMin())
self.min_val.append(val_)
def pop(self) -> None:
"""pop
"""
self.stack.pop()
self.min_val.pop()
def top(self) -> int:
"""Get top element of stack
Returns
-------
int
value
"""
return self.stack[-1]
def get_min(self) -> int:
"""Get the minimum element of stack
Returns
-------
int
value
"""
return self.min_val[-1]
if __name__ == "__main__":
obj = MinStack()
obj.push(4)
obj.push(5)
assert obj.top() == 5
obj.pop()
assert obj.get_min() == 4
|
b66937d7de2e352ea6986023eed9fb6dcd5f5173 | majorsortinghat/majorsortinghat.github.io | /data_analysis/DataCalculator.py | 5,794 | 4 | 4 | import json
import math
with open("Major_Mapping_Survey_2.json", "r") as read_file:
data = json.load(read_file)
counter = 0
majors ={}
correctionVar = -3 #Used to normalize from a scale of 1:5 to -2:2. Why -2:2 and not -1:1? Because
def checkTrait(trait):
if trait != 'NumberOfPeople' and trait != "Clubs" and trait != "Major_2" and trait != "Major_1" and trait != 'Graduation' and trait != 'Satisfaction': # Ignore what's not useful/easy
return True
else:
return False
def weightCalc(person):
return (float(
person['Satisfaction']) - 4) / 2; # Weight each answer in accordance to how much they like the major.
def addTraitToMajor():
return
def addCountToMajor(person, major):
if (person[major] == ""):
return
if(str(person[major]) not in majors):
majors[str(person[major])] = {}
majors[str(person[major])]['NumberOfPeople'] = 1
else:
majors[str(person[major])]['NumberOfPeople'] += 1
def iterateThroughData():
for person in data:
continue
def checkifEmptyString(person):
return person[trait] == "" or person[trait] == "N/A"
for person in data:
if str(person['Major_1']) not in majors and person['Major_1'] != 'Undeclared': #If the major isn't already in the dict.
#weight = (float(person['Satisfaction']) - 4) / 2; #Weight each answer in accordance to how much they like the major.
weight = weightCalc(person)
#print (weight)
print()
print(person['Major_1'])
print(person['Major_2'])
print(person['Satisfaction'])
print(person['Like_Parties'])
majors[str(person['Major_1'])] = {}
majors[str(person['Major_1'])]['NumberOfPeople'] = 1
addCountToMajor(person, 'Major_2')
"""if str(person['Major_2']) not in majors and str(person['Major_2']) != "":
majors[str(person['Major_2'])] = {}
majors[str(person['Major_2'])]['NumberOfPeople'] = 1
elif str(person['Major_2']) != "":
majors[str(person['Major_2'])]['NumberOfPeople'] += 1"""
for trait in person:
if checkTrait(trait):
if checkifEmptyString(person):
majors[str(person['Major_1'])][trait] = 0
if str(person['Major_2']) != "":
majors[str(person['Major_2'])][trait] = 0
else:
majors[str(person['Major_1'])][trait] = (float(person[trait])+correctionVar)*weight
if str(person['Major_2']) != "":
majors[str(person['Major_2'])][trait] = (float(person[trait]) + correctionVar) * weight
#print(majors[str(person['Major_1'])])
elif person['Major_1'] != 'Undeclared': #The major is in the dict, so this is where the data is updated
#weight = (float(person['Satisfaction']) - 4) / 2;
weight = weightCalc(person)
majors[str(person['Major_1'])]['NumberOfPeople'] += 1
if str(person['Major_2']) not in majors and str(person['Major_2']) != "":
majors[str(person['Major_2'])] = {}
majors[str(person['Major_2'])]['NumberOfPeople'] = 1
for trait in person:
if checkTrait(trait):
if checkifEmptyString(person):
majors[str(person['Major_2'])][trait] = 0
else:
majors[str(person['Major_2'])][trait] = (float(person[trait]) + correctionVar) * weight
elif str(person['Major_2']) != "":
majors[str(person['Major_2'])]['NumberOfPeople'] += 1
for trait in majors[str(person['Major_1'])].keys():
if checkTrait(trait):
if not checkifEmptyString(person):
majors[str(person['Major_1'])][trait] += (person[trait]+correctionVar)*weight
if str(person['Major_2']) != "":
majors[str(person['Major_2'])][trait] += (person[trait] + correctionVar) * weight
#print('Number of people in '+ str(person['Major_1'])+': ' + str(majors[str(person['Major_1'])]['NumberOfPeople']))
#majors[person['Major_1']]['Satisfaction'] += float(person['Major_1']['Satisfaction'])
for major in majors.keys():
print()
print('Major: ' + major)
for trait in majors[major].keys():
if trait != 'NumberOfPeople':
tempVariance = 0
majors[major][trait] = majors[major][trait]/majors[major]['NumberOfPeople'] #Convert from sum of traits to avarage of traits
for person in data:
if (str(person['Major_1']) == major or str(person['Major_2']) == major) and person['Major_1'] != 'Undeclared' and person[trait] != "" and person[trait] != "N/A": #important to convert Major to string, as some are numbers
weight = (float(person[
'Satisfaction']) - 4) / 2; # Weight each answer in accordance to how much they like the major.
#print("Person trait. "+str(((person[trait])+correctionVar)*weight)+ " Majors Major trait: "+str(majors[major][trait]))
tempVariance += (((person[trait]+correctionVar)*weight-majors[major][trait])**2)
#print(tempVariance)
tempVariance = tempVariance/majors[major]['NumberOfPeople'] #Calculate actual variance from the sum of individual deltas
majors[major][trait] = {"Mean": majors[major][trait], "SD": math.sqrt(tempVariance)}
print(trait + ': ' + str(majors[major][trait]))
#print('The scales go from -3 to 3, with -3 being "hate it" and 3 being "love it".')
with open('outdata.json', 'w') as outfile:
json.dump(majors, outfile, indent=4, sort_keys=True) |
21a558d2e6e6a8dfaae5ee847bce4614d811bdde | elani0/leetcode-python-solutions | /9.py | 875 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 15:42:12 2017
@author: Elani
"""
#9. Palindrome Number
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
else:
l = len(str(x))
print l
for i in xrange(1,l/2+1):
#compare the head and the tail
x1 = x%(10**(l-i+1)) /(10**(l-i))
x2 = x%(10**i) /(10**(i-1))
print x1
print x2
if x1!=x2 :
return False
return True
"""
public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}
""" |
9348026a00ee840962bd157aedcada28c51eaa18 | ayanamizuta/cpro | /atcoder/abc/abc269/c.py | 356 | 3.609375 | 4 | x=int(input())
digits = []
for i in range(61):
if x>>i&1:
digits.append(i)
def make(bits):
ret=0
for i in range(len(digits)):
if bits>>i&1:
ret+=1<<digits[i]
return ret
numbers=[]
bits = 0
while bits<2**len(digits):
numbers.append(make(bits))
bits+=1
numbers.sort()
for n in numbers:
print(n) |
765cc5a2bef5871d729caebe87021d7c26e20920 | svvay/CodeWars | /work_directory/Sort_the_odd.py | 898 | 4.21875 | 4 | # You have an array of numbers.
# Your task is to sort ascending odd numbers but even numbers must be on their places.
#
# Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
arr = [5, 3, 2, 8, 1, 4]
# print(sorted(source_array))
# [1, 3, 5, 11, 2, 8, 4] should equal [1, 3, 2, 8, 5, 4, 11]
# [5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
# def sort_odds(lst):
# sorted_odds = sorted([n for n in lst if n%2])
# print(sorted_odds)
# new_list = []
# for n in lst:
# if n%2:
# new_list.append(sorted_odds.pop(0))
# else:
# new_list.append(n)
# return list(new_list)
# print(sort_odds(source_array))
# CODE WARS
def sort_array(arr):
odds = sorted((x for x in arr if x % 2 != 0), reverse=True)
print(odds)
return [x if x % 2 == 0 else odds.pop() for x in arr]
print(sort_array(arr)) |
fa98af684c3de52d70e1c29c39d8dd6e59f1c363 | Thancoo/proxymask | /find/asy.py | 1,214 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/2 15:59
# @File : asy.py
# @IDE : PyCharm
import asyncio
import time
import datetime
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main(p):
print(p)
print(f'started at {time.strftime("%X")}')
await say_after(1, 'hello')
await say_after(2, 'world')
print(f'finished at {time.strftime("%X")}')
async def main1():
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
print(f'started at {time.strftime("%X")}')
await task1
await task2
print(f'finished at {time.strftime("%X")}')
async def nested(number):
return number
# 协程
async def main2():
a = await nested(45)
print(a)
# 任务
async def main3():
task = asyncio.create_task(nested(68))
a = await task
print(a)
async def display_date():
loop = asyncio.get_running_loop()
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
print(asyncio.iscoroutinefunction(display_date))
|
1b1fcc51bdbea97d4495d24bb6331174e4092646 | Panthck15/learning-python-repo1 | /game1.py | 1,487 | 3.953125 | 4 | class Board():
def __init__(self,board_size):
self.board_size=board_size
self._initialize_board()
def _initialize_board(self):
self.board = [[(i, j) for i in range(self.board_size)]
for j in range(self.board_size)]
def __repr__(self):
"""
Print the board in a pretty format.
"""
# Let's initialize the top row of column numbers first.
board_output = ' ' + ' '.join(str(num) for
num in range(self.board_size)) + '\n'
for row_idx, row in enumerate(self.board):
board_output += ' {} '.format(row_idx)
for col_idx, col in enumerate(row):
if col in [' X ', ' O ']:
if col_idx != self.board_size - 1:
board_output += col + '|'
else:
board_output += col
else:
if col_idx != self.board_size - 1:
board_output += ' ' * 3 + '|'
else:
board_output += ' ' * 3
board_output += '\n'
if row_idx != self.board_size - 1:
board_output += ' ' * 3
board_output += '--' * self.board_size * 2
board_output += '\n'
return board_output
b1=Board(3)
b1.board_size = int(input("What size board would you like to play on today? "))
b1._initialize_board()
print(b1.board) |
d515cd42332decf2b578985be2acf13bcb41ff69 | Pandiarajanpandian/Python---Programming | /Beginner Level/Palindrome.py | 179 | 4 | 4 | x=int(input("enter a number"))
temp=x
reverse=0
while x>0:
remainder=x%10
reverse=(reverse*10)+remainder
x=x//10
if reverse==temp:
print("yes")
else:
print("no")
|
df517faf9ca4c01542c8b250eea58874771c4ef4 | psygo/cryptography_course | /rsa.py | 2,296 | 3.828125 | 4 | import math
import random
def is_prime(p):
for i in range(2, math.isqrt(p)):
if p % i == 0:
return False
return True
def get_prime(size):
while True:
p = random.randrange(size, 2 * size)
if is_prime(p):
return p
def lcm(a, b):
return a * b // math.gcd(a, b)
def get_e(lambda_n):
for e in range(2, lambda_n):
if math.gcd(e, lambda_n) == 1:
return e
return False
def get_d(e, lambda_n):
for d in range(2, lambda_n):
if d * e % lambda_n == 1:
return d
return False
def factor(n):
for p in range(2, n):
if n % p == 0:
return p, n//p
# Key generation done by Alice (secret)
# Step 1: Generate 2 distinct primes
size = 300
p = get_prime(size)
q = get_prime(size)
print("Generated primes", p, q)
# Step 2: Compute n = p * q
n = p * q
print("Modulus n:", n)
# Step 3: Compute lambda(n) = lcm(a, b) = |ab| / gcd(a, b) = lcm(lambda(p), lambda(q))
lambda_n = lcm(p - 1, q - 1)
print("Lambda n", lambda_n)
# Step 4: Choose an integer `e` such that 1 < e < lambda(n) and gcd(e, lambda(n)) = 1
e = get_e(lambda_n)
print("Public exponent", e)
# Step 5: Determine d: solve for d the equation d * e = 1 (mod lambda(n))
d = get_d(e, lambda_n)
print("Secret exponent", d)
# Done with key generation
print("Public key (e, n):", e, n)
print("Secret key (d)", d)
# This is Bob wanting to send a message
m = 117
c = m**e % n
print("Bob sends", c)
# This is Alice decrypting the cipher
m = c**d % n
print("Alice message", m)
# This is Eve
print("Eve sees the following:")
print(" Public key (e, n):", e, n)
print(" Encrypted cipher:", c)
p, q = factor(n)
print("Eve: Factors", p, q)
lambda_n = lcm(p - 1, q - 1)
print("Eve: lambda(n)", lambda_n)
d = get_d(e, lambda_n)
print("Eve: Secret exponent", d)
m = c**d % n
print(" Eve: message", m)
# This is Bob not being careful
print("This is Bob not being careful")
message = "Alice is awesome" # too big to be inside a single message
for m_c in message:
c = ord(m_c)**e % n
print(c, " ", end='')
print()
# Now you can use frequency analysis to break it.
# You need some randomness to make it secure.
# Adding padding helps counteract the deterministic part of RSA (Chosen Plaintext Attack).
|
772943ce9926be98f8703257b506fbda1b69cfbf | nilshah98/College | /Pracs/SEM4/AOA/NQueen.py | 1,938 | 3.578125 | 4 | #N-Queens problem
#checking functionj
def checkIfPoss(x,y,board):
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] and (x==col or y==row or abs(x-col)==abs(y-row)) and not(x==col and y==row):
return False
return True
def NQueens(n):
#mark the regions here
marked = [0 for i in range(n**2)]
#create board here, and initialise all to 0
board = [[0 for _ in range(n)] for _ in range(n)]
#initialise flag, inital row, and solution
row = 0
sol = 1
flag = True
while flag:
#while flag
#initalise col here
col = 0
#check to see, if any one's already in the column, if yes, set col, one next to it
for colx in range(len(board[row])):
if board[row][colx]:
board[row][colx] = 0
col = colx + 1
while col < n:
#mark the visited cell
marked[row*n + col] = 1
#check if current cell is feasible, if yes, mark and break
if checkIfPoss(col,row,board):
board[row][col] = 1
break
col += 1
#condition for breaking, all the cells are marked, ie. last cell to be marked will be marked[0][n-1], since backtracking
#now after last cell is visited, backtrack for it, final condition, last cell of second row
# if row == 1 and col == n and sum(marked)==n**2:
# flag = False
#check if any location found -
#if sum of row is 1, 1 is there init
#else, when first row and col is n
if row == 0 and col == n:
flag = False
if sum(board[row]) == 1:
sumOfboard = 0
for rowx in board:
sumOfboard += sum(rowx)
#if sum of board is euqal to n, there are n queens
if sumOfboard == n:
print("Solution number",sol)
for rowx in board:
print(*rowx)
print()
sol += 1
row += 1
#if row = n reached, decrement it, and find other solutions
if row == n:
row -= 1
#else backtrack
else:
row -= 1
# print(marked)
print("Enter the number of queens")
n = int(input())
NQueens(n) |
331d4172887d876ce0ed0230c485f82620d9bcb6 | LrpljL/leetcodes | /tree/二叉树层次遍历.py | 1,606 | 3.78125 | 4 | # coding = utf-8
"""
递归+迭代
"""
from collections import deque
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def helper(node, level, levels):
if not node:
return levels
# start the current level
if len(levels) == level:
levels.append([])
# append the current node value
levels[level].append(node.val)
# process child nodes for the next level
if node.left:
helper(node.left, level + 1, levels)
if node.right:
helper(node.right, level + 1, levels)
# 使用队列来存储每一层的节点
def levelorder(tree, levels):
"""
:param tree:
:param levels:
:return:
"""
queue = deque([tree])
level = 0
while queue:
level_length = len(queue)
levels.append([])
for i in range(level_length):
node = queue.popleft()
levels[level].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
level += 1
return levels
if __name__ == "__main__":
"""BFS"""
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.left.right.left = Node(6)
tree.right.left = Node(7)
tree.right.left.left = Node(8)
tree.right.left.left.right = Node(9)
# dict1 = {} # 存储每个节点与根节点的距离
levels = []
helper(tree, 0, levels)
print(levels)
# print(levelorder(tree, levels))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.