blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ff3cddcfc9506ed3399d5f8a8e049220718879a6 | HughesZhang73/Python-Master | /Python-Foundation/Python Overview/07 Python 装饰器类应用.py | 505 | 3.984375 | 4 | # coding=utf-8
"""
装饰器:
1.用于拓展原来函数的功能的一种函数
2.返回函数的函数
3.在不使用原来函数的代码的前提下给函数增加新功能
"""
# 定义一个装饰器
from functools import wraps
def eat(cls):
cls.eat = lambda self: print("{0} need eat something".format(self.name))
return cls
@eat
class Cat(object):
def __init__(self, name):
self.name = name
if __name__ == '__main__':
cat = Cat("Katty")
cat.eat()
|
9e741dba9db4c3730ee2df2442185b9d1e35ef5f | pikkaay/leetcode | /src/2_maximal_square.py | 1,870 | 4 | 4 | '''
221. Maximal Square
Average Rating: 4.86 (172 votes)
July 14, 2016 | 199.2K views
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
Summary
We need to find the largest square comprising of all ones in the given m \times nm×n matrix. In other words we need to find the largest set of connected ones in the given matrix that forms a square.
'''
def maximalSquare(matrix):
# handle 0 and 1 dimensional arrays
if len(matrix) == 0: return 0
if len(matrix) == 1:
for i in range(len(matrix[0])):
if matrix[0][i] == '1': return 1
return 0
# input array is not guaranteed to be square. use the smallest side for
# largest possible square
max_side = len(matrix)
if max_side > len(matrix[0]): max_side = len(matrix[0])
# look for largest possible square to smallest
for side in reversed(range(0, max_side)):
for j in range(len(matrix) - side):
for k in range(len(matrix[j]) - side):
#print '(' + str(j) + ', ' + str(k) + ') side: ' + str(side + 1)
if find_square(matrix, j, k, side + 1):
return (side + 1)**2
return 0
# check a region in the vector for the existence of a square made of '1'
def find_square(matrix, x, y, side):
if len(matrix) < 2: return False
if x + side > len(matrix) or y + side > len(matrix[0]): return False
for i in range(x, x + side):
for j in range(y, y + side):
if matrix[i][j] == '0': return False
return True
test = [
"10100",
"10101",
"11101",
"11100",
"11110"
]
# s = Solution()
print ('solution:')
print (maximalSquare(test))
|
08cad54ff604dd63a7db5419e242bf91ae952932 | rccoder/2013code | /Python/practice/乘法口诀/乘法口诀.py | 329 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 18:43:37 2013
@author: yangshangbin
"""
print " Multiplication Table"
for j in range(1,10):
for i in range(1,10):
if i<=j:
print i,"*",j,"=",format(i*j,"2d")," ",
else:
print("\n")
a=eval(raw_input())
|
7513846856bdb052d400d68a69324a2bba3cfde0 | siam1251/algorithms | /interviewbit/sum_tree.py | 670 | 3.875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sum_path(self,A,s_total,B):
if A.left == None and A.right == None:
if s_total+A.val== B:
return 1
else:
return 0
if A.left != None:
if self.sum_path(A.left,s_total+A.val,B) == 1:
return 1
if A.right != None:
if self.sum_path(A.right,s_total+A.val,B) == 1:
return 1
else:
return 0
# @param A : root node of tree
# @param B : integer
# @return an integer
def hasPathSum(self, A, B):
s_total = 0
return self.sum_path(A,s_total,B)
|
bba7c765f9739b3629cf9dedbad399e565488f1c | Aasthaengg/IBMdataset | /Python_codes/p03385/s776904035.py | 58 | 3.640625 | 4 | print("Yes" if sorted(input()) == ['a','b','c'] else 'No') |
76a4fbe20bbc4f26df3a5b4a9f4da8f29e0ed5b2 | yideng333/Code_Interview | /Code_interview/41.py | 1,335 | 3.875 | 4 | '''
数据流中的中位数
'''
import heapq
# 使用两个大小堆实现
def get_midden(array):
min_list = []
max_list = []
i = 0
while i < len(array):
insert(array[i], min_list, max_list)
i += 1
if len(min_list) + len(max_list) & 1 == 1:
midden = min_list[0]
else:
midden = ((max_list[0] * -1) + min_list[0]) / 2
print(max_list)
print(min_list)
print(midden)
return midden
def insert(number, min_list, max_list):
# 总长度为偶数
if len(min_list) + len(max_list) & 1 == 0:
# 如果该数小于最大堆中的最大数,那么需要交换取出最大数
if len(max_list) > 0 and number < max_list[0] * -1:
heapq.heappush(max_list, number * -1)
number = heapq.heappop(max_list) * -1
# 将元素插入最小堆
heapq.heappush(min_list, number)
else:
# 如果该数大于最小堆中的最小数,那么需要交换取出最小数
if len(min_list) > 0 and number > min_list[0]:
heapq.heappush(min_list, number)
number = heapq.heappop(min_list)
# 将元素插入最大堆
heapq.heappush(max_list, number * -1)
if __name__ == '__main__':
test1 = [2,4,2,4,4,2,2,4,4]
test2 = [2,1,3,6,2,5,4,2,8]
get_midden(test2)
|
0685dc5195610af30d9daf2eb4b67f7e88ea0da1 | jhhsu8/coursera-python-intro-interactive-programming | /IIPP-part-one/guess-number-game.py | 1,679 | 4.09375 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random, simplegui, math
# helper function to start and restart the game
def new_game():
global count, secret_number
secret_number = random.randrange(0,100)
#Number of guesses
count = int(math.log(101,2))
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number, count
secret_number = random.randrange(0,100)
#Number of guesses
count = int(math.log(101,2))
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number, count
secret_number = random.randrange(0,1000)
#Number of guesses
count = int(math.log(1001,2))
def input_guess(number):
# main game logic goes here
global count, secret_number
guess = int(number)
print "Guess was " + number
print "Number of remaining guesses: " + str(count)
count -= 1
if count < 0:
print "game over!"
new_game()
count = int(math.log(101,2))
if guess > secret_number:
print "Go lower!"
elif guess < secret_number:
print "Go higher!"
else:
print "Correct!"
new_game()
# create frame
frame = simplegui.create_frame("Set and print colors", 200, 200)
frame.add_button("range(0,100)", range100)
frame.add_button("range(0,1000)", range1000)
frame.add_button("New game", new_game,100)
frame.add_input("Enter guess", input_guess,100)
# call new_game
new_game()
|
1c7beeb1b856052bf12a22248319c0308e070509 | SleepwalkerCh/Leetcode- | /214_2.py | 1,037 | 3.84375 | 4 | #214. Shortest Palindrome
# 每一字节check会超时
# 用数组切片直接比对会加快速度
class Solution:
def shortestPalindrome(self, s: str) -> str:
self.s=s
if len(s)<2:
return s
left=(len(s)-1)/2
while left>=0:
if self.check(round(left-0.6),round(left+0.6)):
return self.make(left)
left-=0.5
def check(self,a,b):
#print(a,b,self.s[:a+1],self.s[a+b+1:b-1:-1])
return self.s[:a+1]==self.s[a+b+1:b-1:-1]
# while a>=0 and b <len(self.s):
# if self.s[a]!=self.s[b]:
# return False
# a-=1
# b+=1
# return True
def make(self,axis):
if axis==(len(self.s)-1)/2:
return self.s
else:
return self.s[:int(axis*2):-1]+self.s
#Runtime: 216 ms, faster than 33.65% of Python3 online submissions for Shortest Palindrome.
#Memory Usage: 13.2 MB, less than 100.00% of Python3 online submissions for Shortest Palindrome. |
70debd09e4920708fa2f1826e0edea31aefd733d | kyle-mccarthy/maze-traversal | /vertex.py | 351 | 3.609375 | 4 | class Vertex:
def __init__(self):
self.row = None
self.col = None
self.adj = [] # for BFS
self.visited = False # for BFS
self.start = False
self.end = False
self.successor = None
self.cost = None
# add an adjacent edge
def add_adjacent(self, v):
self.adj.append(v) |
b56a2872dd51d8241ec4d23accdc9df6cd277ee1 | thar/TuentiChallenge2 | /Reto11/scrab.py | 5,120 | 3.734375 | 4 | #!/usr/bin/python
#########################################################################
# Program will create words for scrabble given letters and words already
# Date Created: 6/15/11
# Date Finished: TBA
# FileName: Scrabble.py
#########################################################################
#Modificado por: Miguel Angel Julian Aguilar
#Ajustado para el Tuenti contest
#e-mail: [email protected]
import itertools
from sets import Set
import sys
getPoints={}
getPoints['a']=1
getPoints['e']=1
getPoints['i']=1
getPoints['l']=1
getPoints['n']=1
getPoints['o']=1
getPoints['r']=1
getPoints['s']=1
getPoints['t']=1
getPoints['u']=1
getPoints['d']=2
getPoints['g']=2
getPoints['b']=3
getPoints['c']=3
getPoints['m']=3
getPoints['p']=3
getPoints['f']=4
getPoints['h']=4
getPoints['v']=4
getPoints['w']=4
getPoints['y']=4
getPoints['k']=5
getPoints['j']=8
getPoints['x']=8
getPoints['q']=10
getPoints['z']=10
def getWordPoints(word):
global getPoints
points=0
for letter in word:
points=points+getPoints[letter.lower()]
return points
#########################################################################
# Class implements program mechanics
# Such as setting up global variables and...
# Handling events and procedures used in the program
#########################################################################
class Program:
# CTOR and Set up values
def __init__(self):
self.words = []
self.letters = []
# Load words in dictionary file
self.maxLength=0
self.dictionaryEntries = Set(x.strip() for x in open('descrambler_wordlist.txt', 'r').readlines())
for w in self.dictionaryEntries: self.maxLength=max(self.maxLength, len(w))
#####################################################################
# FindWords - Find Words give letters user has and...
# Words on the board
# Returns a list of possible words
#####################################################################
def FindWords(self, words, letters):
self.words = words
self.letters = letters
possibleResults = [('',0)]
possibleWords = ['']
letterCombinations = self.Rotate()
combo = ''
# Check if possible to add on word on to existing word
for x in letterCombinations:
# Convert tuple of letters to one continuous string
combo = ''.join(x)
for word in self.words:
# Check if combination can be added on, before...
# Or inbetween
for i in range(len(combo) + 1):
#if combo[:len(combo) - i] + word + combo[len(combo) - i:] in self.dictionaryEntries:
# possibleWords.append(combo[:len(combo) - i] + word + combo[len(combo) - i:])
for letter in word:
newWord=combo[:len(combo) - i] + letter + combo[len(combo) - i:]
if newWord in self.dictionaryEntries and newWord not in possibleWords:
wordPoints=getWordPoints(newWord)
if wordPoints>possibleResults[0][1]:
possibleResults=[(newWord,wordPoints)]
possibleWords=[newWord]
elif wordPoints==possibleResults[0][1]:
possibleResults.append((newWord,wordPoints))
possibleWords.append(newWord)
combo = ''
return possibleResults
#####################################################################
# Rotate - Find different combinations of letters passed in as...
# Member of class
# Returns a list of the letter combinations
#####################################################################
def Rotate(self):
# Contains letter combinations
x = []
# Find all possible letter combinations
for i in range(1, len(self.letters) + 1):
for j in itertools.permutations(self.letters, min(i,self.maxLength)):
x.append(j)
return x
lines=sys.stdin.readlines()
nCases=int(lines.pop(0).strip())
program = Program()
for line in lines:
lineData=line.strip().split()
myletters=list(lineData[0].upper())
deskWords=[lineData[1].upper()]
res=program.FindWords(deskWords, myletters)
res=sorted(res, key=lambda word: (word[0],word[1]))
print '%s %d' % res[0]
|
604a8ed4e3f5e9da7a40255465afbe659bc3b813 | shadunts/data_structures | /max_queue.py | 993 | 4 | 4 | from collections import deque
class MaxQueue:
def __init__(self):
self.__size = 0
self.__data = []
self.__max_values = deque()
def __len__(self):
return self.__size
def enqueue(self, value):
# delete all the items in max_values which are less than the value we add
# as current element will stay in the queue longer
if not self.is_empty():
while self.__max_values and self.__max_values[-1] < value:
self.__max_values.pop()
self.__data.append(value)
self.__max_values.append(value)
self.__size += 1
def dequeue(self):
item = self.__data.pop(0)
if item == self.max():
self.__max_values.popleft()
self.__size -= 1
return item
def first(self):
return self.__data[0]
def is_empty(self):
return self.__size == 0
# front of the deque is max
def max(self):
return self.__max_values[0]
|
a3b1c4a92b5c42a29ce03bf3dc864514c26db250 | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 01/Assignment Set - 04/Assignment on string - Level 1 (puzzle).py | 986 | 4.21875 | 4 | """
Write a python program to display all the common characters between two strings.
Return -1 if there are no matching characters.
Note: Ignore blank spaces if there are any. Perform case sensitive string comparison wherever necessary.
=========================================================
| Sample Input | Expected Output |
=========================================================
| "I like Python" | lieyon |
| "Java is a very popular language" | |
=========================================================
"""
def find_common_characters(msg1, msg2):
common = ''
for char in msg1:
if char in msg2 and char.isalpha() and char not in common:
common += char
if not len(common):
return -1
else:
return common
msg1 = "I like Python"
msg2 = "Java is a very popular language"
common_characters = find_common_characters(msg1, msg2)
print(common_characters)
|
005e83c68dd415df33603b64f826b9b178f73495 | itsmac/1337C0D3_journey | /Average Salary Excluding the Minimum and Maximum Salary.py | 406 | 3.703125 | 4 | '''
No: 1491.
Title: Average Salary Excluding the Minimum and Maximum Salary
'''
class Solution:
def average(self, salary: List[int]) -> float:
val = 0
max_val,min_val = max(salary),min(salary)
for i in salary:
val += i
return (val-max_val-min_val)/(len(salary)-2)
'''
find the max and min
subtract the above val in total and find the mean
'''
|
92fcdeca91eaee9bd82dc56ca775883e1a752c96 | lepisma/audi | /src/custom.py | 2,769 | 3.515625 | 4 | """
Custom cnversion of data to music
"""
import numpy as np
import pyaudio
def modulate(data):
"""
Modulates the data given to be transferred via audi.
Modulation works as described below
- Change each uint8 element (byte) in the given array to
binary representation
- Form a wave byte by binning the 256 levels in 4 (higher might
cause errors at receiving end)
- So, each byte in wave is representing 2 bits of data.
This gives (4 wave bytes) = (1 data byte)
Neglecting the start and stop pattern, this should get to a
speed of :
sample_rate / (1024 * 4) KBps
For (say) 18000Hz, speed = 4.39 KBps
Parameters
----------
data : numpy.ndarray
Data array in numpy.uint8 format
Returns
-------
wave : str
The output in form of pulsating waves represented in a
form to work with pyaudio
"""
wave = ''
levels = ('\x00', '\x55', '\xaa', '\xff')
for frame in data:
next_num = frame
for grp in range(4):
wave += levels[next_num % 4]
next_num /= 4
return wave
def demodulate(wave):
"""
Demodulates the data received from the microphone.
Demodulation works as described below
- Find the range of values
- Scale the values (or don't, since the relative values are
important)
- Construct 2 bits per wave byte using the 4 levels
Doing this on chunks rather than whole will allow the program
to stop the stream after getting the stop pattern.
Parameters
----------
wave : str
Wave from microphone
Returns
-------
levels : numpy.ndarray
Levels output from the wave
"""
levels = np.frombuffer(wave, np.uint8)
levels = np.array(levels, dtype = np.float16)
max_data = np.max(levels) # Assuming it contains real '\xff'
# Leveling data
bins = np.linspace(0, max_data, 5)
levels= np.digitize(levels, bins) - 1
levels[levels == 4] = 3 # Resolving edge issue
return levels
def levels_to_data(levels):
"""
Converts the levels from demodulation to data array
Parameters
----------
levels : numpy.ndarray
Contains converted form of wave in 4 levels
Returns
-------
data : numpy.ndarray
The data array in uint8 form
"""
b4_conv_fact = [1, 4, 16, 64]
levels = levels.reshape(levels.size / 4, 4)
data = np.array(np.dot(levels, b4_conv_fact), dtype = np.uint8)
return data
def add_trails(wave):
"""
Adds start and stop pattern to the given wave
Adding 'audi' on both sides
"""
text = 'audi'
as_int = map(ord, text)
as_wave = modulate(as_int)
return as_wave + wave + as_wave
|
491d6840ca782a721308df26d9bf22438d3f0b24 | George-lewis/Golf | /py/fact.py | 560 | 3.59375 | 4 | #
# For comparing the speed of a regular recursive factorial to a cached recursive factorial
#
import time, sys
sys.setrecursionlimit(10**6)
cache = { 0 : 1, 1 : 1 }
# cached
def cfact(n):
if n in cache:
return cache[n]
res = n*fact(n-1)
cache[n] = res
return res
# regular
def fact(n):
if n <= 1:
return 1
return n * fact(n-1)
def test(f, n = 1000):
t = time.time()
for i in range(n):
f(i)
print(f"Time elapsed: {time.time() - t}")
test(fact)
test(fact)
test(cfact)
test(cfact)
test(cfact, 10000) |
40377317b5c1c8e707f186b07e9c79c6f4b40696 | fengor/adventofcode | /2015/d5c1.py | 538 | 3.65625 | 4 | with open('d5_input.txt') as f:
strings = f.readlines()
forbidden = ('ab', 'cd', 'pq', 'xy')
vowels = 'aeiou'
nice_strings = 0
for string in strings:
vowel_count = 0
double = False
nice = True
for bad in forbidden:
if bad in string:
nice = False
if not nice:
continue
for i, char in enumerate(string):
if char in vowels:
vowel_count += 1
if char == string[i-1]: # assume \n as last char
double = True
if vowel_count < 3 or not double:
nice = False
if nice:
nice_strings += 1
print(nice_strings)
|
8a4ae3b87c5cf4eacbef91bda3279275280b6d06 | Prashant-Bharaj/A-December-of-Algorithms | /December-09/python_Raahul46_IS_THIS_URL.py | 409 | 4.15625 | 4 | #!python3
"""
Hi there.
This file doesn't contain any code.
It's just here to give an example of the file naming scheme.
Cheers!
"""
import validators
def isurl(link):
value=validators.url(link)
if(value==True):
print("It is a URL")
else:
print("It is not a URL")
def main():
string=str(input("ENTER THE URL TO CHECK:"))
isurl(string)
if __name__ == '__main__':
main()
|
64e3d67b68202a779c65588a88c691c3c36f2afe | MisterKitty1210/Choose-Your-Own-Adventure-Per-3 | /Choose Your Own Adventure Per 3.py | 51,706 | 3.640625 | 4 | import time
import random
import sys
def type(text):
wait = 0
for c in text:
sys.stdout.write(c)
time.sleep(random.randrange(5, 10)/500.0)
def main():
type("The Tale of Gladion Knit3blad3: A Choose Your Own Adventure!\n"
"By Nicholas Eng, Period 3"
"(You'll never beat this game. It makes no sense.)\n")
type("\nIt is a dark and stormy night. Thunder clashes in the distance, awakening you.\n"
"You clamber to you feet, noticing that you are drenched in rain.\n"
"Around you, a supernatural storm is destroying the city. What could be causing it?\n"
"Across the street, you can see a burning streetlamp, despite the rain.\n"
"The building next to you creaks with uncertainty as it is buffered by the wind.\n")
type("1. Cross the street and investigate.\n")
type("2. Wait and regain you senses.\n")
type("3. Back away slowly.\n")
choice = input("Make your choice: ")
if choice == 1:
lamp()
elif choice == 2:
wait()
else:
back_away()
def fight():
type("\nYou draw you blade and leap backwards, just in time to dodge the demon's blade.\n"
"You can hear the blade slice through the air in the place you were standing moments ago.\n"
"You regain your bearings and look up.\n"
"Enraged, the demon charges at you.\n")
type("1. Dodge to the side.\n")
type("2. Roll behind it.\n")
type("3. PANIC!!!\n")
choice = input("What will you do?")
if choice == 3:
charge()
else:
backslash()
def backslash():
type("\nYou dodge just in time.\n"
"The demon barrels past you, and you have time to counter attack.\n"
"You leap through the air with your runeblade raised above your head. \n"
"You exclaim 'BACK SLASH!!!' as you slice the demon's back open.\n"
"Screaming in agony, the demon collapses to the ground. \n"
"It roars 'KnIT3blAD3! I WiLL RETurN!'\n"
"The demon opens a portal to the nether.\n"
"Before it leaves, it shouts 'MaSTEr WarLOck GRaY WIlL HaVE HiS ReVEngE!\n"
"It dissolves into the nether."
"'That was close.' You think.\n"
"'Master Warlock Gray', you think,'Who could that be? It seems that he is behind the city's destruction.'\n"
"It doesn't matter right now. You have limited time before the portal closes.\n")
type("1. Go to the weapon shop to get better gear.\n")
type("2. Dig up information on Master Warlock Gray.\n")
type("3. Go home and sleep so you are ready for action.\n")
type("4. Brave the nether now in case the portal closes.\n")
choice = input("What should I do now? I only have enough time for one action.")
if choice == 1:
weapon()
elif choice == 2:
information()
elif choice == 3:
sleep()
else:
deathportal1()
def deathportal1():
type("\nYou step into the portal, transporting you to the nether. Darkness surrounds you. \n"
"You hear a screeching behind you. You turn around to see an army of imps.\n"
"You try to fight them off, but your sword breaks.\n"
"YOU DIED. GAME OVER.\n"
"If only you had a better weapon...")
def weapon():
type("\n'I need a better weapon' you think as you get into your car. \n"
"Luckily, I know a guy.\n"
"You pull into the parking lot of Gary's Weapon Shop: 'Monstah Huntering Suppliez and Geer'.\n"
"As you get out of the car, the shop explodes into an ethereal flame.\n"
"You hear a maniacal laughter coming from the flames. Spooky.\n"
"Nobody could have survived that. But what if he did...\n")
type("1. Try to save Gary from the ethereal flames.\n")
type("2. Back to the portal.\n")
choice = input("Should I go in after him?...")
if choice == 1:
flames()
else:
deathportal1()
def flames():
type("\nIn an attempt to save Gary the shopkeeper, you charge into the blaze.\n"
"As you approach, you are consumed by flames.\n"
"You burn to death.\n"
"YOU DIED. GAME OVER.\n"
"'Some people just want to watch the world burn...'")
def information():
type("\nYou decide to dig up some information on Master Warlock Gray.\n"
"You head to a dark alley and meet with the crime boss known as 'TYPH00N'.\n"
"He is notorious as a legendary gambler and a card shark. Despite his reputation, he is only 16 years old.\n"
"'TYPH00N - I've come to bargain' you proclaim.\n"
"'What is your name?' He replies.\n"
"'It's Gladion Knit3blad3.'\n"
"'What a wacky name. Is it spelled 'N-I-G-H-T-B-L-A-D-E?' He inquires.\n"
"'It's spelled 'K-N-I-T-3-B-L-A-D-3', and it's way better than yours. Why does it have zeroes in it?'\n"
"'I'm an edgy teen, so I get to be different.' He retorts 'You don't have a reason.'\n"
"Dismissing his rudeness, you get down to business.\n"
"After hearing what happened, he agrees to help, but under one condition.\n"
"'I'll help you out, but only if you can beat me in a children's card game.'\n"
"'WHAT?!?', you exclaim, 'That's the most ridiculous thing I've ever heard.'\n"
"He replies:'It can't be more ridiculous than this game. It makes no sense...'\n"
"'Did you just break the fourth wall? You can't do that!'\n"
"'I believe I just did', he replies, 'Now do we have a deal or not?'\n"
"'Fine' you reply."
"You agree, and he gives you the choice between two decks.\n")
type("1. Take 'DINOPOWER'-the dinosaur themed deck.\n")
type("2. Take 'VERSUS ZOMBIES'- the plant themes deck.\n")
choice = input("Which deck do you want?")
if choice == 1:
dinopower()
else:
pvz()
def dinopower():
type("\nYou pick the deck 'DINOPOWER'.\n"
"You play his game, and easily win. \n"
"Your deck had some of the most powerful cards in the game.\n"
"You exclaim 'GET TYRANNOSAURUS REKT!'. He replies 'You only won because I got terrible RNG...'\n"
"'Fine', he says, 'I'll uphold my end of the bargain...'\n"
"This land is dangerous. It's full of spelling errors and plot holes.\n"
"To get through it, you'll need this spell.\n"
"'Master Warlock Gray's minions can't stand water. \n"
"TYPH00N gives you a water incantation to flood the nether.\n"
"Gray himself is immune to water based attacks: he's a master of scuba diving as well...\n"
"You think that you can hit the weapons shop on the way back.\n")
type("1. Head to Gary's Weapon Shop: 'Monstah Huntering Suppliez and Geer'.\n")
type("2. Head back to the portal.\n")
choice = input("What should I do now?")
if choice == 1:
weapon2()
else:
safeportal()
def safeportal():
type("\nYou decide to hurry back to the portal before it closes.\n"
"On the way, you drive by Gary's Weapon Shop: 'Monstah Huntering Suppliez and Geer'.\n"
"Out of the corner of your eye, you see the shop combust into an ethereal flame.\n"
"You hear a maniacal laughter coming from the flames. Spooky.\n"
"You decide to leave it, but call 911 on the way.\n\n"
"You arrive at the portal.\n"
"Before entering, you recite the water incantation TYPH00N gave you.\n"
"The portal floods. You can hear souls howling in agony from inside.\n"
"After a few minutes, you step into the inky void.\n"
"Afer your eyes adjust, you can look round you."
"You can see the bodies of hundreds, maybe thousands of imps, dissolving in water.\n"
"You walk for a bit, until you see a creepy man next to a rowboat. He seems really shady...\n"
"He offers to take you across this river.\n")
type("1. Accept his guidance.\n")
type("2. Steal his boat.\n")
type("3. Decline his offer.\n")
choice = input("What should I do now?")
if choice == 1:
guidance()
elif choice == 2:
steal()
else:
decline()
def guidance():
type("\nYou choose to accept the creepy man's guidance.\n"
"He takes you across the rapids. When you get off of the boat, \n"
"it vaporizes into thin air along with the man.\n"
"Was he a ghost? A spirit?\n"
"You ignore it and move on.\n"
"You walk for a while, until you see an ominous castle in the distance.\n"
"On the gates, there is large golden lettering spelling out 'MWG'."
"The castle probably belongs to Master Warlock Gray.\n"
"It seems to be guarded by a giant anaconda.\n"
"It looks like it's as large as three train cars linked together.\n")
type("1. Approach the castle head on.\n")
type("2. Sneak into the castle.\n")
type("3. Go around back.\n")
choice = input("What is the smartest approach?")
if choice == 1:
entercastle()
elif choice == 2:
sneak()
else:
back()
def entercastle():
type("\nYou decide to approach the castle head on.\n"
"You wait until the snake slithers behind the castle before approaching.\n"
"You enter the castle. The walls are lined with ancient artifacts on display.\n"
"Everything is coated with a thick layer of dust.\n"
"You notice that there is no dust on the carpets stretching through the castle.\n"
"You find a treasure chest. Inside it, you find a magical suit of armor.\n"
"It is called 'The Plot Armor'. It protects you from the terrible writing.\n"
"You reach two staircases.\n"
"One leads up to the spire, another to the basement.\n")
type("1. Head up to the spire.\n")
type("2. Head down to the basement.\n")
type("3. Ignore the stairs and continue onward.\n")
choice = input("What should I do now?")
if choice == 1:
spire()
elif choice == 2:
basement()
else:
onward()
def actualonward():
type("You make your way back to the middle room.\n"
"On the door, there are two glowing symbols.\n"
"The door slides open.\n"
"You walk through the doorway.\n"
"You find a light shield in the next room.\n"
"You enter the next room.\n")
icedemon()
def icedemon():
type("The room is dark.\n"
"Suddenly, torches light up the room.\n"
"In front of you stands a hooded figure.\n"
"He mutters 'Heh, Nothing personnel kid' and teleports away.\n"
"The door slams closed behind you.\n"
"In the center of the room, a portal opens on the ceiling.\n"
"A demon drops out of it. The portal closes.\n"
"The demon glows blue, and becomes enclosed in ice.\n"
"The temperature of the room drops to freezing. Puddles of water freeze and become ice.\n"
"For some reason, it starts snowing inside.\n"
"Some metal chunks of the ceiling collapse to the ground.\n"
"The demon forms a sword and shield out of ice.\n"
"It charges toward you at lightning speed...\n")
type("1. Raise your shield.\n")
type("2. Attack with your sword.\n")
type("3. Use water magic.\n")
type("4. Use your bow.\n")
type("5. Use your ice rod.\n")
type("6. Take time to survey the room.\n")
choice = input("What should I do?")
if choice == 1:
shield()
elif choice == 2:
sword()
elif choice == 3:
magic()
elif choice == 4:
bow()
elif choice == 5:
shieldrod()
else:
survey()
def survey():
type("\nBefore charging into battle, you look around the room.\n"
"You see a chain partially hidden under a pile of snow.\n"
"There are torches in the corners of the room, but they are out of reach.\n"
"The floor is slippery and covered with ice. It would not be safe to run in here.\n"
"There are mounds of snow on either side of you.\n"
"You need to act before the demon reaches you...\n")
type("1. Raise your shield.\n")
type("2. Attack with your sword.\n")
type("3. Use water magic.\n")
type("4. Use your bow.\n")
type("5. Use your ice rod.\n")
type("6. Roll forward.\n")
type("7. Roll backwards.\n")
type("8. Dodge to the side.\n")
choice = input("What should I do?\n")
if choice == 1:
shield()
elif choice == 2:
sword()
elif choice == 3:
magic()
elif choice == 4:
bow()
elif choice == 5:
shieldrod()
elif choice == 6:
rf()
elif choice == 7:
rb()
else:
ds()
def rf():
type("\nYou roll forward, past the demon.\n"
"It roars past you, and crashes into the door.\n"
"The demon is stunned.\n"
"Now's your chance!\n")
type("1. Attack while it is stunned.\n")
type("2. Investigate the chain.\n")
type("3. Find another way.\n")
choice = input("What do I do?")
if choice == 1:
stunnedsword()
elif choice == 2:
ballandchain()
else:
way()
def way():
type("'There must be some other way...' you think.\n"
"You don't come up with any ideas.\n"
"The demon reaches you and freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def ballandchain():
type("\nYou dig through the pile of snow.\n"
"On the other end of the chain, there is a metal ball attached.\n"
"You swing the ball around you to build up momentum.\n"
"You release it, and it flies at the demon.\n"
"The impact shatters its icy weapons and armor.\n"
"The demon turns from blue to pale.\n"
"You run up and stab it with your sword.\n"
"The demon cries in anguish.\n"
"It explodes into a puff of purple smoke.\n"
"The doors open.")
finalhallway()
def finalhallway():
type("\nThe next room is a hallway.\n"
"You take your time walking through it, preparing for what could be the final battle.\n"
"At the end of the hall, there is a grand door.\n"
"You push it open.")
masterwarlockgray()
def masterwarlockgray():
type("\nThe hooded figure from before is sitting alone, staring into a fireplace.\n"
"'Gladion Knit3blad3' he says, 'I've been expecting you.'\n"
"'You've been waiting here in this room for me?!? What if I never came here?!?\n"
"What if I died in the castle?!? That's the worst plan I've ever heard!' you exclaim.\n"
"'Ignore that obvious plot hole' he replies.\n"
"He continues:\n"
"'I will now tell you my overly complicated and irrelevant back story \n"
"that will not affect the plot in any way...\n\n"
"It all started when I was a child. My family always took me scuba diving during the summer.\n"
"I became an expert at scuba diving. I even started to go spear fishing with a harpoon gun.\n"
"One day, I was out scuba diving, and my parents died.'\n"
"You interrupt: 'Well how did they die-'\n"
"'NO INTERRUPTING!' he screams.\n"
"Anyways, a mysterious voice contacted me and told me that my parents could be revived.\n"
"In return, I would have to sacrifice my soul.\n"
"To perform the ritual of soul sacrificing, I would have to become stronger.\n"
"I went on a soul searching journey after that, travelled the world.\n"
"I learned karakungjutotejitsu from some monks living in the mountains of Tibet.\n"
"I went on a quest to slay a rainbow yeti with wings that was terrorizing the people of my imagination.\n"
"I braved the rivers of the Amazon, discovered Atlantis, and travelled to other galaxies... \n"
"all in order to exact my revenge.'\n"
"He pauses to take a sip of tea.\n"
"'Atlantis doesn't exist, and travel between galaxies isn't possible yet.' You interject.\n"
"'Also, who is your revenge toward?'\n"
"Gray spits out his tea. 'I SAID NO INTERRUPTING!'\n"
"He stands up from his chair, still facing the fire.\n"
"He whirls around and pulls down his hood.\n"
"In front of you stands a shadowy effigy of Gary, the shopkeeper.\n"
"You reel in surprise.\n"
"'Gary?!? You died in an explosion!'\n"
"'That's what you thought...\n"
"You see, after my journey around the world, I settled down to become a shopkeeper.\n"
"But that was just a part of my plan...\n"
"In order to perform the ritual, I had to collect large amounts of cash.\n"
"I profited from the shop, and gained the necessary funds.\n"
"The voice told me to leave the money in a dumpster in a shady alleyway.\n"
"In return, my parents would be revived.\n"
"I did as he asked.\n"
"He took my soul as promised and gave me this castle. I also got magical powers.\n"
"That was what happened when my shop exploded.\n"
"From that point on, I fully adopted my ego known as Gray.\n"
"Alas...\n"
"He never revived my parents. \n"
"All I know is that he is somewhere in the city, and that's why I have to destroy it!\n"
"You summarize 'So you got conned by a magical scammer and now want to destroy the city?'\n"
"'Yes. Why?'\n"
"'This still makes no sense. The shop exploded after you sent a demon after me.\n"
"Also, why were you expecting me? This is the most ridiculous story I've ever heard.\n"
"'You're the main character, so I blamed you. That's why the demon attacked you.\n"
"It was all in order to get my vaguely defined revenge. MWAHAHAHAHAHA!'\n"
"'Wait. If you suspected me, why did you attack the city?\n"
"It seems like you made this story up five minutes ago...'\n"
"'I told you to ignore all these plot holes.\n"
"Enough talk... Let us do battle!'\n")
garybattle()
def garybattle():
type("You draw you sword.\n"
"As long as you believe in the power of friendship, \n"
"your main character powers will prevail.\n"
"Gary holds one hand behind his back.\n"
"He holds the other in front of him.\n"
"'I'M GoNNa BlOCk YouR AttaCKS' he says.\n"
"His voice seems different than before.\n"
"He talks in a strange, almost demonic tone.\n")
type("1. Stab him.\n")
type("2. Slash at him.\n")
type("3. Have mercy.\n")
choice = input("What should I do?")
if choice == 1:
stab()
elif choice == 2:
slash()
else:
mercy()
def stab():
type("\nYou thrust your sword at him.\n"
"He tries to catch it, but is too slow.\n"
"The sword is stuck in his chest.\n"
"ThAT WaS A CheaP MoVE!!!\n"
"YoU'Ll PAy fOR ThAt!!!\n"
"He leaps backwards, onto the mantle.\n"
"He pulls out a harpoon gun and aims it at you.\n"
"'HeYYY hEyyyYY, TiEmE ToO DIEIEE' He shrieks.\n")
type("1. Prepare to die.\n")
type("2. Get to cover.\n")
type("3. Prepare to dodge.\n")
choice = input("Is this the end?")
if choice == 1:
panic2()
elif choice == 2:
cover()
else:
nicedodge()
def panic2():
type("\nYou panic, seeing your life flash before your eyes.\n"
"You hear the gun go off.\n"
"Nothing happens.\n"
"You look up to see Gary with the harpoon through him.\n"
"'CURse YoU...\n"
"ThE Gun WAs BaCKwARdS...'\n"
"It seems that Gary has accidentally shot himself with the gun.\n"
"He apparently was holding it backwards.\n"
"As Gary dies, he whispers his last words to you:\n"
"'THe OnlY THIng DarKEr ThaN BlacK iS GRAY...'\n\n"
"Master Warlock Gray was defeated.\n"
"The city had been saved from his vague and generic plan.\n"
"You didn't really do anything because he shot himself.\n"
"All of your efforts were for nothing.\n"
"\nYOU WIN.\n"
"Congratulations!")
def cover():
type("\nYou dash behind the chair, hoping to get to cover.\n"
"You hear the gun go off.\n"
"Nothing happens.\n"
"You look up to see Gary with the harpoon through him.\n"
"'CURse YoU...\n"
"ThE Gun WAs BaCKwARdS...'\n"
"It seems that Gary has accidentally shot himself with the gun.\n"
"He apparently was holding it backwards.\n"
"As Gary dies, he whispers his last words to you:\n"
"'THe OnlY THIng DarKEr ThaN BlacK iS GRAY...'\n\n"
"Master Warlock Gray was defeated.\n"
"The city had been saved from his vague and generic plan.\n"
"You didn't really do anything because he shot himself.\n"
"All of your efforts were for nothing.\n"
"\nYOU WIN.\n"
"Congratulations!")
def nicedodge():
type("\nYou prepare yourself to dodge the harpoon.\n"
"It's a gutsy move, but you don't have many options...\n"
"You hear the gun go off.\n"
"Nothing happens.\n"
"You look up to see Gary with the harpoon through him.\n"
"'CURse YoU...\n"
"ThE Gun WAs BaCKwARdS...'\n"
"It seems that Gary has accidentally shot himself with the gun.\n"
"He apparently was holding it backwards.\n"
"As Gary dies, he whispers his last words to you:\n"
"'THe OnlY THIng DarKEr ThaN BlacK iS GRAY...'\n\n"
"Master Warlock Gray was defeated.\n"
"The city had been saved from his vague and generic plan.\n"
"You didn't really do anything because he shot himself.\n"
"All of your efforts were for nothing.\n"
"\nYOU WIN.\n"
"Congratulations!")
def slash():
type("\nYou slash at him.\n"
"To your surprise, he catches the blade.\n"
"You wonder how he caught the sword without slicing his hand.\n"
"He wrestles the sword from your hand and stabs you with it.\n"
"YOU DIED. GAME OVER.\n"
"'Nothing personnel kid.'")
def mercy():
type("\nYou sheath your sword.\n"
"'We can find another way.' you say.\n"
"'ThE OnlY wAY iS My Way!!!' he screeches.\n"
"Gary teleports away.\n"
"You look around you but don't see where he went.\n"
"He appears behind you and stabs you with a katana.\n"
"As you fall to the ground, you hear him whisper:\n"
"'NoTHiNG PErSoNNEl KiD.'\n"
"YOU DIED. GAME OVER.\n"
"You came so far...")
def stunnedsword():
type("You run up behind it and slash with your sword.\n"
"Your arm becomes frozen from the subzero temperatures.\n"
"The demon attacks you and freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def rb():
type("You roll backwards.\n"
"You forgot about the door behind you and roll into it.\n"
"The demon catches you and freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def ds():
type("In the nick of time, you dodge to the side.\n"
"If you read the paragraph before, you would have known about the piles of snow near you.\n"
"You get stuck in the mound of snow.\n"
"The demon catches you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
# bow
def bow():
type("\nYou pull out your bow.\n"
"While strafing around the demon, you fire an arrow.\n"
"It bounces off of the demon's ice shield.\n"
"While you recover, it runs over and slashes at you with its ice sword.\n"
"You dodge, and pull out:\n")
type("1. Your sword.\n")
type("2. Your shield.\n")
type("3. Your ice rod.\n")
type("4. Your water spell.\n")
choice = input("What item do I use?")
if choice == 1:
sword()
elif choice == 2:
shield()
elif choice == 3:
shieldrod()
elif choice == 4:
magic()
# swordseries
def sword():
type("\nYou swing your sword at the demon, but miss.\n"
"You raise your sword to block an attack.\n"
"The sword along with your arm becomes frozen.\n"
"The freeze stops you from using some weapons.\n")
type("1. Raise your shield.\n")
type("2. Use water magic.\n")
type("3. Use ice rod.\n")
choice = input("What do I do?")
if choice == 1:
swordshield()
elif choice == 2:
magic()
else:
shieldrod()
def swordshield():
type("\nYou raise your shield to block the demon's attack.\n"
"It slashes at you with its sword, but is blocked by your shield.\n"
"Your other arm and shield become frozen from the contact.\n"
"You are defenseless. The demon freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
# shieldseries
def shield():
type("\nYou raise your shield to block the demon's attack.\n"
"It slashes at you with its sword, but is blocked by your shield.\n"
"Your arm becomes frozen from contact.\n"
"The freeze stops you from using some weapons.\n"
"The shield is frozen as well.\n")
type("1. Use sword.\n")
type("2. Use ice rod.\n")
type("3. Use water magic.\n")
choice = input("What now?")
if choice == 1:
shieldsword()
elif choice == 2:
shieldrod()
else:
magic()
def shieldsword():
type("\nYou swing your sword at the demon, but miss.\n"
"You raise your sword to block an attack.\n"
"The sword along with your other arm becomes frozen.\n"
"You are defenseless. The demon freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def shieldrod():
type("\nYou use the ice rod on the demon.\n"
"Your ice based attack did nothing against the ice elemental.\n"
"You jump out of the way to dodge one of its attacks, but drop your sword, shield, and bow.\n"
"It approaches.")
type("1. Go for your lost items.\n")
type("2. Use water magic.\n")
choice = input("What now?")
if choice == 1:
gonow()
else:
magic()
def gonow():
type("\nYou decide to try to get your items back.\n"
"You start running across the room, but slip and fall.\n"
"The demon catches you and freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def magic():
type("\nYou use the water spell.\n"
"It sends a geyser of water spiraling towards the demon.\n"
"The water freezes before it reaches the demon.\n"
"It catches you and freezes you.\n"
"YOU DIED. GAME OVER.\n"
"What a COOL boss.")
def onward():
type("\nYou keep going until you reach a locked door.\n"
"Next to the door, there is a plaque.\n"
"It says 'Conquer the beasts above and below;\n"
"only then with the true path show'.\n"
"You decide to come back later.\n")
type("1. Go up to the spire.\n")
type("2. Go down to the basement.\n")
choice = input("Now what?")
if choice == 1:
spire()
else:
basement()
# spire series
def spire():
type("\nYou climb the spire until you reach the top.\n"
"You reach the roof.\n"
"As you climb up, the door slams closed behind you.\n"
"There is a harsh downpour. Lightning strikes in the distance.\n"
"Suddenly, a strong wind starts blowing against the tower.\n"
"You turn around to where the wind is coming from.\n"
"A giant dragon flaps it's wings, hovering in place.\n"
"'This is the obligatory dragon boss' you think.\n"
"You find an old bow on the ground. There are no arrows around.\n"
"It is also too windy to aim properly.\n"
"The dragon draws near.\n")
type("1. Use the water spell to fight it.\n")
type("2. Use your sword.\n")
type("3. Jump off of the spire.\n")
choice = input("What should I do?")
if choice == 3:
jump()
else:
dragonkills()
def jump():
type("\nYou jump off of the roof, narrowly avoiding the dragon's flames.\n"
"You cast the water spell in a downward direction, slowing your fall.\n"
"You smash through the roof of a lower level.\n"
"Your plot armor protects you from major injuries from the fall.\n"
"After a while, you recover.\n"
"It was a risky gamble, but it payed off.\n"
"You keep going until you reach a locked door.\n"
"Next to the door, there is a plaque.\n"
"It says 'Conquer the beasts above and below;\n"
"only then with the true path show'.\n"
"You find some arrows in the room.\n"
"You decide to come back later.\n"
"You decide to go to the last unexplored room, the basement.")
basement2()
def basement2():
type("\nYou decide to head down to the basement.\n"
"It's less of a basement and more of a dungeon.\n"
"The floors are grates that are suspended over lava.\n"
"You walk into a room.\n"
"Suddenly, the door closes behind you!\n"
"In the room, you find a magical ice rod.\n"
"It won't work in here, the lava is too hot.\n"
"The room begins to shake, bits of stone fall from the ceiling.\n"
"The lava under you is bubbling.\n"
"A giant hand smashes up through the grate from the lava.\n"
"The hand is made entirely of bone.\n"
"Another hand does the same.\n"
"The skeletal beast pulls itself out of the lava.\n"
"The colossus peers down at you with a single giant eye.\n"
"It roars with rage.\n"
"It raises a single hand above its head, then starts to bring it down towards you.\n")
type("1. Hit it with water magic.\n")
type("2. Dodge to the side.\n")
type("3. Attack with your sword.\n")
type("4. Shoot its eye with your bow.\n")
choice = input("What should I do?")
if choice == 2:
skeleescape()
elif choice == 4:
skelekilled()
else:
skelekills()
def skelekilled():
type("\nYou fire an arrow into its eye.\n"
"The colossus roars in pain and collapses to the ground.\n"
"You run over to it and begin to stab its eye with your sword.\n"
"The eye explodes in a puff of dark smoke.\n"
"The remains of the skeleton slide back into the lava.\n"
"The door behind you opens.\n")
type("1. Head back to the middle room.\n")
type("2. Head up to the spire.\n")
choice = input("What now?")
if choice == 1:
onwardskele()
else:
spire2()
def onwardskele():
type("\nYou head back to the corridor from before.\n"
"On the door, a symbol resembling a skull is glowing.\n"
"The plaque still reads the same thing.\n"
"You decide to head up to the spire.\n")
spire2()
def spire2():
type("\nYou climb the spire until you reach the top.\n"
"You reach the roof.\n"
"As you climb up, the door slams closed behind you.\n"
"There is a harsh downpour. Lightning strikes in the distance.\n"
"Suddenly, a strong wind starts blowing against the tower.\n"
"You turn around to where the wind is coming from.\n"
"A giant dragon flaps it's wings, hovering in place.\n"
"'This is the obligatory dragon boss' you think.\n")
type("1. Use the water spell to fight it.\n")
type("2. Use your sword.\n")
type("3. Jump off of the spire.\n")
type("4. Use the freezing rod.\n")
choice = input("What should I do?")
if choice == 3:
jump2()
elif choice == 4:
freeze()
else:
dragonkills()
def freeze():
type("\nYou point your freezing rod toward the skies.\n"
"It shoots a beam of magic into the clouds above.\n"
"The clouds freeze and fall out of the sky.\n"
"The dragon is pinned to the tower under their weight.\n"
"While it is trapped, you run over and slash it with your sword.\n"
"The beast lets out a final anguished wail and collapses to the floor.\n"
"It explodes in a puff of dark smoke.\n"
"The door opens behind you.\n"
"You decide to head back to the center room.\n")
actualonward()
def jump2():
type("\nYou decide to jump off of the roof again.\n"
"This time, you weren't so lucky.\n"
"You slip as you run to the edge, and drop your gear.\n"
"With nothing to slow your fall, you fall into the castle.\n"
"Your plot armor wasn't strong enough to save you from the fall.\n"
"YOU DIED. GAME OVER.\n"
"What a stupid plan.")
def dragonkills():
type("\nYou raise your weapon to attack.\n"
"The dragon is faster. It melts you with it's fire breath.\n"
"YOU DIED. GAME OVER.\n"
"Heh, this guys toast.")
# basement series
def basement():
type("\nYou decide to head down to the basement.\n"
"It's less of a basement and more of a dungeon.\n"
"The floors are grates that are suspended over lava.\n"
"You walk into a room.\n"
"Suddenly, the door closes behind you!\n"
"In the room, you find a magical ice rod.\n"
"It won't work in here, the lava is too hot.\n"
"The room begins to shake, bits of stone fall from the ceiling.\n"
"The lava under you is bubbling.\n"
"A giant hand smashes through the grate from the lava.\n"
"The hand is made entirely of bone.\n"
"Another hand does the same.\n"
"The skeletal beast pulls itself out of the lava.\n"
"The colossus peers down at you with a single giant eye.\n"
"It roars with rage.\n"
"It raises a single hand above its head, then starts to bring it down towards you.\n")
type("1. Hit it with water magic.\n")
type("2. Dodge to the side.\n")
type("3. Attack with your sword.\n")
choice = input("What should I do?")
if choice == 2:
skeleescape()
else:
skelekills()
def skeleescape():
type("\nThe skeleton launches its fist at you.\n"
"You tumble to the side, evading the attack.\n"
"The fist breaks through the wall.\n"
"You run through the hole in the wall and escape the beast.\n"
"You keep going until you reach a locked door.\n"
"Next to the door, there is a plaque.\n"
"It says 'Conquer the beasts above and below;\n"
"only then with the true path show'.\n"
"You find some arrows in the room.\n"
"You decide to come back later.\n")
type("1. Go up to the spire.\n")
type("2. Go down to the basement.\n")
choice = input("Where should I go?")
if choice == 1:
spire3()
else:
nobasement()
def nobasement():
type("\nYou were just at the basement.\n"
"You climb the spire until you reach the top.\n"
"You reach the roof.\n"
"As you climb up, the door slams closed behind you.\n"
"There is a harsh downpour. Lightning strikes in the distance.\n"
"Suddenly, a strong wind starts blowing against the tower.\n"
"You turn around to where the wind is coming from.\n"
"A giant dragon flaps it's wings, hovering in place.\n"
"'This is the obligatory dragon boss' you think.\n"
"You find an old bow on the ground. There are no arrows around.\n"
"It is also too windy to aim properly.\n"
"The dragon draws near.\n")
type("1. Use the water spell to fight it.\n")
type("2. Use your sword.\n")
type("3. Jump off of the spire.\n")
type("4. Use the freezing rod.\n")
choice = input("What should I do?")
if choice == 3:
jump2()
elif choice == 4:
freeze2()
else:
dragonkills()
def spire3():
type("\nYou climb the spire until you reach the top.\n"
"You reach the roof.\n"
"As you climb up, the door slams closed behind you.\n"
"There is a harsh downpour. Lightning strikes in the distance.\n"
"Suddenly, a strong wind starts blowing against the tower.\n"
"You turn around to where the wind is coming from.\n"
"A giant dragon flaps it's wings, hovering in place.\n"
"'This is the obligatory dragon boss' you think.\n"
"You find an old bow on the ground. There are no arrows around.\n"
"It is also too windy to aim properly.\n"
"The dragon draws near.\n")
type("1. Use the water spell to fight it.\n")
type("2. Use your sword.\n")
type("3. Jump off of the spire.\n")
type("4. Use the freezing rod.\n")
choice = input("What should I do?")
if choice == 3:
jump3()
elif choice == 4:
freeze2()
else:
dragonkills()
def jump3():
type("\nYou decide to jump off of the roof.\n"
"You weren't so lucky.\n"
"You slip as you run to the edge, and drop your gear.\n"
"With nothing to slow your fall, you fall into the castle.\n"
"Your plot armor wasn't strong enough to save you from the fall.\n"
"YOU DIED. GAME OVER.\n"
"What a stupid plan.")
def freeze2():
type("\nYou point your freezing rod toward the skies.\n"
"It shoots a beam of magic into the clouds above.\n"
"The clouds freeze and fall out of the sky.\n"
"The dragon is pinned to the tower under their weight.\n"
"While it is trapped, you run over and slash it with your sword.\n"
"The beast lets out a final anguished wail and collapses to the floor.\n"
"It explodes in a puff of dark smoke.\n"
"The door opens behind you.\n")
type("1. Go back to the middle room.\n")
type("2. Down to the basement.\n")
choice = input("Where should I go?")
if choice == 1:
onwarddragon()
else:
basement3()
def onwarddragon():
type("\nYou head back to the corridor from before.\n"
"On the door, a symbol resembling a skull is glowing.\n"
"The plaque still reads the same thing.\n"
"You decide to head up to the spire.")
basement3()
def basement3():
type("\nYou decide to head down to the basement.\n"
"It's less of a basement and more of a dungeon.\n"
"The floors are grates that are suspended over lava.\n"
"You walk into a room.\n"
"Suddenly, the door closes behind you!\n"
"The room begins to shake, bits of stone fall from the ceiling.\n"
"The lava under you is bubbling.\n"
"A giant hand smashes up through the grate from the lava.\n"
"The hand is made entirely of bone.\n"
"Another hand does the same.\n"
"The skeletal beast pulls itself out of the lava.\n"
"The colossus peers down at you with a single giant eye.\n"
"It roars with rage.\n"
"It raises a single hand above its head, then starts to bring it down towards you.\n")
type("1. Hit it with water magic.\n")
type("2. Dodge to the side.\n")
type("3. Attack with your sword.\n")
type("4. Shoot its eye with your bow.\n")
choice = input("What should I do?")
if choice == 2:
skeleescape2()
elif choice == 4:
skelekilled2()
else:
skelekills()
def skeleescape2():
type("\nThe skeleton launches its fist at you.\n"
"You try tumble to the side to evade the attack.\n"
"You are too slow, the skeleton smashes you with its fist.\n"
"YOU DIED. GAME OVER.\n"
"'Spooky scary skeletons send shivers down your spine...'")
def skelekilled2():
type("\nYou fire an arrow into its eye.\n"
"The colossus roars in pain and collapses to the ground.\n"
"You run over to it and begin to stab its eye with your sword.\n"
"The eye explodes in a puff of dark smoke.\n"
"The remains of the skeleton slide back into the lava.\n"
"The door behind you opens.\n"
"You decide to head back up to the middle room.\n")
actualonward()
def skelekills():
type("\nYou raise your weapon to attack.\n"
"The skeleton is faster.\n"
"It brings its fist down, smashing the grate below you.\n"
"You fall into the lava.\n"
"YOU DIED. GAME OVER.\n"
"Well that's just grate...")
def sneak():
type("\nYou decide to sneak into the castle.\n"
"You see an open window that is within reach.\n"
"You start to climb up to the window, but slip and fall. \n"
"The guard snake is alerted, and attacks you.")
snake()
def back():
type("\nYou go around to the backside of the castle.\n"
"There is a murky moat with what seems to be alligators in it.\n"
"A drawbridge sits over the moat.\n"
"Suddenly, the giant anaconda slithers behind the castle.\n"
"You aren't able to avoid detection, and it attacks you.")
snake()
def snake():
type("\nThe snake is coming towards you. You need to act.\n"
"You have TYPH00N's water spell and your runeblade.\n"
"You don't have much time...\n")
type("1. Fight it.\n")
type("2. Run across the drawbridge into the castle.\n")
type("3. Get to the moat.\n")
choice = input("What should I do about the snake?")
if choice == 1:
snakefight()
elif choice == 2:
drawbridge()
else:
moat()
def snakefight():
type("\nYou cast the water spell. It sends a torrent of water toward the beast.\n"
"Nothing happens. You draw your sword, but the snake kills you with a single bite.\n"
"YOU DIED. GAME OVER\n"
"'Why did it have to be snakes?'")
def drawbridge():
type("\nYou turn to the castle and start running.\n"
"You start across the drawbridge, but the snake smashes it with it's tail.\n"
"You fall into the water. The alligators eat you.\n"
"YOU DIED. GAME OVER.\n"
"What did you expect?")
def moat():
type("\nYou head to the moat, with the snake following you.\n"
"It lunges for you, but you sidestep.\n"
"The snake barrels past you, into the moat.\n"
"The alligators attack it, buying you some time.\n"
"You enter the castle.")
entercastle2()
def entercastle2():
type("\nYou enter the castle. The walls are lined with ancient artifacts on display.\n"
"Everything is coated with a thick layer of dust.\n"
"You notice that there is no dust on the carpets stretching through the castle.\n"
"You find a treasure chest. Inside it, you find a magical suit of armor.\n"
"It is called 'The Plot Armor'. It protects you from the terrible writing.\n"
"You reach two staircases.\n"
"One leads up to the spire, another to the basement.\n")
type("1. Head up to the spire.\n")
type("2. Head down to the basement.\n")
type("3. Ignore the stairs and continue onward.\n")
choice = input("What should I do now?")
if choice == 1:
spire()
elif choice == 2:
basement()
else:
onward()
def steal():
type("\nWhen the man isn't looking you steal his boat.\n"
"You start to cross the river. Around halfway across, your boat gets caught in a fierce current.\n"
"You lose control and capsize in the river. You drown.\n"
"YOU DIED. GAME OVER.\n"
"'We're gonna need a bigger boat.'")
def decline():
type("\nYou decline his offer. To your surprise, the man vanishes along with his boat.\n"
"'Great' you think, 'Now I have to find another way across the river.\n"
"You wander around, but get lost within the nether.\n"
"You continue to wander around, until you starve to death.\n"
"YOU DIED. GAME OVER.\n"
"Not all who wander are lost...")
def weapon2():
type("\n'I need a better weapon' you think as you get into your car. \n"
"Luckily, I know a guy.\n"
"You pull into the parking lot of Gary's Weapon Shop: 'Monstah Huntering Suppliez and Geer'.\n"
"The name is stupid, but the goods are quality.\n"
"As you get out of the car, the shop explodes into an ethereal flame.\n"
"You hear a maniacal laughter coming from the flames. Spooky.\n"
"Nobody could have survived that. But what if he did...\n")
type("1. Try to save Gary from the flames.\n")
type("2. Back to the portal.\n")
choice = input("What should I do???")
if choice == 1:
flames()
else:
deathportal2()
def deathportal2():
type("\nYou hurry back to the portal, traumatized over your decision...\n"
"As you rush forward, you forget about your water incantation.\n"
"You step into the portal, transporting you to the nether. Darkness surrounds you. \n"
"You hear a screeching behind you. You turn around to see an army of imps.\n"
"You try to fight them off, but your sword breaks.\n"
"YOU DIED. GAME OVER.\n"
"If only you had a better weapon...")
def pvz():
type("\nYou pick the deck 'VERSUS ZOMBIES'. \n"
"You play his game, and loose terribly. \n"
"His deck had some of the most powerful cards in the game...\n"
"He exclaims 'GET TYRANNOSAURUS REKT!'. You reply: 'You only won because I got terrible RNG...'\n"
"He kicks you out of his territory and tells you to stay out.\n")
type("1. Demand a rematch.\n")
type("2. Back to the portal.\n")
choice = input("What should I do?")
if choice == 2:
deathportal1()
else:
rematch()
def rematch():
type("\nYou intrude back into TYPH00N's territory.\n"
"When he sees you, he cries 'Interloper! I told you not to return!'\n"
"He orders his guards to kill you. You are shot to death.\n"
"YOU DIED. GAME OVER.\n"
"Don't jump the gun now...")
def sleep():
type("\nYou head home to take a quick nap. You set an alarm to ring in fifty minutes.\n"
"You oversleep your alarm.\n"
"The portal closes.\n"
"\nYOU SURVIVED:\n"
"This is really more of a loss than a win...\n"
"You are safe for now, but Master Warlock Gray is still at large, destroying the city.\n"
"Try again for the actual ending.")
def charge():
type("\nThe demon charges at you, filled with rage. \n"
"Panicked, you take a step backwards, only to slip in a puddle behind you. \n"
"While you are getting up, the demon reaches you and kills you with a savage blow.\n"
"YOU DIED. GAME OVER.\n"
"If only you had payed better attention to your surroundings...")
def back_away():
type("\nYou begin to back away slowly. You reach the entrance to the building.\n"
"The sign reads 'SKYSCRAPERS R US'. The building shudders in the wind.\n")
type("1. Enter the building.\n")
type("2. Back away some more.\n")
choice = input("Make your choice\n")
if choice == 1:
building()
else:
back_away_again()
def back_away_again():
type("\nThe streetlamp continues to smoke.\n"
"You continue to back away from it. \n"
"Not looking where you are going, you back into a street. \n"
"A car runs you over.\n"
"YOU DIED. GAME OVER.\n"
"Look both ways before you cross the street!")
def five():
type("\nYou reach the fifth floor. The building begins to sway in the wind. \n"
"Suddenly, it falls to the ground. \n"
"Luckily, you were unharmed by the fall because of your main character powers.\n"
"Also, you weren't that high up...\n")
type("1. Investigate the lamp.\n")
type("2. Back away from the rubble.\n")
choice = input("What now?")
if choice == 1:
lamp()
else:
back_away_again()
def building():
type("\nThere is a working elevator inside. \n"
"You enter the elevator.\n"
"The doors close. \n"
"A relaxing song plays in the background while you choose your floor.\n")
type("1. Floor five.\n")
type("2. Floor ten.\n")
type("3. Roof.\n")
choice = input("What floor do you want to go to?")
if choice == 1:
five()
else:
collapse()
def collapse():
type("\nThe elevator accelerates upward. You feel the building sway.\n"
"The building collapses while you are riding the elevator upwards. \n"
"The elevator falls with you inside it, causing an instant death. \n"
"YOU DIED. GAME OVER.\n"
"'SKYSCRAPERS R US is experiencing technical difficulties. Please stand by...'")
def wait():
type("\nYou decide to wait around to regain your senses. The wind howls fiercely.\n"
"You turn around to see the building swaying violently.\n"
"The building you are standing next to collapses, crushing you.\n"
"YOU DIED. GAME OVER.\n"
"A hero is never idle...")
def lamp():
type("\nYou cross the street to investigate the lamp. \n"
"Suddenly, lightning strikes it! Luckily, you were unharmed. \n"
"The building you awoke next to collapses suddenly. \n"
"Out of the smoke appears a giant, humanoid in appearance. \n"
"It is a fel demon from the netherworld.\n"
"It calls to you 'GlAdioN, I haVE coME For YoUR SoUl! VenGEncE Will BE MiNE!' \n"
"You don't know what it's talking about, but it seems angry.\n"
"You have a sword.\n")
type("1. RUN FOR IT!.\n")
type("2. Try to bargain.\n")
type("3. Fight the demon.\n")
choice = input("Make your choice: ")
if choice == 1:
run()
elif choice == 2:
bargain()
else:
fight()
def run():
type("\nYou turn to run away.\n"
"As you do, the demon pulls out a sword.\n"
"You are not fast enough. \n"
"The demon cries 'EldRitCH SmACKdOwN!!!' and cuts you down.\n"
"YOU DIED. GAME OVER.\n"
"Stay and face the darkness.")
def bargain():
type("\nYou call out to the demon,'WHAT DO YOU WANT FOUL BEAST?'\n"
"It screams back a reply: 'KnIT3bLAD3, i WIll Not BARGaiN WitH THe LikES Of YoU!!!!!!!!!!!!'\n"
"The demon draws its sword. \n"
"You pull out your sword, an elegant blade shining with the power of the holy light. \n"
"You can feel the power of the runeblade flowing through you as you grasp its hilt. \n"
"The light of the moon reflects off of the surface, revealing a dazzling shine.\n"
"The demon slashes at you. You block with your sword. The force of the impact shatters the blade. \n"
"You have time to mutter a sarcastic 'WOW...' before the demon beheads you. \n"
"YOU DIED. GAME OVER.\n"
"'Dormammu, I've come to bargain...'")
main()
|
43a792c87adb26fd5ffd2da072443061211323ba | Ramyaveerasekar/python_programming | /primeno.py | 559 | 3.515625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: vino
#
# Created: 23/03/2018
# Copyright: (c) VINO 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
pass
if __name__ == '__main__':
main()
num=int(input())
if num>1:
for i in range(2,1000):
if (num%i==0):
print num,("not a prime")
break
else:
print("prime")
|
02a8fc4f9fe3428b3bd6770000ea8ae6d1038387 | sheff-slava/jetBrains_dominoes | /dominoes.py | 6,317 | 3.875 | 4 | from itertools import chain
import random
stock = list()
computer = list()
player = list()
def determine_first(computer_pieces, player_pieces):
for i in range(6, -1, -1):
if [i, i] in computer_pieces:
return 0, [i, i]
elif [i, i] in player_pieces:
return 1, [i, i]
return -1
def distribute():
global stock
code = determine_first(computer, player)
while code == -1:
stock = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6],
[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 2],
[2, 3], [2, 4], [2, 5], [2, 6], [3, 3], [3, 4], [3, 5],
[3, 6], [4, 4], [4, 5], [4, 6], [5, 5], [5, 6], [6, 6]]
for _ in range(7):
random_domino = random.choice(stock)
computer.append(random_domino)
stock.remove(random_domino)
random_domino = random.choice(stock)
player.append(random_domino)
stock.remove(random_domino)
code = determine_first(computer, player)
return code
def end_game_condition():
print('======================================================================')
print('Stock size:', len(stock))
print(f'Computer pieces: {len(computer)}\n')
if len(domino_snake) < 7:
print(*domino_snake, '\n', sep='')
else:
print(domino_snake[0], domino_snake[1], domino_snake[2], '...',
domino_snake[-3], domino_snake[-2], domino_snake[-1], '\n', sep='')
print('Your pieces:')
for index, domino in enumerate(player):
print(f'{index + 1}:{domino}')
if len(computer) == 0:
print("\nStatus: The game is over. The computer won!")
return True
elif len(player) == 0:
print("\nStatus: The game is over. You won!")
return True
elif domino_snake[0][0] == domino_snake[-1][-1]:
first_digit = domino_snake[0][0]
digit_counter = 0
for snake in domino_snake:
if first_digit in snake:
digit_counter += 1
if digit_counter == 7:
print("\nStatus: The game is over. It's a draw!")
return True
if move_num == 0:
print("\nStatus: Computer is about to make a move. Press Enter to continue...")
else:
print("\nStatus: It's your turn to make a move. Enter your command.")
return False
def legal_move(move):
if move == 0:
return 0
if move_num == 0 and abs(move) <= len(computer):
if move < 0 and domino_snake[0][0] in computer[abs(move) - 1]:
return 0
elif move > 0 and domino_snake[-1][-1] in computer[abs(move) - 1]:
return 0
else:
return -2
if move_num == 1 and abs(move) <= len(player):
if move < 0 and domino_snake[0][0] in player[abs(move) - 1]:
return 0
elif move > 0 and domino_snake[-1][-1] in player[abs(move) - 1]:
return 0
else:
return -2
return -1
def handle_move(move):
try:
move = int(move)
except ValueError:
return -1
error_code = legal_move(move)
if error_code == 0:
if move_num == 0:
if move == 0:
if len(stock) != 0:
add_domino = random.choice(stock)
computer.append(add_domino)
stock.remove(add_domino)
else:
return -3
else:
chosen_domino = computer[abs(move) - 1]
if move < 0:
computer.remove(chosen_domino)
if domino_snake[0][0] != chosen_domino[-1]:
chosen_domino = [chosen_domino[1], chosen_domino[0]]
domino_snake.insert(0, chosen_domino)
elif move > 0:
computer.remove(chosen_domino)
if domino_snake[-1][-1] != chosen_domino[0]:
chosen_domino = [chosen_domino[1], chosen_domino[0]]
domino_snake.append(chosen_domino)
elif move_num == 1:
if move == 0:
if len(stock) != 0:
add_domino = random.choice(stock)
player.append(add_domino)
stock.remove(add_domino)
else:
return -3
else:
chosen_domino = player[abs(move) - 1]
if move < 0:
player.remove(chosen_domino)
if domino_snake[0][0] != chosen_domino[-1]:
chosen_domino = [chosen_domino[1], chosen_domino[0]]
domino_snake.insert(0, chosen_domino)
elif move > 0:
player.remove(chosen_domino)
if domino_snake[-1][-1] != chosen_domino[0]:
chosen_domino = [chosen_domino[1], chosen_domino[0]]
domino_snake.append(chosen_domino)
else:
return error_code
def computer_turn():
count_nums = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
for num in chain(computer, domino_snake):
count_nums[num[0]] += 1
count_nums[num[1]] += 1
scores = list()
for index, domino in enumerate(computer):
scores.append((count_nums[domino[0]] + count_nums[domino[1]], index, domino))
scores.sort(key=lambda x: x[0], reverse=True)
scores = [(x[1], x[2]) for x in scores]
for i, turn in scores:
if domino_snake[-1][-1] in turn:
return i + 1
if domino_snake[0][0] in turn:
return -(i + 1)
return 0
random.seed()
move_num, domino_snake = distribute()
if move_num == 0:
computer.remove(domino_snake)
else:
player.remove(domino_snake)
move_num = (move_num + 1) % 2
domino_snake = [domino_snake]
while not end_game_condition():
if move_num == 1:
code = handle_move(input())
while code == -1 or code == -2:
if code == -1:
print("Invalid input. Please try again.")
elif code == -2:
print("Illegal move. Please try again.")
code = handle_move(input())
else:
input()
code = computer_turn()
handle_move(code)
move_num = (move_num + 1) % 2
|
4074ff4810f9fc8add3f07b385e4d2e982e74620 | vgsprasad/Python_codes | /year.py | 1,236 | 3.5625 | 4 | cal_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
cal_nonleap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
conv_leap = [31, 16, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
conv_nonleap = [31, 15, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]
def leap_year(year):
if year % 4:
return 0
else:
if year%100:
return 1
else:
if year%400:
return 1
else:
return 0
def two_fifty_sixth_day(arr, year):
month = 1
date = 0
const = 256
for i in range(0, 11):
if arr[i] < const:
const = const - arr[i]
month = month + 1
else:
date = const+1
return (str(date) + "." + str(month) + "." + str(year))
def greg_day(year):
if leap_year(year):
return two_fifty_sixth_day(cal_leap, year)
else:
return two_fifty_sixth_day(cal_nonleap, year)
def change_day(year):
if leap_year(year):
return two_fifty_sixth_day(conv_leap, year)
else:
return two_fifty_sixth_day(conv_nonleap, year)
def julian_day(year):
if not year % 4:
return two_fifty_sixth_day(cal_leap, year)
else:
return two_fifty_sixth_day(cal_nonleap, year)
year = input()
if (year > 1918):
print greg_day(year)
elif year == 1918:
print change_day(year)
else:
print julian_day(year)
|
b1e95844fd50ed83d8047603ba318ddbf914ca6d | poowoo/leetcode_questions | /191_Number_of_1_Bits.py | 455 | 3.859375 | 4 | class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
while(n >= 1):
if int(n) & 1 == 1:
sum += 1
n /= 2
return sum
def main():
input = int('11111111111111111111111111111101',2)
ans = Solution().hammingWeight(input)
print(ans)
if __name__ == "__main__":
main() |
d8d521731799e278b1f204976123de44c4162b3f | jopela/cityinfo | /cityinfo.py | 2,384 | 3.546875 | 4 | #!/usr/bin/env python3
import json
import argparse
import sys
import logging
import iso3166
# takes a guide file and returns it's city name and country.
def main():
parser = argparse.ArgumentParser(
description="extract city name and bounding box from"\
" a guide.")
parser.add_argument(
'guide',
help='path to guide from which the cityname and the country name'\
' will be extracted. Defaults to stdin if absent',
type = argparse.FileType('r'),
nargs = '?',
default = sys.stdin
)
parser.add_argument(
'-t',
'--test',
help='run the doctest suite and exit',
action='store_true'
)
args = parser.parse_args()
if args.test:
import doctest
doctest.testmod()
exit(0)
jsonguide = json.load(args.guide)
info = cityinfo(jsonguide)
print(info)
return
def filecityinfo(filename):
"""
same as cityinfo but act on a filename rather then a guide content.
"""
jsonguide = None
with open(filename,'r') as g:
jsonguide = json.load(g)
if not jsonguide:
return None
res = cityinfo(jsonguide)
return res
def filecountryinfo(filename):
"""
Returns the country code (iso3166 alpha2) of the city-guide found at
filename.
"""
guide_data = load_guide(filename)
# get the country key.
country = guide_data['Cities'][0].get("country",None)
country_code = country
try:
country_code = iso3166.countries[country].alpha2
except:
pass
return country_code
def load_guide(filename):
"""
returns the datastructure constructed from the json guide found at
filename.
"""
guide = None
with open(filename,'r') as g:
guide = json.load(g)
return guide
def cityinfo(jsonguide):
"""
return the city name and the bounding box, separated by a ';'.
EXAMPLE
=======
>>> jsonguide = json.load(open('./test/inguide.json','r'))
>>> cityinfo(jsonguide)
'Bali;-8.04968577,114.3502976,-8.85186802,115.76261798'
"""
city = jsonguide['Cities'][0]['name']
bb = ",".join(jsonguide['Cities'][0]['bounding_box'])
res = ";".join([city,bb])
return res
if __name__ == '__main__':
main()
|
53c83f21657d5d364d3d45d2d7ff003a22ae194c | kobeding/python | /2016/do_fork.py | 960 | 3.859375 | 4 | #!/usr/bin/python3.5
#fork()系统调用,调用一次返回两次(复制一份子进程)
#一个父进程可以fork出很多子进程,所以父进程需要记住每个子进程的ID
#而子进程只需要调用getppid()就可以拿到父进程的ID
#有了fork,一个进程在接到新任务时就可以复制出一个子进程来处理新任务
#apache服务器就是由父进程监听端口,子进程处理新的http请求
import os#os封装常见的系统调用
print('Process (%s) start ...' % os.getpid())
pid = os.fork() #子进程永远返回0,父进程返回子进程的ID
if pid == 0:
print('I am child process (%s) and my parent is %s.' % (os.getpid(),os.getppid()))
else: #不为0,此时返回的是子进程的ID(pid)
print('I (%s) just created a child process (%s).' % (os.getpid(),pid))
"""
Process (12768) start ...
I (12768) just created a child process (12769).
I am child process (12769) and my parent is 12768.
""" |
148953ae8841f2d8b9e67a972b0ad50c19dea465 | joshuathompson/ctci | /stacks/sort_stack.py | 561 | 3.796875 | 4 | unorderedStack = [5, 4, 6, 4, 3, 12, 23, 10, 5, 10, 3, 12]
orderedStack = []
pop = None
hold = None
while len(unorderedStack) > 0:
pop = unorderedStack.pop()
if hold is None:
hold = pop
elif pop >= hold:
for item in reversed(orderedStack):
if pop > item:
moveBack = orderedStack.pop()
unorderedStack.append(moveBack)
orderedStack.append(pop)
else:
orderedStack.append(hold)
hold = pop
if hold is not None:
orderedStack.append(hold)
print(orderedStack) |
1d93b4feeb9497592605413421e1615ad98ed0d5 | shiny0510/DataStructure_Python | /Algorithm analysis/prefixAverage.py | 684 | 3.625 | 4 | from time import time
def prefix_average1(S):
n = len(S)
A = [0]*n
for j in range(n):
total = 0
for i in range(j+1):
total += S[i]
A[j] = total / (j+1)
return A
# Looks Better
def prefix_average2(S):
n = len(S)
A = [0]*n
for j in range(n):
A[j] = sum(S[0:j+1])/(j+1)
return A
# Linear Time
def prefix_average3(S):
n = len(S)
A = [0]*n
total = 0
for j in range(n):
total += S[j]
A[j] = total/(j+1)
return A
S = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# print(prefix_average1(S))
# print(prefix_average2(S))
# print(prefix_average3(S))
|
96e8a52cd581f6c3d5f1cdbbf185dc35ba04a50f | jaugustomachado/Curso-Next-Python | /Aula4 - Vetores e estrutura de repetição/media.py | 310 | 4.125 | 4 | #Faça um programa que calcule o mostre a média aritmética de N notas.
n=int(input('informe o número de notas, para cálculo da média: '))
notas = [ ]
soma=0
for i in range(n):
notas.append(float(input('informe a nota do aluno: ')))
soma=soma+notas[i]
print( ' a média das notas é : ', soma/n) |
5924aaba2bb6fbcf835a45215b65c12a917e06f1 | bioCKO/science | /python workshop/.svn/text-base/flow.py.svn-base | 1,191 | 4.1875 | 4 | if True:
print("TRUE!")
else:
print("FALSE!")
if False:
print("TRUE!")
else:
print("FALSE!")
if 1:
print("TRUE!")
else:
print("FALSE!")
if 5:
print("TRUE!")
else:
print("FALSE!")
if 0:
print("TRUE!")
else:
print("FALSE!")
if None:
print("TRUE!")
else:
print("FALSE!")
if []:
print("TRUE!")
else:
print("FALSE!")
type = 1
if type == 0:
type = "RANDOM"
elif type == 1:
type = "ORDERED"
else:
type = "OTHER"
print (type)
#make a function that takes a number, and tells you wether it is even or odd
def evenCheck(num):
if num % 2 == 0:
print("even")
else:
print("odd")
#modify the function to return 1 if num is even and 0 otherwise
def evenCheck(num):
if num % 2 == 0:
return 1
return 0
#make a function that returns the nationality of the person
def nation(person):
if person == "Robert":
return "American"
elif person == "Arvid":
return "Swede"
elif person == "Stephen":
return "Canadian"
else:
return "Who knows?"
print(nation("Robert"))
print(nation("Arvid"))
print(nation("Bob")) |
a63a895f8338c247ffd7bcf49ab014727f460ccc | safelyafnan/Muhammad-Safely-Afnan_I0320070_M-Wildan-Rusydani_Tugas-4 | /Soal 2.py | 197 | 3.875 | 4 | pertama= int(input('Masukkan Angka Pertama: '))
kedua= int(input('Masukkan Angka Kedua: '))
print(" ")
print('Angka pertama bisa dibagi oleh angka kedua sebanyak {} kali'.format(pertama//kedua)) |
c3a90f14740eb23907da2539b2c045f5322451dd | vsapronova/BackToBack | /nearest_repeated_entries.py | 533 | 3.75 | 4 | def nearest_distance(sentence):
if len(sentence) < 2:
return None
last_seen_repeated = {}
closest_dist = []
for i in range(len(sentence)):
word = sentence[i]
if word in last_seen_repeated:
closest_dist.append(i - last_seen_repeated[word])
last_seen_repeated[word] = i
return -1 if len(closest_dist) == 0 else min(closest_dist)
print(nearest_distance([
"This",
"is",
"a",
"sentence",
"with",
"is",
"repeated",
"then",
"repeated",
"a",
"a"
])) |
c7c70a59fbf74a502539bbafd01cd4f9f66cab29 | onedreamxmm/Recursion2 | /50. Pow(x, n).py | 771 | 3.9375 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
time complexity: O(log2(n))
space complexity: O(log2(n))
'''
class Solution:
def myPow1(self, x, n):
if n == 0:
return 1
if n < 0:
return 1 / self.myPow1(x, -n)
half = self.myPow1(x, n//2)
if n % 2 == 0:
return half * half
else:
return half * half * x
def myPow2(self, x, n):
if not n:
return 1
if n < 0:
return 1 / self.myPow2(x, -n)
if n % 2:
return x * self.myPow2(x, n-1)
return self.myPow2(x*x, n/2)
if __name__ == '__main__':
x = 3
n = -2
o = Solution()
print(o.myPow1(x, n))
print(o.myPow2(x, n)) |
1426d6e06644f26b42985f2a3bb69e9c481c3665 | pepeArenas/PythonFundamentals | /chapter/collections/CopiesAreShallow.py | 776 | 4.1875 | 4 | numbers = [[1, 2, 3], [4, 5, 6]]
ages = numbers[:]
print("Both list: numbers and ages has the same values", numbers == ages)
print("Both list: numbers and ages has not the same identity", numbers is ages)
print(
"If we reassign ages[0] it will make a new reference for that index and it will be "
"independent from the numbers list")
ages[0] = [7, 8, 9]
print(ages[0]) # This has the new value that we just reassign
print(numbers[0]) # This has the same value as the beginning, and do not have any reference to ages[0]
print("Buf if we just append to a ages[1], this is a mutable operation this will change both list because"
"we are not reassign anything ")
ages[1].append(34)
# The following lines has the same values
print(ages[1])
print(numbers[1])
|
ce85a7bd6513ca1243aa469c2e864c70baba1a8a | mastermind2001/Problem-Solving-Python- | /deficient_numbers.py | 3,057 | 4.3125 | 4 | # Date : 24-05-2018
# Deficient Numbers
# main function for telling a number is deficient or not
def is_deficient(num):
"""
:param num: a positive integer value
:return: a string indicating a number is deficient or not
"""
store_sum = 0
# iterate over an entire range, range = num+1
for integer in range(1, num+1):
if num % integer == 0:
store_sum += integer
if store_sum < 2*num:
print(str(num) + " is a deficient number")
print('\n---------------------------------\n')
else:
print(str(num) + " is not a deficient number")
print('\n---------------------------------\n')
# copied First function for return different result (a boolean value)
def is_deficient_copy(num):
"""
:param num: a positive integer value
:return: a string indicating a number is deficient or not
"""
store_sum = 0
# iterate over an entire range, range = num+1
for integer in range(1, num+1):
if num % integer == 0:
store_sum += integer
if store_sum < 2*num:
return True
else:
return False
# main function for printing deficient numbers up to a given range
def deficient_numbers_range(num):
"""
:param num: a positive integer value
:return: all deficient numbers up to a given range, range = input num
"""
print('Deficient numbers up to ' + str(num) + ' are : \n')
# iterate over an entire range, range = num+1
for integer in range(1, num + 1):
if is_deficient_copy(integer):
print(integer)
print('\n---------------------------------\n')
# main function for telling a number is deficient or not and displaying everything
def displaying_deficient(num):
"""
:param num: a positive integer value
:return: a string indicating a number is deficient or not
"""
# storing factors as strings
store_factors = ''
store_sum = 0
# iterate over an entire range, range = num+1
for integer in range(1, num+1):
if num % integer == 0:
store_sum += integer
store_factors += str(integer) + ', '
print('Factors of '+str(num)+' are : '+store_factors[:-2]+'\n')
print('Sum of factors is : '+str(store_sum)+'\n')
if store_sum < 2*num:
print(str(num) + " is a deficient number")
print('\n---------------------------------\n')
else:
print(str(num) + " is not a deficient number")
print('\n---------------------------------\n')
# input a positive integer value
number = input()
# error handling for wrong input
if number.isdigit():
if int(number) > 0:
# calling function is_deficient
is_deficient(int(number))
# calling function deficient_numbers_range
deficient_numbers_range(int(number))
# calling function displaying_deficient
displaying_deficient(int(number))
else:
print('Invalid input. You can enter only positive integers')
else:
print('Invalid input. You can enter only positive integers')
|
6fa1bf4053ca041fec53d21b73da21aff03694d3 | mecomontes/Python | /Fundamentos Python/Matrices_2.py | 767 | 3.6875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Creación de una Matriz, de manera aleatoria
# Hacer un programa que llene la matriz de manera aleatoria
# Encontrar:
# El valor mayor
# El valor menor
# El valor promedio
# Generar aleatoriamente:
# El numero de filas que tiene la matriz
# El numero de columnas que tiene la matriz
# Los valores de la matriz
# Mostrar:
# La matriz
# El valor mayor
# El valor menor
# El valor promedio
import numpy as np
import random as rd
Filas=rd.randint(2,10)
Columnas=rd.randint(2,10)
Matriz=np.zeros((Filas,Columnas))
for i in range(Filas):
for j in range(Columnas):
Digito=rd.randint(0,99)
Matriz[i,j]=Digito
print ("\n MATRIZ RESULTADO")
print(Matriz)
|
c75abaf694657502f69ee78603278f2517dc23c9 | akaushal123/Project-Euler | /6. Sum Square Difference.py | 904 | 4.21875 | 4 | """
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
def sum_square_natural_number(n):
return (n * (n + 1) * (2 * n + 1))/6
def sum_natural_number(n):
return n * (n + 1)/2
def sum_difference(l):
sum_squares = sum_square_natural_number(l)
sum_term = sum_natural_number(l)
return (sum_term * sum_term) - sum_squares
def sum_difference_simplified(n):
"""
used simplified formula for solving
Solved formula for
S1 = 1+2+3+...+n = n*(n+1)/2
S2 = 1*1 + 2*2 + ... + n*n = n* (n + 1) * (2 * n + 1)/6
S = S1**2 - S2
S = (n * (n + 1) * (n-1) * (3*n + 2))/12
"""
return (n * (n + 1) * (n-1) * (3*n + 2))/12
if __name__ == "__main__":
limit = int(input("Enter the limit"))
print(sum_difference(limit))
print(sum_difference_simplified(limit)) |
c20180d6bd542014f0891d429a8e3f7a349a5a73 | coder-dipesh/Basic_Python | /labwork2/leapyear.py | 257 | 4.0625 | 4 | year=int(input('Enter year to check :'))
if (year%4)==0:
if (year%100)==0:
if (year%400)==0:
print('Leap Year')
else:
print("Not Leap Year")
else:
print("Leap Year")
else:
print("Not Leap Year")
|
0f63de8752cbb846f3b7687c72a33e2d1e1e3195 | tcollins2011/rosalind | /Perfect_matchings_and_rna_secondary_structures/index.py | 968 | 3.65625 | 4 | # Separates fasta file to a single DNA string
from math import factorial
def clean_data(fasta):
cleaned = []
data_set = fasta.strip().split('>')
for dna in data_set:
if len(dna):
i = dna.split()
target = ''.join(i[1:])
cleaned.append(target)
return cleaned
# Assumes an equal number of A's and U's, as well as an equal number of C's and G's
# Can then assume that there is an au and cg complete bipartite graph
# Then uses factorials of these complete graphs multipled together to calculate the maximum number of complete matchings
def total_matches(sequence):
AU = 0
GC = 0
for nucleotide in sequence:
if nucleotide == 'A':
AU += 1
elif nucleotide == 'G':
GC += 1
matchings = factorial(AU) * factorial(GC)
return matchings
if __name__ == "__main__":
sequence = clean_data(open('data.txt').read())
print(total_matches(str(sequence))) |
809f52d51770ebdd6aebae79b6872ce0c588c55c | 283938162/FirstPython | /com/tlz/python-base/python-match.py | 823 | 3.5 | 4 | import re
'''
match.group([group1, ...])
获得匹配后的分组字符串,参数为编号或者别名;
group(0)代表整个字符串,group(1)代表第一个分组匹配到的字符串,
依次类推;如果编号大于pattern中的分组数或者小于0,则返回IndexError。
另外,如果匹配不成功的话,返回None;如果在多行模式下有多个匹配的话,返回最后一个成功的匹配。
'''
m = re.match(r'(\w+)\s+(\w+)', 'Isaac Newton, physicist')
print(m)
print(m.group())
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(3))
'''
match.groups(default=None)
返回一个tuple,包含所有的分组匹配结果;
如果default设为None的话,如果有分组没有匹配成功,则返回"None";若设为0,则返回"0"。
'''
print(m.groups())
|
670a2d7e699fa4440bd996a65e50f846146b5e24 | robomojo/pyxml_clean_edit | /pyxml_clean_edit/test/test_pyxml_clean_edit.py | 8,386 | 3.515625 | 4 | '''
tests for the various ways we might want to add things to an xml file.
'''
import os
from os import unlink
import xml.etree.ElementTree as ET
import tempfile
import xml.dom.minidom
from .. import xml_helpers
from . import utils
def test_add_element():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
ET.SubElement(xml_parent, 'child', attrib={'Name':'1'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# make some new children
xml_child_2 = ET.Element('child', attrib={'Name':'2'})
xml_child_3 = ET.Element('child', attrib={'Name':'3'})
# add the children
xml_helpers.add(file_path=f.name, elements=[xml_child_2, xml_child_3], tag_match='parent')
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/child')) == 3)
def test_replace_child_elements():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
ET.SubElement(xml_parent, 'child', attrib={'Name':'1'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# make some new children
xml_child_2 = ET.Element('child', attrib={'Name':'2'})
xml_child_3 = ET.Element('child', attrib={'Name':'3'})
# add the children
xml_helpers.replace_children(file_path=f.name, elements=[xml_child_2, xml_child_3], tag_match='parent')
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/child')) == 2)
def test_replace_child_elements_with_subelement():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
xml_subparent = ET.SubElement(xml_parent, 'children')
ET.SubElement(xml_subparent, 'child', attrib={'Name':'1'})
ET.SubElement(xml_subparent, 'child', attrib={'Name':'2'})
ET.SubElement(xml_subparent, 'child', attrib={'Name':'3'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# replace with None
# xml_helpers.replace_children(file_path=f.name, elements=None, tag_match='parent')
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/child')) == 0)
def test_replace_element():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
xml_subparent = ET.SubElement(xml_parent, 'children')
ET.SubElement(xml_subparent, 'child', attrib={'Name':'1'})
ET.SubElement(xml_subparent, 'child', attrib={'Name':'2'})
ET.SubElement(xml_subparent, 'child', attrib={'Name':'3'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# replace with None
xml_helpers.replace(file_path=f.name, element=ET.Element('imposter'), tag_match='child', attrib_match={'Name':'2'})
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/children/child')) == 2)
assert(len(new_xml_root.findall('parent/children/imposter')) == 1)
def test_remove_elements():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
ET.SubElement(xml_parent, 'child', attrib={'Name':'1'})
ET.SubElement(xml_parent, 'child', attrib={'Name':'2'})
ET.SubElement(xml_parent, 'child', attrib={'Name':'3'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# add the children
xml_helpers.remove(file_path=f.name, tag_matches='child', attrib_matches=[{'Name':'2'}, {'Name':'3'}])
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/child')) == 1)
def test_add_element_using_subtags():
# make an xml
xml_root = ET.Element('root')
xml_parent = ET.SubElement(xml_root, 'parent')
xml_children = ET.SubElement(xml_parent, 'children')
xml_child1 = ET.SubElement(xml_children, 'child', attrib={'Name':'1'})
xml_child1_children = ET.SubElement(xml_child1, 'children')
xml_child1_subchild = ET.SubElement(xml_child1_children, 'child', attrib={'Name':'1'})
xml_child1_subchild = ET.SubElement(xml_child1_children, 'child', attrib={'Name':'2'})
xml_child1_subchild = ET.SubElement(xml_child1_children, 'child', attrib={'Name':'3'})
xml_child2 = ET.SubElement(xml_children, 'child', attrib={'Name':'2'})
xml_child2_children = ET.SubElement(xml_child2, 'children')
xml_child2_subchild = ET.SubElement(xml_child2_children, 'child', attrib={'Name':'1'})
xml_child2_subchild = ET.SubElement(xml_child2_children, 'child', attrib={'Name':'2'})
xml_child2_subchild = ET.SubElement(xml_child2_children, 'child', attrib={'Name':'3'})
xml_children = ET.SubElement(xml_root, 'children')
xml_child3 = ET.SubElement(xml_children, 'child', attrib={'Name':'1'})
raw_xml = ET.tostring(xml_root)
prettyXml = xml.dom.minidom.parseString(raw_xml).toprettyxml(indent=" ", newl='\n')
f = tempfile.NamedTemporaryFile(delete=False)
f2 = tempfile.NamedTemporaryFile(delete=False)
# write it
with open(f.name, mode='w') as t_file:
t_file.write(prettyXml)
with open(f2.name, mode='w') as t_file:
t_file.write(prettyXml)
# add the children
xml_helpers.add(file_path=f.name, elements=ET.Element('inserted'), tag_match='parent', sub_tags='children')
# os.system('"C:\\Program Files\\KDiff3\\kdiff3.exe" {0} {1}'.format(f2.name, f.name))
# try to find the children
new_xml_root = ET.parse(f.name).getroot()
# close the file
f.close()
unlink(f.name)
f2.close()
unlink(f2.name)
# test
assert(len(new_xml_root.findall('parent/children/inserted')) == 1)
|
50aa30650c0f4697e04c63485eb3c84044d9c70d | duwn55/coding-practice | /python/반복문/while_with_time.py | 257 | 3.703125 | 4 | # 시간과 관련된 기능 가져오기.
import time
# 변수 선언
number = 0
# 5초 동안 반복
target_tick = time.time() + 5
while time.time() < target_tick :
number += 1
# 출력
print("5초 동안 {}번 반복했습니다.".format(number))
|
8c06e8191631c2c83e794236db7628b771cf504b | Shirhussain/Advance-python | /Fluent_python/Data_Structures.py | 8,522 | 3.8125 | 4 | #List Comprehensions and Readability
symbols = '$¢£¥€¤'
code = []
for symbol in symbols:
code.append(ord(symbol))
code = [ord(syembol) for syembol in syembols]
print(code)
#Listcomps No Longer Leak Their Variables
a = 'my precious'
data = [a for a in 'KLM']
print(a)
m = "KLM"
dummy = [ord(m) for m in m]
print(m)
print(dummy)
#Listcomps Versus map and filter
#Listcomps do everything the map and filter functions do
symbols = '$¢£¥€¤'
beyond_ascii = [ord(m) for m in symbols if ord(m)>130]
print(beyond_ascii)
beyond_ascii = list(filter(lambda z: z>90, map(ord,symbols)))
print(beyond_ascii)
----------------------------- tuple and list----------------
#Cartesian Products
colors = ['white', 'green','black','yellow']
sizes = ['S', 'M','L']
tshirts = [(color, size) for color in colors for size in sizes]
print(tshirts)
# or we can do like this as well
for color in colors:
for size in sizes:
print((color, size), end=",")
tshirts2 = [(color, size) for size in sizes for color in colors]
print(tshirts2)
======================Generator Expressions ===========
#Generator Expressions
import array
symbols = '$¢£¥€¤'
tuple_ = tuple(ord(symbol) for symbol in symbols)
print(tuple_)
arr_ = array.array("I", (ord(symbol) for symbol in symbols))
print(arr_)
# Cartesian product in a generator expression
colors = ['black','white']
sizes = ['S','M','L']
for tshirt in ('%s %s' % (c,s) for c in colors for s in sizes):
print(tshirt)
====================Tuples Are Not Just Immutable Lists=====================
#Tuples as Records
lax_coordinates = (33.9425, -118.408056)
city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'),('ESP', 'XDA205856')]
for passport in sorted(traveler_ids):
print('%s/%s' % passport)
for country, _ in traveler_ids:
print(country)
#Tuple Unpacking
d=divmod(30,7)
print(d)
t = (20,7)
print(divmod(*t))
import os
_,fileName = os.path.split('/usr/lib/python3.8/os.py')
print(fileName)
==============Using * to grab excess item===========
a,b,*rest = range(10)
print(a,b,rest)
n,m,*digar = range(5)
print(m,n,digar)
a,*rest, b = range(10)
print(a,rest,b)
*rest, a,b = range(5)
print(rest,b,a)
metro_areas = [
('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833))
]
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas:
if longitude <= 0:
print(fmt.format(name, latitude, longitude))
#the output will be
| lat. | long.
Mexico City | 19.4333 | -99.1333
New York-Newark | 40.8086 | -74.0204
Sao Paulo | -23.5478 | -46.6358
================================= Named Tuples====================
#The collections.namedtuple function is a factory that produces subclasses of tuple enhanced with field names and a class name
from collections import namedtuple
City = namedtuple('City','name country population coordinate')
jpan = City('tokyo','jp',36.933,(35.33433,139.4534534))
print(jpan)
print(jpan.population)
print(jpan.coordinate)
print(jpan[0])
print(City._fields)
LatLong = namedtuple('LatLong','lat long')
kabul_data = ('Kabul','af',6.3,LatLong(34.345345,180.324243))
kabul = City._make(kabul_data)
print(kabul)
print(kabul._asdict)
for key, value in kabul._asdict().items():
print(key+' : ', value)
======================== Slicing ====================================
le = [10,20,30,40,50,60,70,80,90]
print(le[:2])
print(le[2:])
st=("shirhussain_danishyar")
#this one jump 2 unite every time
print(st[::3])
#making reverse
print(st[::-1])
#reverse jump one unite
print(st[::-2])
#this is teh sequance
#seq[start:stop:step]
invoice = """
... 0.....6.................................40........52...55........
... 1909 Pimoroni PiBrella $17.50 3 $52.50
... 1489 6mm Tactile Switch x20 $4.95 2 $9.90
... 1510 Panavise Jr. - PV-201 $28.00 1 $28.00
... 1601 PiTFT Mini Kit 320x240 $34.95 1 $34.95
... """
product_id = slice(0, 6)
description = slice(6,40)
unite_price = slice(40,52)
qunatinty = slice(52,55)
total_price = slice(55,None)
#print(invoice.split("\n")[2:])
items = invoice.split("\n")[2:]
for item in items:
print(item[unite_price], item[description])
#Multidimensional Slicing and Ellipsis
li = list(range(10))
print(li)
li[3:5] = 40,30
print(li)
del li[5:7]
print(li)
#li[1:3]=100 if i use like this i will get an error
li[1:3] = [100]
print(li)
#Using + and * with Sequences
print(li*5) # repeating five time
#Building Lists of Lists
board = [['_'] * 3 for i in range(3)]
print(board)
board[1][2] = "100"
print(board)
#also we can write as follows
board = []
for i in range(3):
row = ['_']*3
board.append(row)
board[1][2]="x"
print(board)
#but here is another example wiche look the same but arn't
# and dosn't behave the same way
#The same row is appended three times to board
# but in above examples each iteration builes a new row and append to teh lest
new_board = [['_']*3]*3
new_board[1][2]="200"
print(new_board)
#the last example look like this
row = ['_']*3
new_board = []
for i in range(3):
new_board.append(row)
new_board[1][2]="y"
print(new_board)
=========================================Augmented Assignment with Sequence=====================
li = (2,5,[15,30])
li[2] += [40,50]
print(li)
#Note
"""
Putting mutable items in tuples is not a good idea
Augmented assignment is not an atomic operation—we just saw it throwing an exception after doing part of its job.
Inspecting Python bytecode is not too difficult, and is often helpful to see what is going on under the hood
"""
==================================Managing Ordered Sequences with bisect ====================
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
row_fmt = '{0:2d} @ {1:2d} {2}{0:2d}'
def sample(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position*' |'
print(row_fmt.format(needle, position, offset))
if __name__=="__main__":
if sys.argv[-1] =="left":
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('Sample: ',bisect_fn.__name__)
print('hystack ->', ' '.join('%2d' % n for n in HAYSTACK))
sample(bisect_fn)
#Inserting with bisect.insort
import bisect
import random
SIZE = 10
my_list=[]
random.seed(2000)
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.insort(my_list, new_item)
print('%2d -> ' % new_item, my_list)
==============================When a List Is Not the Answer========================
from array import array
from random import random
floats = array('d',(random() for i in range(10**4)))
print(floats[-1])
fw = open('floats.bin','wb')
floats.tofile(fw)
fw.close()
floats2 = array('d')
fo = open('floats.bin','rb')
floats2.fromfile(fo,10**4)
fo.close()
print(floats2[-1])
floats2 ==floats
"""
As you can see, array.tofile and array.fromfile are easy to use.
A quick experiment show that it takes about 0.1s for array.fromfile to load 10 million double-precision floats from a binary file created with array.tofile. That is nearly 60 times faster than reading the numbers from a text file, which also involves parsing each line with the float built-in. Saving with array.tofile is about 7 times faster than writing one float per line in a text file.
In addition, the size of the binary file with 10 million doubles is 80,000,000 bytes (8 bytes per double, zero overhead), while the text file has 181,515,739 bytes, for the same data.
Another fast and more flexible way of saving numeric data is the pickle module for object serialization.
"""
=====================================Memory Views========================================
import array
nums = array.array('h',[-2,-1,0,1,2])
memv = memoryview(nums)
print(len(memv))
mem_oct = memv.cast('B')
print(mem_oct.tolist())
print(mem_oct[5])
print(nums)
# end of chapter two
|
4076d6f5676385a963c16856d6e156cc6db99bc5 | Intenfas/Intenfas | /EX1.py | 2,629 | 4.0625 | 4 | from functools import partial
class Set:
def __init__(self, values=None):
self.dict = {}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
return "Set: " + str(self.dict.keys())
def add(self, value):
self.dict[value] = True
def contains(self, value):
return value in self.dict
def remove(self, value):
del self.dict[value]
s = Set([1,2,3])
s.add(4)
print s.contains(4)
s.remove(3)
print s.contains(3)
print ("str(Set)"+str(s))
class Set1(Set):
def __repr__(self):
return "Set: " + str(self.dict.keys())
s2 =Set1([1,2,3,4,])
s2.add(10)
print ("str(Set1)"+str(s2))
print ("---------\n")
print ("-----\n")
def exp(base, power):
return base ** power
def two_to_the(power):
return exp(2, power)
two_to_the = partial(exp, 2) # is now a function of one variable
print two_to_the(3)
print ("---------\n")
def double(x):
return 2 * x
xs = [1, 2, 3, 4]
twice_xs = [double(x) for x in xs] # [2, 4, 6, 8]
print ("double for X in xs"+str(twice_xs))
twice_xs = map(double, xs) # same as above
print ("map"+str(twice_xs))
list_doubler = partial(map, double) # *function* that doubles a list
twice_xs = list_doubler(xs) # again [2, 4, 6, 8]
print ("---------\n")
def multiply(x, y): return x * y
products = map(multiply, [1, 2], [4, 5]) # [1 * 4, 2 * 5] = [4, 10]
print ("products"+str(products)+"\n")
def is_even(x):
"""True if x is even, False if x is odd"""
return x % 2 == 0
x_evens = [x for x in xs if is_even(x)] # [2, 4]
print ("x_evens" + " = " +str(x_evens) )
x_evens = filter(is_even, xs) # same as above
print ("filter_x_evens"+str(x_evens))
list_evener = partial(filter, is_even) # *function* that filters a list
x_evens = list_evener(xs) # again [2, 4]
print ("x_evens" + " = " +str(x_evens) )
print ("--reduce nultiply--")
x_product = reduce(multiply, xs) # = 1 * 2 * 3 * 4 = 24
list_product = partial(reduce, multiply) # *function* that reduces a list
x_product = list_product(xs) # again = 24
print ("x_product = "+str(x_product))
print ("\n---word cut---")
documents=["aa","bbb","GGG"]
for i in range(len(documents)):
document = documents[i]
print (i, document)
print ("\n-------\n")
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
zip(list1, list2)
print ("zip list1+list2 ="+str(zip(list1, list2)))
pairs = [('a', 1), ('b', 2), ('c', 3)]
letters, numbers = zip(*pairs)
print ("pairs unzip"+str(zip(*pairs)))
def magic(**args, *kwargs):
print "unnamed args:", args
print "keyword args:", kwargs
magic( 'a',1,2,key="word", key2="word2",)
|
efec55f2b46b35d7f154cf7abe625e2d628739c4 | mathankrish/Python-Programs | /Company_ques/Arithematic series-1.py | 491 | 4 | 4 | # Arithematic series for 0,0,7,6,14,12,21,18,28 find the 15th term in the series
number_of_term = int(input("Enter the nth term: "))
List = number_of_term * [0]
even_place = 0
odd_place = 0
List[0] = 0
List[1] = 0
for i in range(2, number_of_term):
if i % 2 == 0:
even_place += 7
List[i] = even_place
else:
odd_place += 6
List[i] = odd_place
print(List)
print("The {0} element in the series is {1}".format(number_of_term, List[-1])) |
286bcf7ea35235779ad4a6ae0f526cd7d927199e | TetianaSob/Python-Projects | /test_Unit_Testing.py | 965 | 4.15625 | 4 | # test_Unit_Testing.py
import unittest
from Unit_Testing import circle_area
from math import pi
#create a class from the subclass
class TestCircleArea(unittest.TestCase):
def test_area(self):
#Test areas when radius >= 0
self.assertAlmostEqual(circle_area(1), pi)
self.assertAlmostEqual(circle_area(0), 0)
self.assertAlmostEqual(circle_area(2.1), pi * 2.1**2)
# self.assertAlmostEqual(circle_area(1), pi) - the assertAlmostEqual method the first value will be the output
# of the circle area function and the second value will be the correct answe
# the python unittest framework will compaire these 2 values and if they are
# correct to the 7 dessimal places. It will asume they are equal.
# self.assertAlmostEqual(circle_area(0), 0)- check the function with the cirlce radiaus 0
# and the circle radiaus '2.1'
#if one of these registers fail the python will register the 'F' fail. |
844356a2192778c71be640abf926993895cb23c8 | jameswmccarty/PythonChallenge | /31.py | 1,767 | 3.625 | 4 | """
http://www.pythonchallenge.com/pc/ring/grandpa.html
title: Where am I?
photo: http://www.pythonchallenge.com/pc/ring/grandpa.jpg
(shows a rock on a lake)
Next link: http://www.pythonchallenge.com/pc/rock/grandpa.html
username: island
password: country
Searching for 'Grandfather's Rock'
http://www.kosamui.com/lamai-beach/hinta-hinyai.htm
Island is kohsamui
Country is thailand
<!-- short break, this ***REALLY*** has nothing to do with Python -->
http://www.pythonchallenge.com/pc/rock/grandpa.html
"That was too easy, you are still on 31..."
Title: UFOs
<img src="mandelbrot.gif" border="0">
<window left="0.34" top="0.57" width="0.036" height="0.027"/>
<option iterations="128"/>
"""
from PIL import Image
from PIL import ImageOps
def calcpoint(x, y, imax):
i = 0
x0 = x
y0 = y
while x*x + y*y <= 4. and i < imax:
t = x*x - y*y + x0
y = 2.*x*y + y0
x = t
i += 1
return i
xres = 640
yres = 480
xmin = 0.34
width = 0.036
ymin = 0.57
height = 0.027
#im = Image.new('RGB', (640,480))
im = Image.new('L', (640,480))
#pal = img.getpalette()
sp = im.load()
for x in range(xres):
for y in range(yres):
x0 = xmin + x/xres*(width)
y0 = ymin + y/yres*(height)
z = calcpoint(x0, y0, 127)
#sp[x,y] = (pal[z*3],pal[z*3+1],pal[z*3+2])
sp[x,y] = z
im = ImageOps.flip(im)
#im.show()
img = Image.open("mandelbrot.gif")
px = img.load()
#img.show()
diffs = []
mine = im.getdata()
orig = img.getdata()
for i in range(len(mine)):
if mine[i] != orig[i]:
diffs.append(orig[i] - mine[i])
print(len(diffs))
print(diffs)
out = Image.new('L', (23,73))
op = out.load()
for i in range(23):
for j in range(73):
op[i,j] = 0 if diffs[j*23+i] < 0 else 255
out.show() # https://en.wikipedia.org/wiki/Arecibo_message
|
9c5ef28e14a88197a7ebd2dfa599b4924d437a9f | Radek011200/Wizualizacja_danych | /Zadania_lista_nr5/5_9.py | 246 | 3.515625 | 4 | def parzyste(wyraz):
for index in range(0,len(wyraz),2):
yield wyraz[index]
prz=parzyste("Zadanie")
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
|
e03075ba7bc4578199b2ecab6da5f1e59695d872 | valentina-zhekova/Hack-Bulgaria-Programming-101 | /week0/part 2/sudokuSolved.py | 1,239 | 3.984375 | 4 | def sudoku_solved(sudoku):
return (correct_matrix(sudoku) and check_rows(sudoku)
and check_columns(sudoku) and check_3x3(sudoku))
def check_rows(matrix):
m0 = matrix
m = list(map(lambda x: condition(x), m0))
if len(set(m)) == 1 and m[0]:
return True
return False
def check_columns(matrix):
flag = True
s = []
i = 0
j = 0
while i < len(matrix):
if not flag:
return False
while j < len(matrix):
s.append(matrix[j][i])
j += 1
flag = flag and condition(s)
s = []
j = 0
i += 1
return flag
def check_3x3(matrix):
m = []
for row in matrix:
m += row
s = []
flag = True # to check for wrong 3x3 square
for i in [0, 3, 6, 27, 30, 33, 54, 57, 60]:
if not flag:
return False
s = m[i:i + 3] + m[i + 9:i + 12] + m[i + 18:i + 21]
flag = flag and condition(s)
s = []
return flag
def condition(lst):
l = list(map(lambda x: str(x), sorted(lst)))
return ''.join(l) == "123456789"
def correct_matrix(matrix):
m = list(map(lambda x: len(x), matrix))
return m[0] == len(matrix) and len(set(m)) == 1
|
ed639ec272a6fd484a007002f7a95d300f416f11 | Zovengrogg/ProjectEuler | /Euler37_TrancatablePrimes.py | 816 | 3.671875 | 4 | # Truncatable Primes https://projecteuler.net/problem=37
from math import sqrt
def isPrime(n):
if n > 1:
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
return False
answers = []
for n in range(11, 1000001, 2):
if not isPrime(n):
continue
digits = str(n)
truncatable = True
newPrimeRight = digits
newPrimeLeft = digits
for index in range(1, len(digits)):
newPrimeRight = newPrimeRight[1:]
newPrimeLeft = newPrimeLeft[:-1]
if not isPrime(int(newPrimeRight)) or not isPrime(int(newPrimeLeft)):
truncatable = False
break
if truncatable:
answers.append(n)
total = 0
for a in answers:
total += a
print(total) |
35d4b96ab956d7fea3d88b1d8a640cc97ab4e68e | Naheuldark/Codingame | /Puzzles/Easy/AChildsPlay.py | 1,124 | 3.625 | 4 | import sys
import numpy as np
def is_obstacle(m, pos):
return m[pos[0]][pos[1]] == '#'
w, h = [int(i) for i in input().split()]
n = int(input())
m = []
for i in range(h):
line = input()
m.append(line)
if 'O' in line:
# Found initial pos
pos = np.array([i, line.index('O')])
# Initial direction
direction = np.array([-1,0])
# Rotation matrix
turn_clockwise = np.array([[0,-1],[1,0]])
# Walk m and remember
walks = []
first_loop = True
leftout = 0
for i in range(n):
while is_obstacle(m, pos + direction):
direction = direction @ turn_clockwise
for x in walks:
#print(x[0], pos, x[1], direction)
if (x[0] == pos).all() and (x[1] == direction).all():
if first_loop:
first_loop = False
leftout = len(walks)
walks = []
else:
pos = walks[(n-leftout)%len(walks)][0]
print( "%(x)d %(y)d" %{"x": pos[1], "y": pos[0]} )
exit(0)
walks.append([pos, direction])
pos = pos + direction
print( "%(x)d %(y)d" %{"x": pos[1], "y": pos[0]} ) |
1468e6e47cabf7cde204bda9417785b8059a4a8b | Sheretluko/LearnPython_homeworks | /lesson3/3_2_datetime.py | 638 | 3.96875 | 4 | # Напечатайте в консоль даты: вчера, сегодня, 30 дней назад
# Превратите строку "01/01/25 12:10:03.234567" в объект datetime
from datetime import datetime, date, time, timedelta
dt_now = datetime.now()
print(f"Сегодня: {dt_now.strftime('%d.%m.%Y')}")
print(f"Вчера: {(dt_now - timedelta(days = 1)).strftime('%d.%m.%Y')}")
print(f"30 дней назад: {(dt_now - timedelta(days = 30)).strftime('%d.%m.%Y')}")
date_before = '01/01/25 12:10:03.234567'
date_after = datetime.strptime(date_before, '%m/%d/%y %H:%M:%S.%f')
print(date_before)
print(date_after)
|
09f51b5d201473b3b4ecfc529154337a2fd9f740 | leiz2192/Python | /exercise/permutations/permutations.py | 611 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
if not nums:
return [[]]
nums_size = len(nums)
if nums_size == 1:
return [nums]
res = []
for i in range(nums_size):
for j in self.permute(nums[:i] + nums[i+1:]):
res.append([nums[i]] + j)
return res
def main():
print(Solution().permute([1, 2]))
print(Solution().permute([1, 2, 3]))
if __name__ == '__main__':
main()
|
906da6df99ea8fcb8d19fea549e5c88b083af69f | avikd1001/TrainingSDET | /Python/activity2_4.py | 352 | 4.25 | 4 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
def fibo (num):
if num <= 1:
return num
else:
return (fibo(num-1) + fibo (num-2))
userInput = int(input("Enter the desired number to generate the fibonacci series: "))
for i in range(userInput):
print(fibo(i)) |
54b7cca3aa91ac93ddb4755f93ebb6d6dd22c130 | HaiZukon/HaiZuka-1 | /Files/Gon.py | 140 | 3.796875 | 4 | print(a)
b = []
for i in range(len(a)):
c = []
c.append(a[i])
b.append(c)
print(b)
print(b[0][0])
print(b[1][0])
print(b[2][0])
|
b6c5a50aea10b14f8a278ff10524b38bd0bf2f25 | lekhav/LC-practice | /String/Reverse String .py | 1,118 | 3.546875 | 4 | class Solution:
def reverseString1(self, s):
# O(2N) time; O(N) space
# Append all characters to a stack; Pop them and add them to result
res = [] # EXTRA SPACE SOLUTION
l = len(s)
for i in range(l):
res.append(s.pop())
return res
def reverseString2(self, s):
# 2 Pointer Approach,
# O(N) time ; O(1) space
l = 0
r = len(s)-1
while l < r:
# temp = s[l]
# s[l] = s[r]
# s[r] = temp
s[l], s[r] = s[r], s[l]
l+=1
r-=1
return s
def reverseString3(self, s):
# Recursive stack approach
# O[N] Time, O[N] Stack-Space
return self.helper(s, [])
def helper(self, s, result):
if len(s) == 0:
return result
result += [s[-1]]
self.helper(s[:len(s)-1], result)
obj = Solution()
print(obj.reverseString1(s= ['h', 'e', 'l', 'l', 'o']))
print(obj.reverseString2(s= ['h', 'e', 'l', 'l', 'o']))
print(obj.reverseString3(s= ['h', 'e', 'l', 'l', 'o'])) |
20426eba9a85ee81eb6817942e50fe6f05652eb4 | SZTerminator/Unic-Word-finder | /Word_finder.py | 2,378 | 3.734375 | 4 | def clear_from_simbols(data):
import re
data = data.replace("-","_") # Спасаем дефисы для некоторых слов как "как-нибудь" или "fourty-five"
regex = re.compile('\W') # Хз зачем но без этого не работает
data = regex.sub(' ',data) # Собственно удаление спец. символов
data = data.replace("_","-") # Возвращаем дефисы на своё место
return data
def return_unic(data):
data = set(data)
data = list(data)
return data
def delete_numbers(data):
words = []
for i in data:
if i.isdigit():
continue
words.append( i )
return words
def read_from_file(name):
'''Функция принимает имя файла,
который будет про0чтён и из которого составит и
вернёт список уникальных слов
name - задаёться полным именем и его директории:
data.txt
texsts\data.txt
C:\texsts\data.txt
'''
with open(name,"r") as g: # Открываем
data = g.read() # Читаем и запоминаем
return data
def return_unic_words(name):
data = read_from_file(name)
data = data.replace('_',' ') # Убираем исключение _
data = data.lower() # Переводим в нижний регистр так как "Мы" и "мы" - одно и тоже слоово
data = clear_from_simbols(data)
data = data.split() # Делаем из строки список
data = return_unic(data)
data = sorted(data)
data = delete_numbers(data)
return data
def save_to_file(name,list_of_words):
with open(name,'w') as f:
words = len(list_of_words)
f.write('Количество уникальных слов ' + str(words) + '\n')
f.write("========================================" + '\n')
for i in list_of_words:
f.write(i + '\n')
# from library import save_to_file
# from library import return_unic_words
# from library import read_from_file
data = return_unic_words('data.txt')
save_to_file('count.txt', data)
|
c9d95a53a7d91e4b1b5e869087d44c05b0b26c85 | theprogrammer1/Random-Projects | /watercheck.py | 425 | 4.09375 | 4 | # Just a simple water check!:)
print("Welcome to WaterCheck")
goal = input("How much ml of water do you plan to drink today? ")
print("Come after a day and then enter how much you drank")
water = input("How much ml of water have you drank today? ")
if goal > water:
print("You have completed your goal")
if goal < water:
print("You have not completed your goal")
if goal == water :
print("You have completed your goal")
|
88179acc181529fde3c01de45ba26d0f0bb764d1 | actlienholding/ttrpy | /ttrpy/util/midpri.py | 930 | 3.953125 | 4 | # Author: joelowj
# License: Apache License, Version 2.0
import pandas as pd
def midpri(df, high, low, midpri, n):
"""
The Midprice returns the midpoint value from two different input fields. The
default indicator calculates the highest high and lowest low within the look
back period and averages the two values to return the Midprice.
Parameters:
df (pd.DataFrame): DataFrame which contain the asset information.
price (string): the column name for the price of the asset.
midpri (string): the column name for the calculated midprice values.
n (int): the total number of periods.
Returns:
df (pd.DataFrame): Dataframe with the midprice calculated.
"""
midpri_hh = df[high].rolling(window=n).max()
midpri_ll = df[low].rolling(window=n).min()
df[midpri] = (midpri_hh + midpri_ll) / 2
df = df.dropna().reset_index(drop=True)
return df
|
a2acb8ad8dd2d999c86e84eaef6b23ab99cc3db1 | microease/Python-Tip-Note | /013ok.py | 457 | 3.75 | 4 | # 光棍们对1总是那么敏感,因此每年的11.11被戏称为光棍节。小Py光棍几十载,光棍自有光棍的快乐。让我们勇敢地面对光棍的身份吧,现在就证明自己:给你一个整数a,数出a在二进制表示下1的个数,并输出。
# 例如:a=7
# 则输出:3
# bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
a = 7
n = 0
for i in bin(a):
if i == "1":
n += 1
print(n)
|
ec4e9797da063bee52346b31f5fbe680367d5e55 | alexandraback/datacollection | /solutions_2700486_0/Python/bigOnion/B.py | 3,245 | 3.546875 | 4 | directory = 'C:/users/hai/my projects/google code jam/2013/round1b/B/'
from decimal import Decimal
from fractions import Fraction
def factorial (n):
s = 1
for i in range(1,n+1):
s *= i
return s
def binomial (n,k):
if k > n:
print ('oh no!')
return 0
return factorial (n) // (factorial(k)*factorial(n-k))
def solve (f_in, f_out):
T = int(f_in.readline())
for testcase in range(1,T+1):
#print ('\ntestcase = ' , testcase)
N, X, Y = [int(x) for x in f_in.readline().split()]
result = calc (N,X,Y)
f_out.write('Case #' + str(testcase) + ': ' + str(result) + '\n')
def calc (N, X, Y, debug=0):
if debug:
print ('N = ', N)
print ('X,Y = ',X,Y)
if Y < 0:
return 0
if (X+Y) % 2 == 1:
return 0
l = 1
while sum(range(1,l+1)) <= N:
l += 2
if debug:
print ('l = ',l)
if abs(X) + abs(Y) +1 < l:
return 1
if abs(X) + abs(Y) + 1 > l :
return 0
if X == 0:
if sum(range(1,Y+2)) <= N:
return 1
else:
return 0
n0 = N - sum(range(1,l-1))
if debug:
print ('n0 = ',n0)
## if n0 > (l-1):
## print ('kuku1')
## leftovers = n0 - 2 * (n0 - (l-1))
## height = Y - (n0 - (l-1))
## else:
## print ('kuku2')
## leftovers = n0
## height = Y
## print ('leftovers = ', leftovers)
## print ('height =', height)
## s = 0
## for i in range(height+1, leftovers+1):
## s += binomial (leftovers, i)
## print ('s = ',s)
if (Y+1) + (l-1) <= n0:
if debug:
print ('here')
return 1
if debug:
print ('kuku')
s = 0
for i in range(Y+1, n0+1):
s += binomial (n0, i)
if debug:
print ('s = ',s)
#return make_decimal_string(Fraction(s, 2**n0))
return float(Fraction(s, 2**n0))
#return Decimal(s) / Decimal(2**leftovers)
def make_decimal_string(frac):
nom_high = 999999999
nom_low = 1
while nom_high - nom_low > 1:
#print (nom_high, nom_low)
nom_mid = (nom_high + nom_low)//2
if Fraction(nom_mid, 1000000000) > frac:
nom_high = nom_mid
else:
nom_low = nom_mid
assert Fraction (nom_mid,1000000000) - frac < Fraction(1,1000000)
return '0.' + ('0'*10 + str(nom_mid))[-9:]
def main_run():
import os
import time
filenames = [x for x in os.listdir (directory)]
filenames = [x for x in filenames if x.endswith('.in')]
l1 = [(os.stat(directory+x).st_mtime, x) for x in filenames]
chosen_filename = sorted(l1)[-1][1][:-3]
print ('Directory : ', directory)
print ('Chosen Filename : ',chosen_filename)
print()
print ('Start : ', time.ctime())
print()
f_in = open(directory+chosen_filename+'.in')
f_out = open(directory+chosen_filename+'.out', 'w')
solve(f_in,f_out)
f_in.close()
f_out.close()
print ()
print ('End : ', time.ctime())
main_run()
|
8cab57cf42c0c43ee2d59c5f1201b60c4e40549b | huangyisan/lab | /python/jiechen.py | 285 | 3.578125 | 4 | from functools import reduce
from operator import mul,iadd
def fact(n):
return reduce(lambda x,y:x*y, range(1,n+1))
print(fact(10))
def factmul(n):
return reduce(mul, range(1, n+1))
print(factmul(10))
def addadd(n):
return reduce(iadd, range(1,n+1))
print(addadd(100)) |
582021fbdf2bb065bc4d8064f832fe97d52e4578 | mshsarker/PPP | /Turtle Graphics/66.py | 484 | 3.921875 | 4 | ## My solutions to the 150 Challenges by Nichola Lacey
## Get this wonderful book to know with the explanations and quick tips.
## 066 Draw an octagon that uses a different colour (randomly selected from a list of six possible colours) for each line.
import random
import turtle
turtle.pensize(3)
for i in range(0,8):
clr = random.choice(["red", 'black', 'green', 'purple', 'blue', 'yellow'])
turtle.color(clr, 'red')
turtle.right(45)
turtle.forward(100)
turtle.exitonclick() |
31626ec8578aadd9b28572bb25785dcd51b82771 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise15_13.py | 373 | 3.921875 | 4 | def main():
s = input("Enter a string: ").strip()
print("The uppercase letters in " + s + " is " + str(countUppercase(s)))
def countUppercase(s):
return countUppercaseHelper(s, len(s) - 1)
def countUppercaseHelper(s, high):
if high < 0:
return 0
else:
return countUppercaseHelper(s, high - 1) + (1 if s[high].isupper() else 0)
main()
|
def53c33a41fb92bac0462c756393b1ca2872e4c | Tquran/Python-Code-Samples | /M4P2BTQ.py | 307 | 4.25 | 4 | # Tamer Quran
# 7/29/2021
# This program prints each number and its square on a new line
# 12, 10, 32, 3, 66, 17, 42, 99, 20
myList = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in myList:
print(i ** 2)
# I squared each item on the list by using ** and the program did the rest by going down the list.
|
6f80d1132e651ae834415d6fec2432290c392828 | HIT-jixiyang/offer | /不用成分算等差数列.py | 322 | 3.734375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
self.s=0
self.add(n)
return self.s
def add(self,n):
self.s = self.s + n
return n > 0 and self.add(n - 1)
if __name__ == '__main__':
S=Solution()
print(S.Sum_Solution(5))
|
b4862baea3871ebb8a2240e5e1794627c936b42b | nikpil/Python-HW2 | /HW2_3.py | 785 | 4.125 | 4 | number = int(input("Введите неомер месяца: "))
if number <= 12 and number >= 1:
month_dict = {1: 'Зима',
2: 'Зима',
3: 'Весна',
4: 'Весна',
5: 'Весна',
6: 'Лето',
7: 'Лето',
8: 'Лето',
9: 'Осень',
10: 'Осень',
11: 'Осень',
12: 'Зима'}
month_list = list(month_dict.values())
for i, el in enumerate(month_list):
if i == number-1:
print(f"Решение через 'list'. Это {month_list[i]}")
print(f"Решение через 'dict'. Это {month_dict[number]}")
|
afc2b21d9c431313e976515e2f07166498b947e5 | wangxiao4/programming | /Num9/_9_17_AnimationDemo.py | 993 | 3.734375 | 4 | from tkinter import *
class AnimationDemo:
def __init__(self):
window=Tk()
window.title("Animation demo")
width=250
height=150
canvas=Canvas(window,width=width,height=height)
self.testText_x=10
self.testText_y=10
testText=canvas.create_text(self.testText_x,self.testText_y,text="天上飘着五个字",tags="text")
canvas.pack()
x_f=1
y_f=1
while True:
x_temp=1
y_temp=1
if self.testText_x>=width or self.testText_x<=0:
x_f=x_f*-1
if self.testText_y>=height or self.testText_y<=0:
y_f=y_f*-1
self.testText_y=self.testText_y+y_temp*y_f
self.testText_x=self.testText_x+x_temp*x_f
canvas.move("text",x_temp*x_f,y_temp*y_f)
canvas.after(10)
canvas.update()
print(self.testText_x,self.testText_y)
window.mainloop()
AnimationDemo() |
cdf3b373b7c30d16e6a1d424a638a74e3583e2f6 | ishtiaq2/python | /beginner/Bird.py | 353 | 3.84375 | 4 | class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super(Bird,self).__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")
a1 = Animal()
a1.whatIsThis()
|
f30f2b63215fc092ed5d7edd92e11dddb154a618 | Aborigenius/python | /List Comprehensions/listComprehension.py | 140 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 16:48:27 2020
@author: spiridiv
"""
lst = []
lst=[x**3 for x in range(1,11)]
print(lst) |
4513cdbfe3703945e0ab9e023858b5705ca41635 | Djdev7/NewGame | /engine.py | 1,035 | 3.515625 | 4 | #The character starts in a dark room.He notices that he is strapped to a table.
#------------------------------------------------------------------------------#
#This is where i was place what needs to happen at this point
# 1. Opening scene
# 2. How to play
# 3. Look at surroundings
# 4. Descision tree
# 5. Move to next node
# 6. Display available nodes
# 7. Display all avaiable commands
# 8. View contents of inventory
#------------------------------------------------------------------------------#
# here we are gonna make the englne where the game state is.
class Engine(object):
#this dict will contain all the room description text
nodesd = {key: Value}
# This function will display the current nodes discription.
def node_descrip(self, node):
print Engine.nodes[]
#this function will call the help dialog
def Help():
if Userinput == "help" or "Help":
print ""
#this function will move the engine to the next node
def next_node(self):
if node_complete == True:
|
795941231f9bb1840957baeb164342d70dbd66b3 | godwinreigh/web-dev-things | /programming projects/python projects/tkinter practice/7. Build an Image Viewer App.py | 2,748 | 3.546875 | 4 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("My simple image viewer")
root.iconbitmap('C:/Users/godwi/Downloads/myicons/Sbstnblnd-Plateau-Apps-image-viewer.ico')
#creating images
my_img1= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/angry_reaction.jpg"))
my_img2= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/getoutsmarted_reaction.jpg"))
my_img3= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/heart_reaction.jpg"))
my_img4= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/hehe_reaction.jpg"))
my_img5= ImageTk.PhotoImage(Image.open("C:/Users/godwi/Desktop/collected pictures from fb/reactions/love_reaction.jpg"))
image_list=[my_img1,my_img2,my_img3,my_img4,my_img5]
my_label= Label(image=my_img1)
my_label.grid(row=2,column=0,columnspan=3)
#functions
def forward(image_number):
global my_label
global button_forward
global button_backward
#my_label.grid_forget() is an internal function to get rid something
my_label.grid_forget()
my_label = Label(image=image_list[image_number-1])
# we need to update it so it you can click na button more than once
button_forward = Button(root, text=">>", command=lambda: forward(image_number +1))
button_backward = Button(root, text="<<", command=lambda: back(image_number - 1))
#disabling the button for the last part
if image_number == 5:
button_forward = Button(root, text='>>', state=DISABLED)
my_label.grid(row=2, column=0, columnspan=3)
button_backward.grid(row=1, column=0)
button_forward.grid(row=1, column=2)
def back(image_number):
global my_label
global button_forward
global button_backward
my_label.grid_forget()
my_label = Label(image=image_list[image_number - 1])
# we need to update it so it you can click na button more than once
button_forward = Button(root, text=">>", command=lambda: forward(image_number + 1))
button_backward = Button(root, text="<<", command=lambda: back(image_number - 1))
if image_number == 1:
button_backward = Button(root,text="<<", state= DISABLED)
my_label.grid(row=2, column=0, columnspan=3)
button_backward.grid(row=1, column=0)
button_forward.grid(row=1, column=2)
#creating buttons
button_forward=Button(root, text= '>>', command=lambda: forward(2))
button_backward=Button(root, text= '<<', command=back, state= DISABLED)
button_exit=Button(root, text="EXIT PROGRAM", width=20, command=root.quit)
button_backward.grid(row=1,column=0)
button_exit.grid(row=1,column=1)
button_forward.grid(row=1,column=2)
root.mainloop() |
2b7bec056a4eaa735d35ae6cda1cbd7f8131d985 | leecheng28/COMP20008-2016S1 | /create-datafile.py | 2,111 | 3.609375 | 4 | # This Python file uses the following encoding: utf-8
# Data Pre-processing and Integration
# Author: Li Cheng. ID: 688819.
import csv
# Procedures for data pre-processing---
# Read data, from the business-count.csv file, in column C(CULE small area) and column X(Total establishments in block), to store the number of business establishments in each suburb into a dictionary.
# There are no duplicates of suburb in the dictionary N. ie. each suburb occurs once
# An example: dict_N={“CBD”: 1, “Carlton”:2, "Brunswick":5555, …}
# categorise data baesd on each suburb. In the form: N={“CBD”: 1, “Carlton”:2, "Brunswick":5555, …}
dict_N={}
list_suburb_N=[]
list_count_N=[]# extract useful data from file
with open('business-count.csv') as csvfile:
reader = csv.DictReader(csvfile)
# get the list of values in list form. eg.['', '', '', ...]
for column in reader:
list_suburb_N.append(column['CLUE_small_area'])
list_count.append(column['Total_establishments_in_block'])
idx_N=0 # index of current suburb in the list of suburb
for suburb in list_suburb_N:
if suburb not in dict_N:
dict_N[suburb]=int(list_count[idx_N])
else: # suburb already exists in the dictionary
dict_N[suburb]+=int(list_count[idx_N])
idx_N+=1
print dict_N
# now do the same step of categorising date for unemploy-rate.csv file
# An example of required dictionary: dict_UR={UR= {“CBD”: 0.05, “Carlton”: 0.025, 'Brunswick': 0.01, …}}
'''
dict_UR={}
list_suburb_UR=[]
list_average_UR=[]
with open('employ-rate.csv') as csvfile:
reader = csv.DictReader(csvfile)
for column in reader:
list_suburb_UR.append(column['Statistical Area Level 2 (SA2)'])
list_average_UR.append(column['Average'])
idx_UR=0 # index of current suburb in the list of suburb
for suburb in list_suburb_UR:
if suburb not in dict_UR:
dict_UR[suburb]=int(list_average_UR[idx_UR])
else: # suburb already exists in the dictionary
dict_UR[suburb]+=int(list_average_UR[idx_UR])
idx_UR+=1
print dict_UR
'''
# Prodecures for data integration--- |
5a7f7c23c8b0e9eb82f5f3b2d28852d51c9b12a2 | srikanthpragada/PYTHON_30_AUG_2021 | /demo/ds/common_chars_v2.py | 135 | 3.875 | 4 | st1 = "Abcdefde"
st2 = "dexyzd"
chars = []
for c in st1:
if c not in chars and c in st2:
print(c)
chars.append(c)
|
ec27ff8435a449f20aafc26496b6a3487456e4bc | dogbyt3/Data-Science-Projects | /Evolutionary Algorithms/pso.py | 8,497 | 3.796875 | 4 | """
* File: pso.py
* Purpose: This module contains the declaration and implementation of the
particle swarm optimization algorithm for knapsacks.
Example Use:
from pso.py import *
from knapsack_generator.py import *
# create a knapsack generator
knapsack_gen = knapsack_generator(None, 100, 100)
# create a knapsack problem from the generator
knapsack_problem = knapsack_gen.next()
To run canonical pso algorithm:
knapsack_contents = pso(knapsack_problem)
The search algorithm returns a list of contents represented by
{0, 1} where a '1' indicates that the item is in the knapsack, and
'0' otherwise.
"""
from copy import *
from random import *
from knapsack import *
# class representing PSO particle for a knapsack problem
class particle(object):
def __init__(self, knapsack, index, swarm):
self.knapsack = knapsack
self.index = index
self.pbest = knapsack
self.swarm = swarm
self.cognition = swarm.population_cognition
self.social = swarm.population_social
self.inertial = swarm.population_inertial
self.velocity = 0
self.max_velocity = len(self.knapsack.content_list)-1
# f(n) that determines fitness of an individual
# Maximizes the values of the knapsack contents by returning the value
# of the items in the pack, unless the weight violates the knapsack
# capacity contraint.
def fitness(self, knap):
capacity = 0
value = 0
for i in range(0, len(knap.content_list)):
if knap.content_list[i] == 1:
capacity += knap.weights[i]
value += knap.values[i]
if capacity > knap.capacity:
return 0
else:
return value
def update_velocity(self):
#print 'update velocity knapsack['+str(self.index)+']'
# Note:
# Using the fitness f(n) that returns a knapsack value returns
# high numbers, i.e. > 150, and more fit the knapsack soln is,
# the higher it is. But we need this to be proportionate to the
# length of the content_list.
global_distance = (self.fitness(self.swarm.global_best.knapsack) -
self.fitness(self.knapsack))
personal_distance = (self.fitness(self.pbest) -
self.fitness(self.knapsack))
# create a global ratio of fitness
if self.fitness(self.knapsack) != 0 and \
(self.fitness(self.swarm.global_best.knapsack))!= 0:
global_ratio = 1 - (float(self.fitness(self.knapsack)) /
(self.fitness(self.swarm.global_best.knapsack)))
else:
global_ratio = 1
# create a personal ratio
if self.fitness(self.knapsack) != 0 and \
(self.fitness(self.knapsack)) != 0:
personal_ratio = 1 - (float(self.fitness(self.knapsack)) /
(self.fitness(self.pbest)))
else:
personal_ratio = 1
# clamp the ratios. Ratio will be > 1 when best is worse than current
if global_ratio > 1:
global_ratio = 0.1
if personal_ratio > 1:
personal_ratio = 0.1
# create a relationship between the distance and the knapsack by
# taking a percentage of the global best's knapsack
# This creates a velocity to be used as a splicing point that is a
# percentage of the
# global best
self.velocity = self.max_velocity * global_ratio
# adjust the velocity by the intertial constant
self.velocity = self.inertial * self.velocity
# calculate the cognition
cognition_distance = self.velocity * personal_ratio
cognition_calc = abs((self.cognition * random()) * (cognition_distance))
# adjust for sociality
social_distance = self.velocity
social_calc = abs((self.social * random()) * (social_distance))
self.velocity += (cognition_calc + social_calc)
# make certain we get an integer to use as an index
self.velocity = int(round(self.velocity))
# clamp it to within the content_list
if self.velocity > self.max_velocity:
self.velocity = self.max_velocity
elif self.velocity < 0:
self.velocity = 0
# particle method that updates the particle's position within the swarm
def update_position(self):
# pbest is pointing to knapsack, so before we update knapsack,
# make certain pbest retaints its
# values from knapsack
new_pbest = knapsack(self.knapsack.capacity, \
self.knapsack.weights, \
self.knapsack.values)
new_pbest.content_list = self.knapsack.content_list[:]
self.pbest = new_pbest
# take the velocity and use it to splice the content of the swarm's
# best with our contents
new_knapsack = knapsack(self.knapsack.capacity, \
self.knapsack.weights, \
self.knapsack.values)
new_knapsack.content_list = \
self.swarm.global_best.knapsack.content_list[:self.velocity] + \
self.knapsack.content_list[self.velocity:]
# now set the knapsack to the newly created knapsack
self.knapsack = new_knapsack
# update the local best if better
if self.fitness(self.knapsack) > self.fitness(self.pbest):
self.pbest = self.knapsack
# update the global best if its better
if self.fitness(self.knapsack) > \
self.fitness(self.swarm.global_best.knapsack):
self.swarm.global_best = self
# class representing PSO
class particle_swarm_optimization(object):
def __init__(self, knapsack_problem, population_size, population_cognition,\
population_social, population_inertial, max_iterations):
self.knapsack_problem = knapsack_problem
self.population_size = population_size
# cognition affects a particle's pbest influence on its movement
self.population_cognition = population_cognition
# social affects the swarms gbest influence on its movement
self.population_social = population_social
# intertial affects how much of the current partical velocity to account
self.population_inertial = population_inertial
self.population = []
self.global_best = None
self.max_iterations = max_iterations
# create the initial swarm
for i in range(0, population_size):
# create a knapsack instance
new = knapsack(self.knapsack_problem.capacity, \
self.knapsack_problem.weights, \
self.knapsack_problem.values)
new.addrandomcontents()
# create the swarm of particles
new_particle = particle(new, i, self)
self.population.append(new_particle)
# randomize the order of population
shuffle(self.population)
# create the initial global best
self.global_best = self.population[0]
# put the swarm in motion within the solution space
def fly(self):
for i in range(self.max_iterations):
for particle in self.population:
# update the particle's velocity
particle.update_velocity()
# update the particle's position
particle.update_position()
# Module Method that implements particle swarm optimization for knapsacks
# @param1: knapsack_problem generated from knapsack_generator
# @returns: returns list of values for x(i), where x(i) is an elem of {0, 1}
# Note:
def pso(knapsack_problem):
# population size
population_size = 100
population_cognition = 2
population_social = 2
population_inertial = 0.95
max_iterations = 100
swarm = particle_swarm_optimization(knapsack_problem, population_size, \
population_cognition,\
population_social, population_inertial,\
max_iterations)
swarm.fly()
return swarm.global_best.knapsack.content_list
|
2f3b8d8b825a6d52272950cd0febba23e1b65c10 | kongzhidea/leetcode | /Palindrome Linked List.py | 1,306 | 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 isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return True
if head.next == None:
return True
after = self.partition(head)
rev_after = self.reverse(after)
h = head
p = rev_after
while h != None:
if h.val != p.val:
return False
h = h.next
p = p.next
return True
def reverse(self,head):
if head == None or head.next == None:
return head
t = None
h = head
while h != None:
a = h.next
h.next = t
t = h
h = a
return t
def partition(self,head):
h = head
p = head
pre = h
while p.next != None and p.next.next != None:
p = p.next.next
pre = h
h = h.next
if p.next == None:
t = pre.next
pre.next = None
return t
if p.next != None:
t = h.next
h.next = None
return t |
62d6a28867972760988e7dd8140debce11c91647 | metinkanca/Lectures | /CNG111-IntroductionToComputerEngineeringConcepts/1-Assignment1/q8.py | 466 | 3.96875 | 4 | #$ python q8.py
n = int(raw_input("Enter> "))
i = 0.0
j = 1.0
print "Seeking the square root of {}".format(n)
while j*j < n:
j*=2.0
print "For j = {}, square of j exceeds {}".format(j, n)
g = 0.0
while True:
g = (i+j)/2
d = g*g-n
if d < 0:
d *= -1
if d < 0.001:
print "The square root of {} is {}".format(n, g)
break
print "i = {}, j = {}, g = {}".format(i,j,g)
if g*g < n:
i = g
elif g*g > n:
j = g
|
c58f7314cc792a5a8adcfa535fe6b1c9143e8b62 | schmit/sheepherding | /sheepherding/ai/ai.py | 2,441 | 3.984375 | 4 | from ..world.location import Location
from learning import QLearner
class AI:
def __init__(self, learner):
self.learner = learner
self.rewards = []
self.actions = []
self.done = False
# keep track of which sheep are done
self.sheep_done = set([])
def setLearner(self, learner):
self.learner = learner
def getAction(self, state):
return self.learner.getAction(state)
def evaluate(self, old_state, action, new_state):
reward = self.computeReward(old_state, action, new_state)
self.rewards.append(reward)
self.learner.incorporateFeedback(old_state, action, reward, new_state)
def computeReward(self, state, action, new_state):
return 0.0
def reset(self):
''' resets rewards and actions '''
total_reward = sum(self.rewards)
self.rewards = []
self.actions = []
self.done = False
self.sheep_done = set([])
return total_reward
class GoTargetAI(AI):
'''
The GoTargetAI implements the simple task of moving the dog itself to a target.
'''
def computeReward(self, state, action, new_state):
'''
Return 1 if dog is at target
'''
# convert to location so we can use distance function
own_location = Location(new_state.own_location[0], new_state.own_location[1])
distance_target = own_location.distance(new_state.target_location)
if distance_target < new_state.target_radius:
self.done = True
return 1.0
return 0.0
class HerdSheepAI(AI):
'''
The HerdSheepAI implements the task of moving sheep to the target.
'''
def computeReward(self, state, action, new_state):
'''
Return +1 for each sheep in target location
'''
# convert to location so we can use distance function
reward = 0
for k, sheep in enumerate(state.sheep_locations):
distance_target = Location(sheep[0], sheep[1]).distance(new_state.target_location)
# reward += 2.0 / (1.0 + distance_target)
if distance_target < new_state.target_radius and k not in self.sheep_done:
reward += 1
self.sheep_done.add(k)
# done if all sheep in target location
if len(state.sheep_locations) == len(self.sheep_done):
self.done = True
return reward
|
f6bbebecc87f42c17c540428e556938b4c289f97 | bran0144/mars-explorer-hackerank | /mars_explorer.py | 374 | 3.609375 | 4 | # Completed Hackerrank Mars Exploration
def marsExploration(s):
count = 0
n = 3
out = [(s[i:i+n]) for i in range(0, len(s), n)]
for sos in out:
if sos != "SOS":
if sos[0] != "S":
count +=1
if sos[1] != "O":
count +=1
if sos[2] != "S":
count +=1
return count
|
f68764f56102e25cc8cd5a58ff9cde21084f54b7 | annapeterson816/PythonPrograms | /Comp Sci Labs-2018/sierpinskiTriangle.py | 751 | 3.765625 | 4 | from Tkinter import *
def drawTriangle(p1,p2,p3):
the_canvas.create_polygon([p1,p2,p3], fill = 'blue', width=5)
def sierpinskiHelper ( n , p1, p2, p3 ) :
if n == 1 :
drawTriangle(p1, p2, p3)
else :
p4 = ((p1[0]+p2[0])/2,(p1[1]+p2[1])/2)
p5 = ((p2[0]+p3[0])/2,(p2[1]+p3[1])/2)
p6 = ((p3[0]+p1[0])/2,(p3[1]+p1[1])/2)
sierpinskiHelper ( n-1 , p1, p4, p6)
sierpinskiHelper ( n-1 , p4, p2, p5)
sierpinskiHelper ( n-1 , p6, p5, p3)
window= Tk()
window.title("Sierpinski Triangles")
the_canvas=Canvas(window, width=400, height=400)
the_canvas.grid(row=0, column=0)
sierpinskiHelper(5,(0,0),(200,400), (400,0))
#needs to be the last line on any code that you are trying to display
window.mainloop()
|
0a01138103efb14021b32168ecbe2af83a264873 | cuonghtran/mapreduce | /reducer.py | 966 | 3.515625 | 4 | #!/usr/bin/python
import sys
import collections
def main():
current_word = None
current_count = 0
word = None
top_counter = collections.Counter()
for line in sys.stdin:
# parse the input we got from mapper.py
word, count = line.strip().split('\t', 1)
# counting
top_counter[word] += int(count)
# convert count (currently a string) to int
try:
count = int(count)
except ValueError:
continue
if current_word == word:
current_count += count
else:
# if current_word:
# print(str(current_count) + "\t" + current_word)
current_count = count
current_word = word
# if current_word == word:
# print(str(current_count) + "\t" + current_word)
for con in top_counter.most_common(100):
print(str(con[1]) + "\t" + str(con[0]))
if __name__ == '__main__':
main()
|
5d4537eef6fb5723f830f374789092a822a680c3 | Threathounds/skripts | /single-char-xor.py | 1,725 | 3.96875 | 4 | #!/usr/bin/python3
# author: ide0x90
import sys
import re
if len(sys.argv) != 3:
sys.exit("Usage: single-char-xor.py <ciphertext_file> <keyword>")
# keyword is the plaintext we want to search for. Convert it to bytes
keyword = bytes(sys.argv[2], encoding="utf-8")
# create a regular expression matching pattern. The flag is assumed to be between curly brackets
regexp = bytes('{(.+?)}', encoding="utf-8")
# the keyword is assumed to be before the opening curly bracket
regexp = keyword + regexp
# open the file, read-only
ciphertext_file = open(sys.argv[1], "r")
# read everything in the file
ciphertext = ciphertext_file.read()
# remove newlines in ciphertext, they're annoying and are not part of the ciphertext
ciphertext = ciphertext.replace("\n", "")
# convert ciphertext from hex to bytes
ciphertext = bytes.fromhex(ciphertext)
# no plaintext at the moment, but declare it as bytes, encoding is UTF-8
plaintext = bytes("", encoding="utf-8")
# 256 keys we should concern ourselves with (the standard printable characters for UTF-8)
for i in range(0, 256):
# for each byte in the ciphertext
for byte in ciphertext:
# XOR the byte and the key, then convert to bytes, then add to plaintext
plaintext += bytes([byte ^ i])
# find the match using a regular expression search
flag = re.search(regexp, plaintext)
if flag:
sys.exit(f"Found: {flag.group(1)}")
# comment the above 2 lines, and uncomment the next 2 lines if you think the regular expression search is not working properly
# if keyword in plaintext:
# print(plaintext)
# clear the plaintext variable after XOR operation
plaintext = bytes("", encoding="utf-8")
sys.exit("Flag not found!")
|
7ad12f72a600be42492637dbfb301af022b23382 | Sharma30042000/DSA-_Solutions | /string/underscore.py | 665 | 3.8125 | 4 | def underscore(s,sub):
l=list(s.split(" "))
print(l)
ans=""
for i in l:
if len(i)<len(sub):
ans=ans+i+" "
if len(i)>len(sub):
if i[0:len(sub)]==sub and i[-len(sub):]!=sub:
ans=ans+"_"+sub+"_"+i[len(sub):]+" "
elif i[-len(sub):]==sub and i[0:len(sub)]!=sub:
ans=ans+i[0:len(i)-len(sub)]+"_"+sub+"_"+" "
elif i[0:len(sub)]==sub and i[-len(sub):]==sub:\
ans=ans+"_"+i+"_"+" "
else:
ans=ans+i+" "
return ans[0:len(ans)-1]
print(underscore("testthis is a testtest to see if testestest it works","test"))
|
512d9b462d910b048bd30c1b2107210192256ec2 | corinnelhh/code_eval | /easy/sum_of_integers.py | 529 | 4.03125 | 4 | # https://www.codeeval.com/open_challenges/24/
# Sum of Integers from File
# Challenge Description:
# Print out the sum of integers read from a file.
# Input sample:
# The first argument to the program will be a path to a filename
# containing a positive integer, one per line. E.g.
# 5
# 12
# Output sample:
# Print out the sum of all the integers read from the file. E.g.
# 17
import sys
with open(sys.argv[1], 'r') as f:
total = 0
for line in f.readlines():
total += int(line.strip())
print total
|
ba1297e6d8923a0f1b72380adec983d5cb3aef95 | monilj/RestAPITestingUsingPython | /ReadNWriteToJsonFilesNParsingUsinPythonMethods/ParseJsonString.py | 308 | 3.5625 | 4 | import json
courses = '{"name":"Rahul", "languages": [ "Java","Python"]}'
dict_course = json.loads(courses)
print(type(dict_course))
print(dict_course)
print(dict_course['name'])
print(dict_course['languages'])
list_languages = dict_course['languages']
print(list_languages[0])
print(list_languages[1])
|
7040abcffe4c60a2e72c91527852b9d623dd416f | evozkio/Aprendiendo | /agenda.py | 957 | 3.84375 | 4 | agenda=[["adolfo","11"],["pepe","12"],["ana","13"],["maria","44"]]
hacer = input("Añadir un numero /Consultar numero (A/C)")
while hacer != "FIN":
if hacer == "A":
nombre = input("Nombre :")
telefono = input("Telefono :")
agenda.append([nombre,telefono])
elif hacer == "C":
consultar = input("nombre o numero :")
if consultar == "nombre":
buscar = input("Que nombre :")
for nombre_numero in agenda:
if nombre_numero[0] == buscar:
print("Me has pedido el numero de {} y es {}".format(buscar,nombre_numero[1]))
elif consultar == "numero":
buscar = (input("Que numero :"))
for nombre_numero in agenda:
if nombre_numero[1] == buscar:
print("Me has pedido el numero de {} y es {}".format(buscar, nombre_numero[0]))
hacer = input("Quieres consultar,añadir o FIN (C/A/FIN)") |
d1dd9f17d2b0d6aee646c1bc078e73319089a923 | chandrikakurla/inserting-node-at-the-end-of-the-linkedlist | /linkedlist inserting node at the end of list.py | 1,099 | 4.03125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,Newnode):
if self.head is None:
self.head=Newnode
else:
lastnode=self.head
while True:
if lastnode.next is None:
break
else:
lastnode=lastnode.next
lastnode.next=Newnode
def printllist(self):
if self.head is None:
print('linked list is empty')
return
currentnode=self.head
while True:
if currentnode is None:
break
print(currentnode.data)
currentnode=currentnode.next
if __name__ == '__main__':
firstnode=Node("jack")
llist=LinkedList()
llist.insert(firstnode)
secondnode=Node("rose")
llist.insert(secondnode)
thirdnode=Node("lily")
llist.insert(thirdnode)
llist.printllist()
|
9fe3cc21f79061d82bb9194b2cf1abcead6b7d38 | Christoph5782/CS4830---Hack-Week-Project | /Chat-Room/client.py | 5,184 | 3.5625 | 4 | #----------Christopher Foeller-----Lab 3-----5/1/19----------#
# Description: This is a simple chat room using a server and client
# made using socket. It supports login/logout, making a
# new account, and sending messages to all users in the
# chat room. You can also look up all of the commands by
# typing help and exit the client by typing exit
#
# File: This is the file the the user will run to connect to the chat room
import socket
import select
import errno
import sys
import time
#-------------------------Establish Variables-------------------------#
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 14745
#------------------------------Functions------------------------------#
#-----Connect to Server-----#
def startup():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblocking(False)
return client_socket
#-----Handle User Input-----#
def runcommands(splitmsg, login, inputmsg):
#-----EXIT-----#
if splitmsg[0] == "exit":
print("Bye!")
sys.exit()
#-----HELP-----#
elif splitmsg[0] == "help":
print("LIST OF COMMANDS:")
print("\"login [username] [password]\" - Login to the server")
print("\"newuser [username] [password]\" - Make an account")
print("\"send [username] [message goes here]\" - Send a message to a certain user")
print("\"send all [message goes here]\" - Send a message to all users")
print("\"send [message goes here]\" - Send a message to all users")
print("\"logout\" - Logout of the server")
print("\"exit\" - Close client")
elif(login):
#-----SEND-----#
if splitmsg[0] == "send":
if len(splitmsg) < 2:
return login
message = splitmsg[1].encode("utf-8")
message_header = f"{len(message):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(message_header + message)
#-----WHO-----#
elif splitmsg[0] == "who":
message = "SERVER_COMMAND_WH0".encode("utf-8")
message_header = f"{len(message):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(message_header + message)
#-----LOGOUT-----#
elif splitmsg[0] == "logout":
print("You have logout.")
return False
#-----Inform User about double login attempt-----#
elif(splitmsg[0] == "login" or splitmsg[0] == "newuser"):
print("You are already login.")
#-----Invalid Commannd-----#
else:
print("Invalid command. Type \"help\" for list of commands")
else:
#-----LOGIN-----#
if splitmsg[0] == "login":
if len(splitmsg) < 2:
print("Try again entering \"login [username] [password]\".")
return False
username = inputmsg.encode("utf-8")
username_header = f"{len(username):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(username_header + username)
time.sleep(0.2)
a_header = client_socket.recv(HEADER_LENGTH)
a_length = int(a_header.decode("utf-8").strip())
a = client_socket.recv(a_length).decode("utf-8")
if(a == "T"):
print("Login Successful")
return True
else:
print("Username or Password is incorrect")
return False
#-----NEWUSER-----#
elif splitmsg[0] == "newuser":
if len(splitmsg) < 2:
print("Try again entering \"newuser [username] [password]\".")
return False
username = inputmsg.encode("utf-8")
username_header = f"{len(username):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(username_header + username)
time.sleep(0.2)
a_header = client_socket.recv(HEADER_LENGTH)
a_length = int(a_header.decode("utf-8").strip())
a = client_socket.recv(a_length).decode("utf-8")
if(a == "T"):
print("Account Created!")
return True
elif(a == "E"):
print("Username is already taken.")
return False
elif(a == "N"):
print("Sorry, please enter a password between 4 and 8 characters.")
else:
print("That didn't work. Please try again")
return False
else:
print("You need to login first. You can do that by typing \"login [username] [password]\".")
print("To make an account, type \"newuser [username] [password]\"")
return login
def runchatroom():
login = False
keepalive = True
while keepalive:
inputmsg = input(">")
if inputmsg:
splitmsg = inputmsg.split(" ", 1)
login = runcommands(splitmsg, login, inputmsg)
if login == False:
keepalive = False
try:
while True:
time.sleep(0.1)
outputmsg_header = client_socket.recv(HEADER_LENGTH)
if not len(outputmsg_header):
print("Connection closed by server")
sys.exit()
outputmsg_length = int(outputmsg_header.decode("utf-8").strip())
outputmsg = client_socket.recv(outputmsg_length).decode("utf-8")
print(outputmsg)
except IOError as e:
if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
print('Error Reading From Server', str(e))
sys.exit()
continue
except Exception as e:
print('Panicpanicpanicpanicpanicpanic', str(e))
sys.exit()
while True:
client_socket = startup()
runchatroom()
client_socket.shutdown(socket.SHUT_RDWR)
client_socket.close()
input("Type any key to start a new session!") |
6d32aa8d35a7b4bbeb64084cdd491cb9e523f238 | Mishrak/DevelopLogic | /Language/Python/AreaOfTriangle.py | 204 | 3.96875 | 4 | l_base = float(input('Enter the base value of the triangle = '))
l_height = float(input('Enter the height value of the triangle = '))
l_area = 0.5 * l_base * l_height
print('Area of triangle = ', l_area)
|
b92f6247d6a881e6af1a9b5bf51a3c9ce7b5db46 | DesislavaDimitrova/HackBulgaria | /week0/2-Python-harder-problems-set /05.Reduce_file_path.py | 376 | 3.625 | 4 | #Rturning the reduced version of the path
def reduce_file_path(path):
path = path.replace('//', 'd/')
path = path.split('/')
for index in range (0, len(path)):
if "d" in path:
path.remove('d')
if ".." in path:
i = path.index('..')
path.remove('..')
path = path[:i-2] + path[i:]
if '.' in path:
path.remove('.')
return '/' + "/".join(path)[:-1]
|
6e4f8a250ba650714d3db2244bf566358d848b74 | ksommerh94/MIT_Python | /exercise2/ps1b.py | 1,019 | 4 | 4 | import numpy
import pylab
from matplotlib import pylab
from pylab import *
# input variables
annual_salary=float(input("Enter your annual salary: "))
portion_saved=float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost=float(input("Enter the cost of your dream home: "))
semi_annual_raise=float(input("Enter the semiannual raise, as a decimal: "))
#for testing
# annual_salary=80000
# portion_saved=.1
# total_cost=800000
# semi_annual_raise=.03
# initialiazing variables
monthly_savings=(annual_salary/12)*portion_saved
portion_down_payment=0.25
r=0.04
month=0
current_savings=0
costDownPayment=total_cost*portion_down_payment
#monthly
while(current_savings<costDownPayment):
if month%6==0 and month!=0:
annual_salary+=annual_salary*semi_annual_raise
monthly_savings=(annual_salary/12)*portion_saved
current_savings+=current_savings*r/12
current_savings+=monthly_savings
month+=1
#print (current_savings)
print("Number of months: " + str(month))
|
2bba16e4235d64d56b5a18da1614d2299bbd18b4 | regnart-tech-club/programming-concepts | /course-2:combining-building-blocks/subject-4:all together now/topic-2:ETL/lesson-5.0:sum of squares puzzle.py | 268 | 3.640625 | 4 | # Using `map` and `reduce`,
# write a function or lambda, `sum_square`,
# that has one parameter, a list,
# and returns the sum of the squares of the elements of the list.
# For example, given the list [1, 2, 3], the function should return 14
# since 14 is 1 + 4 + 9.
|
e4bcf37656a7c7d208dea7645dcd724bb2ab38ed | kamit28/python-stuff | /src/com/amit/algo/sorting_algos.py | 1,447 | 4.09375 | 4 | #!/usr/bin/python
'''
partition method to find pivot.
to be used by quicksort
'''
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i + 1]
return i + 1
'''
The quicksort algorithm
'''
def quick_sort(arr, low, high):
if low < high:
pivot = partition(arr, low, high)
quick_sort(arr, low, pivot - 1)
quick_sort(arr, pivot + 1, high)
'''
The merge routine for merge sort
'''
def merge_lists(arr, low, mid, high):
n1 = mid - low + 1
n2 = high - mid
l_temp = [0] * n1
r_temp = [0] * n2
for i in range(0, n1):
l_temp[i] = arr[low + i]
for i in range(0, n2):
r_temp[i] = arr[mid + 1 + i]
i = 0
j = 0
k = low
while i < n1 and j < n2:
if l_temp[i] < r_temp[j]:
arr[k] = l_temp[i]
i += 1
else:
arr[k] = r_temp[j]
j += 1
k += 1
while i < n1:
arr[k] = l_temp[i]
i += 1
k += 1
while j < n2:
arr[k] = r_temp[j]
j += 1
k += 1
'''
The merge sort algorithm
'''
def merge_sort(arr, low, high):
if high > low:
mid = (low + high) / 2
merge_sort(arr, low, mid)
merge_sort(arr, mid+1, high)
merge_lists(arr, low, mid, high)
|
58d3faab933a79ecdb91f8992a12a5ca356d92d0 | htietze/capstone_lab8 | /bitcoin.py | 1,711 | 3.6875 | 4 | import requests
def main():
bitcoins = get_bitcoin_amount()
bitcoin_rate = get_current_BTC_rate()
# if it successfully returned a bitcoin rate, then it'll convert and print, otherwise alerts the user to an issue.
if bitcoin_rate:
converted = convert_BTC_to_USD(bitcoins, bitcoin_rate)
print(f'{bitcoins} bitcoin is equal to ${converted}, at a rate of {bitcoin_rate} dollars per bitcoin')
else:
print('Please try again later or check your network connection')
def get_bitcoin_amount():
# loops for validation, so if they enter something that breaks the float requirement, it'll keep going
# and only return once they do it right.
while True:
try:
btc = float(input('Enter bitcoin amount for conversion: '))
return btc
except ValueError:
print('Invalid amount entered, please try again.')
def get_current_BTC_rate():
# trys to get the BTC rate from online, then return the USD rate from that json
# If that fails due to the json response being different resulting in a key error, or there being no network connection
# which causes requests to raise a connection error exception, then it'll return false and let the user know it couldn't get the rate.
try:
data = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json').json()
USD_rate = data['bpi']['USD']['rate_float']
return USD_rate
except (KeyError, requests.exceptions.ConnectionError):
print('Bitcoin exchange rate could not be retrieved')
return False
def convert_BTC_to_USD(bitcoins, bitcoin_rate):
return bitcoins * bitcoin_rate
if __name__ == '__main__':
main() |
6ce691cf50d48836f4e45545c0fb2623cb7d8d0b | abboliwit/kompendietoliver | /kompendie/kompendie/kap.3/3.2.py | 397 | 4.0625 | 4 | male = ["erik","Lars","Karl","Anders","Johan"]
female = ["Maria","Anna","Margareta","Elisabeth","Eva"]
print(male[0],female[2],female[-1],male[1])# printar det första från men och tredje objektet från female sista från female och andra från male
male.pop(2)# tar bort ett namn
female.pop(0)
print(male)
print(female)
male.append("Oliver")#3.3 men den läger till mit namn
print(male) |
5c950b07317b5e0c5fbebecbc26f977947bc7ca3 | abocz/school-python | /cgi_script_web_form/loan_class.py | 1,068 | 3.765625 | 4 | class Loan(object):
# computes the remaining balance
def remainingBalance(self, month):
if month < 1:
raise ValueError("month must be positive")
elif month == 1:
return self.balance
else:
temp_bal = self.balance
return self.remainingBalance(month-1) + self.interestAccrued(month-1) - self.payment
# computes the interest accrued
def interestAccrued(self, month):
if month == 1:
return self.balance * self.monthly_rate
else:
return self.remainingBalance(month) * self.monthly_rate
# computes the monthly payment by dividing the annual rate by the term length
def computeMonthlyPayment(self):
self.payment = self.balance * ( self.monthly_rate / (1 - (1 + self.monthly_rate) ** (-self.term)))
return round(self.payment, 2)
# init function
def __init__(self, balance, term, rate):
if (balance <= 0) or (term <= 0) or (rate <= 0):
raise ValueError("can't be zero")
self.balance = balance
self.term = term
self.rate = rate
# convert annual rate to monthly rate, also casting it
self.monthly_rate = rate / (100.0 * 12)
|
189eb4a19c0410ff4a7e58528a562ff14be3f06a | Rawkush/Python_Programs | /basics/5. Function.py | 538 | 3.59375 | 4 | # creating a function
def function_name():
"explainatory string ius wriiten here, it is smilar to comment" # it is optional
print("created the function and inside the function cui=rrently")
return
#global variable
age=17
def newFunction():
age=12 ## this age is local variable
print(age)
return
newFunction()
print(age)
#to chanege the gl,obal variable
def changing():
global qge
age=12 ## this age is local variable
print(age)
return
changing()
print("global changed",age)
|
79d137cb283148c64fd87e8b4d1c156cf5f8dff6 | piyushgairola/daily_code | /max_subarray.py | 195 | 3.5 | 4 | def maxSubarray(nums):
curr_sum = ans = nums[0]
n = len(nums)
for i in range(1,n):
curr_sum = max(curr_sum+nums[i], nums[i])
ans = max(ans, curr_sum)
return ans |
49d9ccee5280cc91bd9da3c9565ed613e1833aad | JCharlieDev/Python | /Python Programs/TkinterTut/TkinterHello.py | 262 | 4.09375 | 4 | from tkinter import *
# Mostly everything is a widget
# Main Window
root = Tk()
# Creating label widget
myLabel = Label(root, text = "Hello world")
# Putting it on the screen
myLabel.pack()
# Event loop, loops the application to stay open
root.mainloop() |
67b4bd22df3c1036af38a66f73b03e4a6e87dd26 | scalpelHD/Study_python | /课堂/8.4传递列表.py | 1,095 | 3.546875 | 4 | def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg='Hello,'+name.title()+'!'
print(msg)
usernames=['jerry','lucy','megrite']
greet_users(usernames)
#在函数中修改列表
def print_models(unprintfed_designs,completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
"""
while unprinted_designs:
current_design=unprinted_designs.pop(0)
#模拟根据设计打印过程
print('Printing model:'+current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print('\nThe following models have been printed:')
for completed_model in completed_models:
print(completed_model)
unprinted_designs=['iphone case','robot pendant','dodecahedron']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
|
394a05ef47ccc494d517376a290af3bf6b1b700c | Orion3451/python_scripts_basicos | /examenes/0-examen_funciones_anidadas.py | 618 | 3.859375 | 4 | '''def division(num_uno, num_dos):
def validacion():
return num_uno > 0 and num_dos > 0
if validacion():
return num_uno / num_dos
else:
print ('No se puede dividir')
resultado = division(10,2)
print (resultado)'''
# APLICANDO CLOUSTER
def creando_funcion(num_uno, num_dos):
def validacion():
if num_uno > 0 and num_dos > 0:
return num_uno / num_dos
return validacion
def aplicando_funcion(funcion_enviada):
resultado = funcion_enviada()
print ('funcion exito-->{}'.format(resultado))
nueva_funcion = creando_funcion(10,2)
aplicando_funcion(nueva_funcion)
|
58d6dbc6a6e35ee7a746994fe0e847feb575c24a | K-AlfredIwasaki/job_hunting_made_easy | /startup_db_recommendation/data_collection_preprocessing/company_from_title.py | 2,046 | 3.984375 | 4 | def get_company_from_title(title):
"""
algorithm to extract a company name to tech cruch article title
"""
import re
# remove "word word word: "
regex_intro = re.compile(r'\w+(\s+\w+)*\s*:\s')
title = re.sub(regex_intro, "", title)
# remove ", word word word,"
regex_middle = re.compile(r',\s.+,')
title = re.sub(regex_middle, "", title)
# split the title by strong verb and keep the head
regex_verb = re.compile(r" (raise|land|grab|hire|march|cook|is|head|scoop|launch|step|aim|rocket|order|receive|get|bag|emerge|collect|pull|close|secure|take|tap|score|snare|snag|grab|nab|win)",
re.IGNORECASE)
title = re.split(regex_verb, title)[0].strip(" ")
# remove "word word word,"
regex_intro2 = re.compile(r'.+,\s')
title = re.sub(regex_intro2, "", title).strip(" ")
# count the number of spaces in the head
if count_word(title) == 1:
return title
elif count_word(title) == 2:
return two_words_check(title)
else:
# split the remained title by strong noun and keep the tail
regex_noun = re.compile(r" (marketplace|maker|juggernaut|system|finalist|alum|solution|dashboard|editor|restaurant|app|firm|rival|lender|site|startup|company|competitor|platform|network|service|leader|house|developer|retailer)",
re.IGNORECASE)
title = re.split(regex_noun, title)[-1].strip(" ")
if count_word(title) == 1:
return title
elif count_word(title) == 2:
return two_words_check(title)
else:
#
title = title.split("$")[0]
title = title.split("Series")[0]
regex_lead = re.compile(r"\s[Ll]eads\s",
re.IGNORECASE)
title = re.split(regex_lead, title)[-1].strip(" ")
if count_word(title) == 2:
return two_words_check(title)
else:
return title
def count_word(title):
import re
regex_space = re.compile(r'\s')
return len(re.findall(regex_space, title)) + 1
def two_words_check(title):
import re
regex = re.compile(r'([A-Z]\w+)\s[a-z]')
match = re.search(regex, title)
if match:
return match.group(1)
else:
return title
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.